target
stringlengths
5
300
feat_repo_name
stringlengths
6
76
text
stringlengths
26
1.05M
test/integration/production-swcminify/pages/error-in-browser-render-status-code.js
azukaru/next.js
import React from 'react' export default class ErrorInRenderPage extends React.Component { render() { if (typeof window !== 'undefined') { const error = new Error('An Expected error occurred') // This will be extracted by getInitialProps in the _error page, // which will result in a different error message being rendered. error.statusCode = 404 throw error } return <div /> } }
src/routes/dashboardPages/databaseView/databaseView.js
bhavik3jain/LibertyMutual320Project
import React, { Component } from 'react'; import $ from "jquery"; import Panel from 'react-bootstrap/lib/Panel'; import Alert from 'react-bootstrap/lib/Alert'; import Button from 'react-bootstrap/lib/Button'; import OverlayTrigger from 'react-bootstrap/lib/OverlayTrigger'; import Tooltip from 'react-bootstrap/lib/Tooltip'; import Popover from 'react-bootstrap/lib/Popover'; import Modal, { Footer, Header, Title, Body } from 'react-bootstrap/lib/Modal'; import PageHeader from 'react-bootstrap/lib/PageHeader'; import { sendXHR } from '../../../core/util.js'; import s from './dbView.css'; import history from '../../../core/history'; class DatabaseView extends Component { constructor(props) { super(props); this.state = { M_DL_DR_SCHED_RN: false, M_DL_DR_STEP_RN: false, M_DL_DR_STEP_RN_GN: false, M_DL_DR_STEP_RN_SID: false, M_DL_DR_STEP_DTL_RN: false, M_UD_DR_SCHED_STTS_RN_AID : false, M_UD_DR_SCHED_VAL_END_RN_AID : false, M_UD_DR_SCHED_VAL_START_RN_AID : false, M_UD_DR_SCHED_SLA_AID : false, M_UD_DR_SCHED_SLA_RN : false, M_UD_DR_STEP_DTL_RN_GN : false, M_UD_DR_STEP_DTL_RN_STPDTLID : false, M_UD_DR_STEP_ASI_SID : false, M_UD_DR_STEP_ASI_RN_SID : false, M_UD_DR_STEP_ASI_RN_GN : false, M_UD_DR_SCHED_START_RN_AID: false, //to do// M_UD_DR_STEP_ASI_RN: false, hiddenTextBox: false, hiddenDropBox: false, user_id: "", reviewer: "", view: true, edit: false, delete: false, showModal: false, }; this.handleMacroFormType = this.handleMacroFormType.bind(this); this.handleMacroType = this.handleMacroType.bind(this); } handleReviewer(id){ switch(id){ case 'A': this.setState({reviewer: 'bhavik.jain'}); break; case 'B': this.setState({reviewer: 'maya.bergandy'}); break; case 'C': this.setState({reviewer: 'matthew.hinsley'}); break; case 'D': this.setState({reviewer: 'tony.gao'}); break; case 'E': this.setState({reviewer: 'zachary.tousignant'}); break; case 'F': this.setState({reviewer: 'bryce.bodleygomes'}); break; case 'G': this.setState({reviewer: 'adrian.povedamckay'}); break; case 'H': this.setState({reviewer: 'chenhao.huang'}); break; case 'I': this.setState({reviewer: 'michael.schiller'}); break; case 'J': this.setState({reviewer: 'kevin.silva'}); break; default: this.setState({reviewer: 'bhavik.jain'}); } } getUserId(cb){ sendXHR("POST", "http://localhost:3001/readfile", "", (xhr) => { cb(JSON.parse(xhr.responseText)); }); } componentDidMount() { this.getUserId((data) => { this.setState({"user_id": data.user_id}); }); } getTrueState(){ for(var key in this.state){ if (key.substr(0,2) === "M_"){ if (this.state[key]){ return key } } } } tb(){ if (document.getElementById('blankCheckbox').checked){ this.setState({hiddenTextBox: true}); this.setState({hiddenDropBox: true}); } else { this.setState({hiddenTextBox: false}); this.setState({hiddenDropBox: false}); } } runMacro() { var textbox = $('#ta').val(); var macroName = this.getTrueState(); var test = $("#" + macroName).serializeArray(); var parameters = []; for(var val in test) { var value = test[val].value; if(isNaN(parseInt(value)) || value.includes("-") || value.includes(":")) { value = "\'" + value + "\'"; parameters.push(value); } else { parameters.push(value); } } var sql_call = 'CALL ' + macroName + "(" + parameters.join(", ") + ")"; if(document.getElementById('blankCheckbox').checked) { const new_parameters = parameters.map((value) => {return "'" + value + "'"}); var new_sql_call = 'CALL ' + macroName + "(" + new_parameters + ")"; var query = "INSERT INTO PeerReview (MacroInstanceID, ReviewerID, State, PeerReviewComment, SQL_CALL, SubmittedBy)" + "values " + "( " + "(select MAX(MacroInstanceID) + 100 as MacroInstanceID from PeerReview AS MacroInstanceID) " + ", " + "'" + this.state.reviewer + "'" + ", " + "'" + "Under Review" + "'" + ", " + "'" + textbox + "'" + ", " + "'" + new_sql_call + "'" + ", " + "'" + this.state.user_id + "'" + ");" sendXHR("POST", "http://localhost:3001/sql_request", query, (xhr) => { JSON.parse(xhr.responseText); }); } else { sendXHR("POST", "http://localhost:3001/sql_request", sql_call, (xhr) => { JSON.parse(xhr.responseText); }); const new_parameters = parameters.map((value) => {return "'" + value + "'"}); var query = "INSERT INTO CHANGE_LOG (DATE_TIME, Owner, MacroName, Parameters, PeerReviewedBy) values ( NOW() " + ", " + "'" + this.state.user_id + "'" + ", " + "'" + macroName + "'" + ", " + parameters.join(", ") + ", " + "'" + "No Peer Review" + "'" + ");" sendXHR("POST", "http://localhost:3001/sql_request", query, (xhr) => { JSON.parse(xhr.responseText); }); } alert("Success"); history.push('/app'); } handleMacroFormType(option) { switch (option) { case 'M_DL_DR_SCHED_RN': this.setState({M_DL_DR_SCHED_RN: true}); this.setState({M_DL_DR_STEP_RN: false}); this.setState({M_DL_DR_STEP_RN_GN: false}); this.setState({M_DL_DR_STEP_RN_SID: false}); this.setState({M_DL_DR_STEP_DTL_RN: false}); this.setState({M_UD_DR_SCHED_STTS_RN_AID: false}); this.setState({M_UD_DR_SCHED_VAL_END_RN_AID: false}); this.setState({M_UD_DR_SCHED_VAL_START_RN_AID: false}); this.setState({M_UD_DR_SCHED_SLA_AID: false}); this.setState({M_UD_DR_SCHED_SLA_RN: false}); this.setState({M_UD_DR_STEP_DTL_RN_GN: false}); this.setState({M_UD_DR_STEP_DTL_RN_STPDTLID: false}); this.setState({M_UD_DR_STEP_ASI_SID: false}); this.setState({M_UD_DR_STEP_ASI_RN_SID: false}); this.setState({M_UD_DR_STEP_ASI_RN: false}); this.setState({M_UD_DR_STEP_ASI_RN_GN: false}); break; case 'M_DL_DR_STEP_RN': this.setState({M_DL_DR_SCHED_RN: false}); this.setState({M_DL_DR_STEP_RN: true}); this.setState({M_DL_DR_STEP_RN_GN: false}); this.setState({M_DL_DR_STEP_RN_SID: false}); this.setState({M_DL_DR_STEP_DTL_RN: false}); this.setState({M_UD_DR_SCHED_STTS_RN_AID: false}); this.setState({M_UD_DR_SCHED_VAL_END_RN_AID: false}); this.setState({M_UD_DR_SCHED_VAL_START_RN_AID: false}); this.setState({M_UD_DR_SCHED_SLA_AID: false}); this.setState({M_UD_DR_SCHED_SLA_RN: false}); this.setState({M_UD_DR_STEP_DTL_RN_GN: false}); this.setState({M_UD_DR_STEP_DTL_RN_STPDTLID: false}); this.setState({M_UD_DR_STEP_ASI_SID: false}); this.setState({M_UD_DR_STEP_ASI_RN_SID: false}); this.setState({M_UD_DR_STEP_ASI_RN: false}); this.setState({M_UD_DR_STEP_ASI_RN_GN: false}); break; case 'M_DL_DR_STEP_RN_GN': this.setState({M_DL_DR_SCHED_RN: false}); this.setState({M_DL_DR_STEP_RN: false}); this.setState({M_DL_DR_STEP_RN_GN: true}); this.setState({M_DL_DR_STEP_RN_SID: false}); this.setState({M_DL_DR_STEP_DTL_RN: false}); this.setState({M_UD_DR_SCHED_STTS_RN_AID: false}); this.setState({M_UD_DR_SCHED_VAL_END_RN_AID: false}); this.setState({M_UD_DR_SCHED_VAL_START_RN_AID: false}); this.setState({M_UD_DR_SCHED_SLA_AID: false}); this.setState({M_UD_DR_SCHED_SLA_RN: false}); this.setState({M_UD_DR_STEP_DTL_RN_GN: false}); this.setState({M_UD_DR_STEP_DTL_RN_STPDTLID: false}); this.setState({M_UD_DR_STEP_ASI_SID: false}); this.setState({M_UD_DR_STEP_ASI_RN_SID: false}); this.setState({M_UD_DR_STEP_ASI_RN: false}); this.setState({M_UD_DR_STEP_ASI_RN_GN: false}); break; case 'M_DL_DR_STEP_RN_SID': this.setState({M_DL_DR_SCHED_RN: false}); this.setState({M_DL_DR_STEP_RN: false}); this.setState({M_DL_DR_STEP_RN_GN: false}); this.setState({M_DL_DR_STEP_RN_SID: true}); this.setState({M_DL_DR_STEP_DTL_RN: false}); this.setState({M_UD_DR_SCHED_STTS_RN_AID: false}); this.setState({M_UD_DR_SCHED_VAL_END_RN_AID: false}); this.setState({M_UD_DR_SCHED_VAL_START_RN_AID: false}); this.setState({M_UD_DR_SCHED_SLA_AID: false}); this.setState({M_UD_DR_SCHED_SLA_RN: false}); this.setState({M_UD_DR_STEP_DTL_RN_GN: false}); this.setState({M_UD_DR_STEP_DTL_RN_STPDTLID: false}); this.setState({M_UD_DR_STEP_ASI_SID: false}); this.setState({M_UD_DR_STEP_ASI_RN_SID: false}); this.setState({M_UD_DR_STEP_ASI_RN: false}); this.setState({M_UD_DR_STEP_ASI_RN_GN: false}); break; case 'M_DL_DR_STEP_DTL_RN': this.setState({M_DL_DR_SCHED_RN: false}); this.setState({M_DL_DR_STEP_RN: false}); this.setState({M_DL_DR_STEP_RN_GN: false}); this.setState({M_DL_DR_STEP_RN_SID: false}); this.setState({M_DL_DR_STEP_DTL_RN: true}); this.setState({M_UD_DR_SCHED_STTS_RN_AID: false}); this.setState({M_UD_DR_SCHED_VAL_END_RN_AID: false}); this.setState({M_UD_DR_SCHED_VAL_START_RN_AID: false}); this.setState({M_UD_DR_SCHED_SLA_AID: false}); this.setState({M_UD_DR_SCHED_SLA_RN: false}); this.setState({M_UD_DR_STEP_DTL_RN_GN: false}); this.setState({M_UD_DR_STEP_DTL_RN_STPDTLID: false}); this.setState({M_UD_DR_STEP_ASI_SID: false}); this.setState({M_UD_DR_STEP_ASI_RN_SID: false}); this.setState({M_UD_DR_STEP_ASI_RN: false}); this.setState({M_UD_DR_STEP_ASI_RN_GN: false}); break; case 'M_UD_DR_SCHED_STTS_RN_AID': this.setState({M_DL_DR_SCHED_RN: false}); this.setState({M_DL_DR_STEP_RN: false}); this.setState({M_DL_DR_STEP_RN_GN: false}); this.setState({M_DL_DR_STEP_RN_SID: false}); this.setState({M_DL_DR_STEP_DTL_RN: false}); this.setState({M_UD_DR_SCHED_STTS_RN_AID: true}); this.setState({M_UD_DR_SCHED_VAL_END_RN_AID: false}); this.setState({M_UD_DR_SCHED_VAL_START_RN_AID: false}); this.setState({M_UD_DR_SCHED_SLA_AID: false}); this.setState({M_UD_DR_SCHED_SLA_RN: false}); this.setState({M_UD_DR_STEP_DTL_RN_GN: false}); this.setState({M_UD_DR_STEP_DTL_RN_STPDTLID: false}); this.setState({M_UD_DR_STEP_ASI_SID: false}); this.setState({M_UD_DR_STEP_ASI_RN_SID: false}); this.setState({M_UD_DR_STEP_ASI_RN: false}); this.setState({M_UD_DR_STEP_ASI_RN_GN: false}); break; case 'M_UD_DR_SCHED_VAL_END_RN_AID': this.setState({M_DL_DR_SCHED_RN: false}); this.setState({M_DL_DR_STEP_RN: false}); this.setState({M_DL_DR_STEP_RN_GN: false}); this.setState({M_DL_DR_STEP_RN_SID: false}); this.setState({M_DL_DR_STEP_DTL_RN: false}); this.setState({M_UD_DR_SCHED_STTS_RN_AID: false}); this.setState({M_UD_DR_SCHED_VAL_END_RN_AID: true}); this.setState({M_UD_DR_SCHED_VAL_START_RN_AID: false}); this.setState({M_UD_DR_SCHED_SLA_AID: false}); this.setState({M_UD_DR_SCHED_SLA_RN: false}); this.setState({M_UD_DR_STEP_DTL_RN_GN: false}); this.setState({M_UD_DR_STEP_DTL_RN_STPDTLID: false}); this.setState({M_UD_DR_STEP_ASI_SID: false}); this.setState({M_UD_DR_STEP_ASI_RN_SID: false}); this.setState({M_UD_DR_STEP_ASI_RN: false}); this.setState({M_UD_DR_STEP_ASI_RN_GN: false}); break; case 'M_UD_DR_SCHED_VAL_START_RN_AID': this.setState({M_DL_DR_SCHED_RN: false}); this.setState({M_DL_DR_STEP_RN: false}); this.setState({M_DL_DR_STEP_RN_GN: false}); this.setState({M_DL_DR_STEP_RN_SID: false}); this.setState({M_DL_DR_STEP_DTL_RN: false}); this.setState({M_UD_DR_SCHED_STTS_RN_AID: false}); this.setState({M_UD_DR_SCHED_VAL_END_RN_AID: false}); this.setState({M_UD_DR_SCHED_VAL_START_RN_AID: true}); this.setState({M_UD_DR_SCHED_SLA_AID: false}); this.setState({M_UD_DR_SCHED_SLA_RN: false}); this.setState({M_UD_DR_STEP_DTL_RN_GN: false}); this.setState({M_UD_DR_STEP_DTL_RN_STPDTLID: false}); this.setState({M_UD_DR_STEP_ASI_SID: false}); this.setState({M_UD_DR_STEP_ASI_RN_SID: false}); this.setState({M_UD_DR_STEP_ASI_RN: false}); this.setState({M_UD_DR_STEP_ASI_RN_GN: false}); break; case 'M_UD_DR_SCHED_SLA_AID': this.setState({M_DL_DR_SCHED_RN: false}); this.setState({M_DL_DR_STEP_RN: false}); this.setState({M_DL_DR_STEP_RN_GN: false}); this.setState({M_DL_DR_STEP_RN_SID: false}); this.setState({M_DL_DR_STEP_DTL_RN: false}); this.setState({M_UD_DR_SCHED_STTS_RN_AID: false}); this.setState({M_UD_DR_SCHED_VAL_END_RN_AID: false}); this.setState({M_UD_DR_SCHED_VAL_START_RN_AID: false}); this.setState({M_UD_DR_SCHED_SLA_AID: true}); this.setState({M_UD_DR_SCHED_SLA_RN: false}); this.setState({M_UD_DR_STEP_DTL_RN_GN: false}); this.setState({M_UD_DR_STEP_DTL_RN_STPDTLID: false}); this.setState({M_UD_DR_STEP_ASI_SID: false}); this.setState({M_UD_DR_STEP_ASI_RN_SID: false}); this.setState({M_UD_DR_STEP_ASI_RN: false}); this.setState({M_UD_DR_STEP_ASI_RN_GN: false}); break; case 'M_UD_DR_SCHED_SLA_RN': this.setState({M_DL_DR_SCHED_RN: false}); this.setState({M_DL_DR_STEP_RN: false}); this.setState({M_DL_DR_STEP_RN_GN: false}); this.setState({M_DL_DR_STEP_RN_SID: false}); this.setState({M_DL_DR_STEP_DTL_RN: false}); this.setState({M_UD_DR_SCHED_STTS_RN_AID: false}); this.setState({M_UD_DR_SCHED_VAL_END_RN_AID: false}); this.setState({M_UD_DR_SCHED_VAL_START_RN_AID: false}); this.setState({M_UD_DR_SCHED_SLA_AID: false}); this.setState({M_UD_DR_SCHED_SLA_RN: true}); this.setState({M_UD_DR_STEP_DTL_RN_GN: false}); this.setState({M_UD_DR_STEP_DTL_RN_STPDTLID: false}); this.setState({M_UD_DR_STEP_ASI_SID: false}); this.setState({M_UD_DR_STEP_ASI_RN_SID: false}); this.setState({M_UD_DR_STEP_ASI_RN: false}); this.setState({M_UD_DR_STEP_ASI_RN_GN: false}); break; case 'M_UD_DR_STEP_DTL_RN_GN': this.setState({M_DL_DR_SCHED_RN: false}); this.setState({M_DL_DR_STEP_RN: false}); this.setState({M_DL_DR_STEP_RN_GN: false}); this.setState({M_DL_DR_STEP_RN_SID: false}); this.setState({M_DL_DR_STEP_DTL_RN: false}); this.setState({M_UD_DR_SCHED_STTS_RN_AID: false}); this.setState({M_UD_DR_SCHED_VAL_END_RN_AID: false}); this.setState({M_UD_DR_SCHED_VAL_START_RN_AID: false}); this.setState({M_UD_DR_SCHED_SLA_AID: false}); this.setState({M_UD_DR_SCHED_SLA_RN: false}); this.setState({M_UD_DR_STEP_DTL_RN_GN: true}); this.setState({M_UD_DR_STEP_DTL_RN_STPDTLID: false}); this.setState({M_UD_DR_STEP_ASI_SID: false}); this.setState({M_UD_DR_STEP_ASI_RN_SID: false}); this.setState({M_UD_DR_STEP_ASI_RN: false}); this.setState({M_UD_DR_STEP_ASI_RN_GN: false}); break; case 'M_UD_DR_STEP_DTL_RN_STPDTLID': this.setState({M_DL_DR_SCHED_RN: false}); this.setState({M_DL_DR_STEP_RN: false}); this.setState({M_DL_DR_STEP_RN_GN: false}); this.setState({M_DL_DR_STEP_RN_SID: false}); this.setState({M_DL_DR_STEP_DTL_RN: false}); this.setState({M_UD_DR_SCHED_STTS_RN_AID: false}); this.setState({M_UD_DR_SCHED_VAL_END_RN_AID: false}); this.setState({M_UD_DR_SCHED_VAL_START_RN_AID: false}); this.setState({M_UD_DR_SCHED_SLA_AID: false}); this.setState({M_UD_DR_SCHED_SLA_RN: false}); this.setState({M_UD_DR_STEP_DTL_RN_GN: false}); this.setState({M_UD_DR_STEP_DTL_RN_STPDTLID: true}); this.setState({M_UD_DR_STEP_ASI_SID: false}); this.setState({M_UD_DR_STEP_ASI_RN_SID: false}); this.setState({M_UD_DR_STEP_ASI_RN: false}); this.setState({M_UD_DR_STEP_ASI_RN_GN: false}); break; case 'M_UD_DR_STEP_ASI_SID': this.setState({M_DL_DR_SCHED_RN: false}); this.setState({M_DL_DR_STEP_RN: false}); this.setState({M_DL_DR_STEP_RN_GN: false}); this.setState({M_DL_DR_STEP_RN_SID: false}); this.setState({M_DL_DR_STEP_DTL_RN: false}); this.setState({M_UD_DR_SCHED_STTS_RN_AID: false}); this.setState({M_UD_DR_SCHED_VAL_END_RN_AID: false}); this.setState({M_UD_DR_SCHED_VAL_START_RN_AID: false}); this.setState({M_UD_DR_SCHED_SLA_AID: false}); this.setState({M_UD_DR_SCHED_SLA_RN: false}); this.setState({M_UD_DR_STEP_DTL_RN_GN: false}); this.setState({M_UD_DR_STEP_DTL_RN_STPDTLID: false}); this.setState({M_UD_DR_STEP_ASI_SID: true}); this.setState({M_UD_DR_STEP_ASI_RN_SID: false}); this.setState({M_UD_DR_STEP_ASI_RN: false}); this.setState({M_UD_DR_STEP_ASI_RN_GN: false}); break; case 'M_UD_DR_STEP_ASI_RN_SID': this.setState({M_DL_DR_SCHED_RN: false}); this.setState({M_DL_DR_STEP_RN: false}); this.setState({M_DL_DR_STEP_RN_GN: false}); this.setState({M_DL_DR_STEP_RN_SID: false}); this.setState({M_DL_DR_STEP_DTL_RN: false}); this.setState({M_UD_DR_SCHED_STTS_RN_AID: false}); this.setState({M_UD_DR_SCHED_VAL_END_RN_AID: false}); this.setState({M_UD_DR_SCHED_VAL_START_RN_AID: false}); this.setState({M_UD_DR_SCHED_SLA_AID: false}); this.setState({M_UD_DR_SCHED_SLA_RN: false}); this.setState({M_UD_DR_STEP_DTL_RN_GN: false}); this.setState({M_UD_DR_STEP_DTL_RN_STPDTLID: false}); this.setState({M_UD_DR_STEP_ASI_SID: false}); this.setState({M_UD_DR_STEP_ASI_RN_SID: true}); this.setState({M_UD_DR_STEP_ASI_RN: false}); this.setState({M_UD_DR_STEP_ASI_RN_GN: false}); break; case 'M_UD_DR_STEP_ASI_RN': this.setState({M_DL_DR_SCHED_RN: false}); this.setState({M_DL_DR_STEP_RN: false}); this.setState({M_DL_DR_STEP_RN_GN: false}); this.setState({M_DL_DR_STEP_RN_SID: false}); this.setState({M_DL_DR_STEP_DTL_RN: false}); this.setState({M_UD_DR_SCHED_STTS_RN_AID: false}); this.setState({M_UD_DR_SCHED_VAL_END_RN_AID: false}); this.setState({M_UD_DR_SCHED_VAL_START_RN_AID: false}); this.setState({M_UD_DR_SCHED_SLA_AID: false}); this.setState({M_UD_DR_SCHED_SLA_RN: false}); this.setState({M_UD_DR_STEP_DTL_RN_GN: false}); this.setState({M_UD_DR_STEP_DTL_RN_STPDTLID: false}); this.setState({M_UD_DR_STEP_ASI_SID: false}); this.setState({M_UD_DR_STEP_ASI_RN_SID: false}); this.setState({M_UD_DR_STEP_ASI_RN: true}); this.setState({M_UD_DR_STEP_ASI_RN_GN: false}); break; case 'M_UD_DR_STEP_ASI_RN_GN': this.setState({M_DL_DR_SCHED_RN: false}); this.setState({M_DL_DR_STEP_RN: false}); this.setState({M_DL_DR_STEP_RN_GN: false}); this.setState({M_DL_DR_STEP_RN_SID: false}); this.setState({M_DL_DR_STEP_DTL_RN: false}); this.setState({M_UD_DR_SCHED_STTS_RN_AID: false}); this.setState({M_UD_DR_SCHED_VAL_END_RN_AID: false}); this.setState({M_UD_DR_SCHED_VAL_START_RN_AID: false}); this.setState({M_UD_DR_SCHED_SLA_AID: false}); this.setState({M_UD_DR_SCHED_SLA_RN: false}); this.setState({M_UD_DR_STEP_DTL_RN_GN: false}); this.setState({M_UD_DR_STEP_DTL_RN_STPDTLID: false}); this.setState({M_UD_DR_STEP_ASI_SID: false}); this.setState({M_UD_DR_STEP_ASI_RN_SID: false}); this.setState({M_UD_DR_STEP_ASI_RN: false}); this.setState({M_UD_DR_STEP_ASI_RN_GN: true}); break; default: this.setState({ M_DL_DR_SCHED_RN: false, M_DL_DR_STEP_RN: false, M_DL_DR_STEP_RN_GN: false, M_DL_DR_STEP_RN_SID: false, M_DL_DR_STEP_DTL_RN: false, M_UD_DR_SCHED_STTS_RN_AID : false, M_UD_DR_SCHED_VAL_END_RN_AID : false, M_UD_DR_SCHED_VAL_START_RN_AID : false, M_UD_DR_SCHED_SLA_AID : false, M_UD_DR_SCHED_SLA_RN : false, M_UD_DR_STEP_DTL_RN_GN : false, M_UD_DR_STEP_DTL_RN_STPDTLID : false, M_UD_DR_STEP_ASI_SID : false, M_UD_DR_STEP_ASI_RN_SID : false, M_UD_DR_STEP_ASI_RN_GN : false, }); } } handleMacroType(option){ switch(option){ case 'A': this.setState({view : true}); this.setState({edit : false}); this.setState({delete : false}); break; case 'B': this.setState({view : false}); this.setState({edit : true}); this.setState({delete : false}); break; case 'C': this.setState({view : false}); this.setState({edit : false}); this.setState({delete : true}); break; default: this.setState({ view : true, edit : false, delete : false, }); } } render() { return ( <div> <div className="row"> <div className="col-lg-12"> <PageHeader>Invoke Macro</PageHeader> </div> </div> <div className="row"> <div className="col-lg-4 "> <Panel header={<span>Actions</span>} > <Button className="btn btn-default btn-block" onClick={() =>{this.handleMacroType('A')}}> View </Button> <Button className="btn btn-primary btn-block" onClick={() =>{this.handleMacroType('B')}}> Edit </Button> <Button className="btn btn-danger btn-block" onClick={() =>{this.handleMacroType('C')}}> Delete </Button> </Panel> </div> {this.state.view ? <div className="col-lg-6"> <Panel header={<span>Macros</span>} > <input type="search" className="form-control" placeholder="Search..."></input> <select multiple className="form-control"> <option onClick={() =>{this.handleMacroFormType('A')}}>TBD</option> <option onClick={() =>{this.handleMacroFormType('B')}}>TBD</option> <option onClick={() =>{this.handleMacroFormType('C')}}>TBD</option> <option onClick={() =>{this.handleMacroFormType('D')}}>TBD</option> <option onClick={() =>{this.handleMacroFormType('E')}}>TBD</option> </select> </Panel> </div>: null } {this.state.delete ? <div className="col-lg-6"> <Panel header={<span>Macros</span>} > <input type="search" className="form-control" placeholder="Search..."></input> <select multiple className="form-control"> <option onClick={() =>{this.handleMacroFormType('M_DL_DR_SCHED_RN')}}>M_DL_DR_SCHED_RN</option> <option onClick={() =>{this.handleMacroFormType('M_DL_DR_STEP_RN')}}>M_DL_DR_STEP_RN</option> <option onClick={() =>{this.handleMacroFormType('M_DL_DR_STEP_RN_GN')}}>M_DL_DR_STEP_RN_GN </option> <option onClick={() =>{this.handleMacroFormType('M_DL_DR_STEP_RN_SID')}}>M_DL_DR_STEP_RN_SID</option> <option onClick={() =>{this.handleMacroFormType('M_DL_DR_STEP_DTL_RN')}}>M_DL_DR_STEP_DTL_RN </option> </select> </Panel> </div>: null } {this.state.edit ? <div className="col-lg-6"> <Panel header={<span>Macros</span>} > <input type="search" className="form-control" placeholder="Search..."></input> <select multiple className="form-control"> <option onClick={() =>{this.handleMacroFormType('M_UD_DR_SCHED_STTS_RN_AID')}}>M_UD_DR_SCHED_STTS_RN_AID</option> <option onClick={() =>{this.handleMacroFormType('M_UD_DR_SCHED_VAL_END_RN_AID')}}>M_UD_DR_SCHED_VAL_END_RN_AID</option> <option onClick={() =>{this.handleMacroFormType('M_UD_DR_SCHED_VAL_START_RN_AID')}}>M_UD_DR_SCHED_VAL_START_RN_AID</option> <option onClick={() =>{this.handleMacroFormType('M_UD_DR_SCHED_SLA_AID')}}>M_UD_DR_SCHED_SLA_AID</option> <option onClick={() =>{this.handleMacroFormType('M_UD_DR_SCHED_SLA_RN')}}>M_UD_DR_SCHED_SLA_RN</option> <option onClick={() =>{this.handleMacroFormType('M_UD_DR_STEP_DTL_RN_GN')}}>M_UD_DR_STEP_DTL_RN_GN</option> <option onClick={() =>{this.handleMacroFormType('M_UD_DR_STEP_DTL_RN_STPDTLID')}}>M_UD_DR_STEP_DTL_RN_STPDTLID</option> <option onClick={() =>{this.handleMacroFormType('M_UD_DR_STEP_ASI_SID')}}>M_UD_DR_STEP_ASI_SID</option> <option onClick={() =>{this.handleMacroFormType('M_UD_DR_STEP_ASI_RN_SID')}}>M_UD_DR_STEP_ASI_RN_SID</option> <option onClick={() =>{this.handleMacroFormType('M_UD_DR_STEP_ASI_RN')}}>M_UD_DR_STEP_ASI_RN</option> <option onClick={() =>{this.handleMacroFormType('M_UD_DR_STEP_ASI_RN_GN')}}>M_UD_DR_STEP_ASI_RN_GN</option> </select> </Panel> </div>: null } </div> {this.state.M_DL_DR_SCHED_RN ? <div className="col-lg-10"> <Panel header={<span>Delete Drive Schedule by Run Name</span>} > <form className="form-inline" id="M_DL_DR_SCHED_RN"> <div className="form-group"> <label for="exampleInputName2">Param 1: </label> <input type="text" className="form-control" name="RUN_NAME" id="RUN_NAME" placeholder="Run Name"></input> </div> </form> </Panel> </div> : null } {this.state.M_DL_DR_STEP_RN ? <div className="col-lg-10"> <Panel header={<span>Delete Driver Step by Run Name</span>} > <form className="form-inline" id="M_DL_DR_STEP_RN"> <div className="form-group"> <label for="exampleInputName2">Param 1: </label> <input type="text" className="form-control" name="RUN_NAME" id="RUN_NAME" placeholder="Run Name"> </input> </div> </form> </Panel> </div> : null } {this.state.M_DL_DR_STEP_RN_GN ? <div className="col-lg-10"> <Panel header={<span>Delete Driver Step by Run Name and Group Number</span>} > <form className="form-inline" id="M_DL_DR_STEP_RN_GN"> <div className="form-group"> <label for="exampleInputName2">Param 1: </label> <input type="text" className="form-control" name="RUN_NAME" id="RUN_NAME" placeholder="Run Name"></input> </div> <div className="form-group"> <label for="exampleInputName2">Param 2: </label> <input type="text" className="form-control" name="GROUP_NUMBER" id="GROUP_NUMBER" placeholder="Group Number"></input> </div> </form> </Panel> </div> : null } {this.state.M_DL_DR_STEP_RN_SID ? <div className="col-lg-10"> <Panel header={<span>Delete Driver Step by Run Name and Driver Step ID</span>} > <form className="form-inline" id="M_DL_DR_STEP_RN_SID"> <div className="form-group"> <label for="exampleInputName2">Param 1: </label> <input type="text" className="form-control" name="RUN_NAME" id="RUN_NAME" placeholder="Run Name"></input> </div> <div className="form-group"> <label for="exampleInputName2">Param 2: </label> <input type="text" className="form-control" name="DRIVER_STEP_ID" id="DRIVER_STEP_ID" placeholder="Driver Step ID"></input> </div> </form> </Panel> </div> : null } {this.state.M_DL_DR_STEP_DTL_RN ? <div className="col-lg-10"> <Panel header={<span>Delete Driver Step Detail Entry by Run Name</span>} > <form className="form-inline" id="M_DL_DR_STEP_DTL_RN"> <div className="form-group"> <label for="exampleInputName2">Param 1: </label> <input type="text" className="form-control" name="RUN_NAME" id="RUN_NAME" placeholder="Run Name"></input> </div> </form> </Panel> </div> : null } {this.state.M_UD_DR_SCHED_STTS_RN_AID ? <div className="col-lg-10"> <Panel header={<span>Update Driver Schedule Status by Run Name and Audit ID</span>} > <form className="form-inline" id="M_UD_DR_SCHED_STTS_RN_AID"> <div className="form-group"> <label for="exampleInputName2">Param 1: </label> <input type="text" className="form-control" name="RUN_NAME" id="RUN_NAME" placeholder="Run Name"></input> </div> <div className="form-group"> <label for="exampleInputName2">Param 2: </label> <input type="text" className="form-control" name="AUDIT_ID" id="AUDIT_ID" placeholder="Audit ID"></input> </div> <div className="form-group"> <label for="exampleInputName2">Param 3: </label> <input type="text" className="form-control" name="STATUS" id="STATUS" placeholder="Status"></input> </div> </form> </Panel> </div> : null } {this.state.M_UD_DR_SCHED_VAL_END_RN_AID ? <div className="col-lg-10"> <Panel header={<span>Update Driver Schedule Table Valuation End Date by Run Name and Audit ID</span>} > <form className="form-inline" id="M_UD_DR_SCHED_VAL_END_RN_AID"> <div className="form-group"> <label for="exampleInputName2">Param 1: </label> <input type="text" className="form-control" name="RUN_NAME" id="RUN_NAME" placeholder="Run Name"></input> </div> <div className="form-group"> <label for="exampleInputName2">Param 2: </label> <input type="text" className="form-control" name="AUDIT_ID" id="AUDIT_ID" placeholder="Audit ID"></input> </div> <div className="form-group"> <label for="exampleInputName2">Param 3: </label> <input type="text" className="form-control" name="VAL_END_TIME" id="VAL_END_TIME" placeholder="End Time"></input> </div> </form> </Panel> </div> : null } {this.state.M_UD_DR_SCHED_VAL_START_RN_AID ? <div className="col-lg-10"> <Panel header={<span>Update Driver Schedule Table Valuation Start Date by Run Name and Audit ID</span>} > <form className="form-inline" id="M_UD_DR_SCHED_VAL_START_RN_AID"> <div className="form-group"> <label for="exampleInputName2">Param 1: </label> <input type="text" className="form-control" name="VAL_START_RUN_NAME" id="VAL_START_RUN_NAME" placeholder="Run Name"></input> </div> <div className="form-group"> <label for="exampleInputName2">Param 2: </label> <input type="text" className="form-control" name="AUDIT_ID" id="AUDIT_ID" placeholder="Audit ID"></input> </div> <div className="form-group"> <label for="exampleInputName2">Param 3: </label> <input type="text" className="form-control" name="VAL_START_TIME" id="VAL_START_TIME" placeholder="Start Time"></input> </div> </form> </Panel> </div> : null } {this.state.M_UD_DR_SCHED_SLA_AID ? <div className="col-lg-10"> <Panel header={<span>Update Driver Schedule SLA Date and Time by Audit ID</span>} > <form className="form-inline" id="M_UD_DR_SCHED_SLA_AID"> <div className="form-group"> <label for="exampleInputName2">Param 1: </label> <input type="text" className="form-control" name="SLA_DATE" id="SLA_DATE" placeholder="SLA Date"></input> </div> <div className="form-group"> <label for="exampleInputName2">Param 2: </label> <input type="text" className="form-control" name="SLA_TIME" id="SLA_TIME" placeholder="SLA Time"></input> </div> <div className="form-group"> <label for="exampleInputName2">Param 3: </label> <input type="text" className="form-control" name="AUDIT_ID" id="AUDIT_ID" placeholder="Audit ID"></input> </div> </form> </Panel> </div> : null } {this.state.M_UD_DR_SCHED_SLA_RN ? <div className="col-lg-10"> <Panel header={<span>Update Driver Schedule SLA Date and Time by Run Name</span>} > <form className="form-inline" id="M_UD_DR_SCHED_SLA_RN"> <div className="form-group"> <label for="exampleInputName2">Param 1: </label> <input type="text" className="form-control" name="SLA_TIME" id="SLA_TIME" placeholder="SLA Time"></input> </div> <div className="form-group"> <label for="exampleInputName2">Param 2: </label> <input type="text" className="form-control" name="RUN_NAME" id="RUN_NAME" placeholder="Run Name"></input> </div> </form> </Panel> </div> : null } {this.state.M_UD_DR_STEP_DTL_RN_GN ? <div className="col-lg-10"> <Panel header={<span>Update Driver Step Detail Status by Run Name and Group Number</span>} > <form className="form-inline" id="M_UD_DR_STEP_DTL_RN_GN"> <div className="form-group"> <label for="exampleInputName2">Param 1: </label> <input type="text" className="form-control" name="RUN_NAME" id="RUN_NAME" placeholder="Run Name"></input> </div> <div className="form-group"> <label for="exampleInputName2">Param 2: </label> <input type="text" className="form-control" name="GROUP_NUMBER" id="GROUP_NUMBER" placeholder="Group Number"></input> </div> <div className="form-group"> <label for="exampleInputName2">Param 3: </label> <input type="text" className="form-control" name="STATUS" id="STATUS" placeholder="Status"></input> </div> </form> </Panel> </div> : null } {this.state.M_UD_DR_STEP_DTL_RN_STPDTLID ? <div className="col-lg-10"> <Panel header={<span>Update Driver Step Detail Run Status by Run Name and Driver Step Detail ID</span>} > <form className="form-inline" id="M_UD_DR_STEP_DTL_RN_STPDTLID"> <div className="form-group"> <label for="exampleInputName2">Param 1: </label> <input type="text" className="form-control" name="RUN_NAME" id="RUN_NAME" placeholder="Run Name"></input> </div> <div className="form-group"> <label for="exampleInputName2">Param 2: </label> <input type="text" className="form-control" name="STEP_DETAIL" id="STEP_DETAIL" placeholder="Driver Step Detail ID"></input> </div> <div className="form-group"> <label for="exampleInputName2">Param 3: </label> <input type="text" className="form-control" name="STATUS" id="STATUS" placeholder="Status"></input> </div> </form> </Panel> </div> : null } {this.state.M_UD_DR_STEP_ASI_SID ? <div className="col-lg-10"> <Panel header={<span>Update Driver Step Table Active Step Indicator by Driver Step ID</span>} > <form className="form-inline" id="M_UD_DR_STEP_ASI_SID"> <div className="form-group"> <label for="exampleInputName2">Param 1: </label> <input type="text" className="form-control" name="DRIVER_STEP_ID" id="DRIVER_STEP_ID" placeholder="Driver Step ID"></input> </div> <div className="form-group"> <label for="exampleInputName2">Param 2: </label> <input type="text" className="form-control" name="ACTIVE_STEP_INDICATOR" id="ACTIVE_STEP_INDICATOR" placeholder="Active Step Indicator"></input> </div> </form> </Panel> </div> : null } {this.state.M_UD_DR_STEP_ASI_RN ? <div className="col-lg-10"> <Panel header={<span>Update Driver Table Active Step Indicator by Run Name</span>} > <form className="form-inline" id="M_UD_DR_STEP_ASI_RN"> <div className="form-group"> <label for="exampleInputName2">Param 1: </label> <input type="text" className="form-control" name="RUN_NAME" id="RUN_NAME" placeholder="Run Name"></input> </div> <div className="form-group"> <label for="exampleInputName2">Param 2: </label> <input type="text" className="form-control" name="ACTIVE_STEP_INDICATOR" id="ACTIVE_STEP_INDICATOR" placeholder="Active Step Indicator"></input> </div> </form> </Panel> </div> : null } {this.state.M_UD_DR_STEP_ASI_RN_SID ? <div className="col-lg-10"> <Panel header={<span>Update Driver Table Active Step Indicator by Run Name and Step ID</span>} > <form className="form-inline" id="M_UD_DR_STEP_ASI_RN_SID"> <div className="form-group"> <label for="exampleInputName2">Param 1: </label> <input type="text" className="form-control" name="RUN_NAME" id="RUN_NAME" placeholder="Run Name"></input> </div> <div> <label for="exampleInputName2">Param 2: </label> <input type="text" className="form-control" name="DRIVER_STEP_ID" id="DRIVER_STEP_ID" placeholder="Driver Step ID"></input> </div> <div className="form-group"> <label for="exampleInputName2">Param 3: </label> <input type="text" className="form-control" name="ACTIVE_STEP_INDICATOR" id="ACTIVE_STEP_INDICATOR" placeholder="Active Step Indicator"></input> </div> </form> </Panel> </div> : null } {this.state.M_UD_DR_STEP_ASI_RN_GN ? <div className="col-lg-10"> <Panel header={<span>Update Driver Table Active Step Indicator by Run Name and Group Number</span>} > <form className="form-inline" id="M_UD_DR_STEP_ASI_RN_GN"> <div className="form-group"> <label for="exampleInputName2">Param 1: </label> <input type="text" className="form-control" name="RUN_NAME" id="RUN_NAME" placeholder="Run Name"></input> </div> <div> <label for="exampleInputName2">Param 2: </label> <input type="text" className="form-control" name="GROUP_NUMBER" id="GROUP_NUMBER" placeholder="Group Number"></input> </div> <div className="form-group"> <label for="exampleInputName2">Param 3: </label> <input type="text" className="form-control" name="ACTIVE_STEP_INDEX" id="ACTIVE_STEP_INDEX" placeholder="Active Step Index"></input> </div> </form> </Panel> </div> : null } <div className="col-lg-8 col-lg-offset-4"> <div className="checkbox"> <label> <input type="checkbox" id="blankCheckbox" value="option1" aria-label="Peer Review" onClick={() =>{this.tb()}}></input> Peer Review </label> </div> </div> <br/> {this.state.hiddenTextBox ? <div className="col-lg-5"> <Panel header={<span>Enter Comments</span>} > <textarea id='ta' rows="4" cols="50" placeholder="Enter some comments"></textarea> </Panel> </div> : null } {this.state.hiddenDropBox ? <div className="col-lg-7"> <Panel header={<span>Select Reviewer</span>} > <select multiple id="myOptions" className="form-control"> <option value='bhavik.jain' onClick={() =>{this.handleReviewer('A')}}>bhavik.jain</option> <option value='maya.bergandy' onClick={() =>{this.handleReviewer('B')}}>maya.bergandy</option> <option value='matthew.hinsley' onClick={() =>{this.handleReviewer('C')}}>matthew.hinsley</option> <option value='tony.gao' onClick={() =>{this.handleReviewer('D')}}>tony.gao</option> <option value='zachary.tousignant' onClick={() =>{this.handleReviewer('E')}}>zachary.tousignant</option> <option value='bryce.bodleygomes' onClick={() =>{this.handleReviewer('F')}}>bryce.bodleygomes</option> <option value='adrian.povedamckay' onClick={() =>{this.handleReviewer('G')}}>adrian.povedamckay</option> <option value='chenhao.huang' onClick={() =>{this.handleReviewer('H')}}>chenhao.huang</option> <option value='michael.schiller' onClick={() =>{this.handleReviewer('I')}}>michael.schiller</option> <option value='kevin.silva' onClick={() =>{this.handleReviewer('J')}}>kevin.silva</option> </select> </Panel> </div>: null } <div className="col-lg-8 col-lg-offset-4"> <Button className="btn btn-primary" id="submitButton" onClick={() =>{this.runMacro()}}> Enter </Button> </div> </div> ); } } export default DatabaseView;
examples/auth-with-shared-root/components/PageTwo.js
meraki/react-router
import React from 'react' const PageOne = React.createClass({ render() { return <h2>Page Two! Wooo!</h2> } }) export default PageOne
src/components/pagination/PaginationButton/PaginationPrev.js
cltk/cltk_frontend
import React from 'react'; import { Link, withRouter } from 'react-router'; const PaginationPrev = props => ( <Link to={{ pathname: '/browse', query: { ...props.location.query, page: (props.location.query.page ? parseInt(props.location.query.page, 10) : 2) - 1, }, }} > <i className="mdi mdi-chevron-left" /> <span> Previous </span> </Link> ); export default withRouter(PaginationPrev);
ajax/libs/react/0.4.2/JSXTransformer.js
jacoborus/cdnjs
/** * JSXTransformer v0.4.2 */ (function(e){if("function"==typeof bootstrap)bootstrap("jsxtransformer",e);else if("object"==typeof exports)module.exports=e();else if("function"==typeof define&&define.amd)define(e);else if("undefined"!=typeof ses){if(!ses.ok())return;ses.makeJSXTransformer=e}else"undefined"!=typeof window?window.JSXTransformer=e():global.JSXTransformer=e()})(function(){var define,ses,bootstrap,module,exports; return (function(e,t,n){function i(n,s){if(!t[n]){if(!e[n]){var o=typeof require=="function"&&require;if(!s&&o)return o(n,!0);if(r)return r(n,!0);throw new Error("Cannot find module '"+n+"'")}var u=t[n]={exports:{}};e[n][0].call(u.exports,function(t){var r=e[n][1][t];return i(r?r:t)},u,u.exports)}return t[n].exports}var r=typeof require=="function"&&require;for(var s=0;s<n.length;s++)i(n[s]);return i})({1:[function(require,module,exports){ var Base62 = (function (my) { my.chars = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "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", "U", "V", "W", "X", "Y", "Z"] my.encode = function(i){ if (i === 0) {return '0'} var s = '' while (i > 0) { s = this.chars[i % 62] + s i = Math.floor(i/62) } return s }; my.decode = function(a,b,c,d){ for ( b = c = ( a === (/\W|_|^$/.test(a += "") || a) ) - 1; d = a.charCodeAt(c++); ) b = b * 62 + d - [, 48, 29, 87][d >> 5]; return b }; return my; }({})); module.exports = Base62 },{}],2:[function(require,module,exports){ var process=require("__browserify_process");function filter (xs, fn) { var res = []; for (var i = 0; i < xs.length; i++) { if (fn(xs[i], i, xs)) res.push(xs[i]); } return res; } // resolves . and .. elements in a path array with directory names there // must be no slashes, empty elements, or device names (c:\) in the array // (so also no leading and trailing slashes - it does not distinguish // relative and absolute paths) function normalizeArray(parts, allowAboveRoot) { // if the path tries to go above the root, `up` ends up > 0 var up = 0; for (var i = parts.length; i >= 0; i--) { var last = parts[i]; if (last == '.') { parts.splice(i, 1); } else if (last === '..') { parts.splice(i, 1); up++; } else if (up) { parts.splice(i, 1); up--; } } // if the path is allowed to go above the root, restore leading ..s if (allowAboveRoot) { for (; up--; up) { parts.unshift('..'); } } return parts; } // Regex to split a filename into [*, dir, basename, ext] // posix version var splitPathRe = /^(.+\/(?!$)|\/)?((?:.+?)?(\.[^.]*)?)$/; // path.resolve([from ...], to) // posix version exports.resolve = function() { var resolvedPath = '', resolvedAbsolute = false; for (var i = arguments.length; i >= -1 && !resolvedAbsolute; i--) { var path = (i >= 0) ? arguments[i] : process.cwd(); // Skip empty and invalid entries if (typeof path !== 'string' || !path) { continue; } resolvedPath = path + '/' + resolvedPath; resolvedAbsolute = path.charAt(0) === '/'; } // At this point the path should be resolved to a full absolute path, but // handle relative paths to be safe (might happen when process.cwd() fails) // Normalize the path resolvedPath = normalizeArray(filter(resolvedPath.split('/'), function(p) { return !!p; }), !resolvedAbsolute).join('/'); return ((resolvedAbsolute ? '/' : '') + resolvedPath) || '.'; }; // path.normalize(path) // posix version exports.normalize = function(path) { var isAbsolute = path.charAt(0) === '/', trailingSlash = path.slice(-1) === '/'; // Normalize the path path = normalizeArray(filter(path.split('/'), function(p) { return !!p; }), !isAbsolute).join('/'); if (!path && !isAbsolute) { path = '.'; } if (path && trailingSlash) { path += '/'; } return (isAbsolute ? '/' : '') + path; }; // posix version exports.join = function() { var paths = Array.prototype.slice.call(arguments, 0); return exports.normalize(filter(paths, function(p, index) { return p && typeof p === 'string'; }).join('/')); }; exports.dirname = function(path) { var dir = splitPathRe.exec(path)[1] || ''; var isWindows = false; if (!dir) { // No dirname return '.'; } else if (dir.length === 1 || (isWindows && dir.length <= 3 && dir.charAt(1) === ':')) { // It is just a slash or a drive letter with a slash return dir; } else { // It is a full dirname, strip trailing slash return dir.substring(0, dir.length - 1); } }; exports.basename = function(path, ext) { var f = splitPathRe.exec(path)[2] || ''; // TODO: make this comparison case-insensitive on windows? if (ext && f.substr(-1 * ext.length) === ext) { f = f.substr(0, f.length - ext.length); } return f; }; exports.extname = function(path) { return splitPathRe.exec(path)[3] || ''; }; exports.relative = function(from, to) { from = exports.resolve(from).substr(1); to = exports.resolve(to).substr(1); function trim(arr) { var start = 0; for (; start < arr.length; start++) { if (arr[start] !== '') break; } var end = arr.length - 1; for (; end >= 0; end--) { if (arr[end] !== '') break; } if (start > end) return []; return arr.slice(start, end - start + 1); } var fromParts = trim(from.split('/')); var toParts = trim(to.split('/')); var length = Math.min(fromParts.length, toParts.length); var samePartsLength = length; for (var i = 0; i < length; i++) { if (fromParts[i] !== toParts[i]) { samePartsLength = i; break; } } var outputParts = []; for (var i = samePartsLength; i < fromParts.length; i++) { outputParts.push('..'); } outputParts = outputParts.concat(toParts.slice(samePartsLength)); return outputParts.join('/'); }; exports.sep = '/'; },{"__browserify_process":3}],3:[function(require,module,exports){ // shim for using process in browser var process = module.exports = {}; process.nextTick = (function () { var canSetImmediate = typeof window !== 'undefined' && window.setImmediate; var canPost = typeof window !== 'undefined' && window.postMessage && window.addEventListener ; if (canSetImmediate) { return function (f) { return window.setImmediate(f) }; } if (canPost) { var queue = []; window.addEventListener('message', function (ev) { if (ev.source === window && ev.data === 'process-tick') { ev.stopPropagation(); if (queue.length > 0) { var fn = queue.shift(); fn(); } } }, true); return function nextTick(fn) { queue.push(fn); window.postMessage('process-tick', '*'); }; } return function nextTick(fn) { setTimeout(fn, 0); }; })(); process.title = 'browser'; process.browser = true; process.env = {}; process.argv = []; process.binding = function (name) { throw new Error('process.binding is not supported'); } // TODO(shtylman) process.cwd = function () { return '/' }; process.chdir = function (dir) { throw new Error('process.chdir is not supported'); }; },{}],4:[function(require,module,exports){ /* Copyright (C) 2013 Thaddee Tyl <[email protected]> Copyright (C) 2012 Ariya Hidayat <[email protected]> Copyright (C) 2012 Mathias Bynens <[email protected]> Copyright (C) 2012 Joost-Wim Boekesteijn <[email protected]> Copyright (C) 2012 Kris Kowal <[email protected]> Copyright (C) 2012 Yusuke Suzuki <[email protected]> Copyright (C) 2012 Arpad Borsos <[email protected]> Copyright (C) 2011 Ariya Hidayat <[email protected]> Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /*jslint bitwise:true plusplus:true */ /*global esprima:true, define:true, exports:true, window: true, throwError: true, generateStatement: true, peek: true, parseAssignmentExpression: true, parseBlock: true, parseClassExpression: true, parseClassDeclaration: true, parseExpression: true, parseForStatement: true, parseFunctionDeclaration: true, parseFunctionExpression: true, parseFunctionSourceElements: true, parseVariableIdentifier: true, parseImportSpecifier: true, parseLeftHandSideExpression: true, parseParams: true, validateParam: true, parseSpreadOrAssignmentExpression: true, parseStatement: true, parseSourceElement: true, parseModuleBlock: true, parseConciseBody: true, advanceXJSChild: true, isXJSIdentifierStart: true, isXJSIdentifierPart: true, scanXJSStringLiteral: true, scanXJSIdentifier: true, parseXJSAttributeValue: true, parseXJSChild: true, parseXJSElement: true, parseXJSExpressionContainer: true, parseXJSEmptyExpression: true, parseYieldExpression: true */ (function (root, factory) { 'use strict'; // Universal Module Definition (UMD) to support AMD, CommonJS/Node.js, // Rhino, and plain browser loading. if (typeof define === 'function' && define.amd) { define(['exports'], factory); } else if (typeof exports !== 'undefined') { factory(exports); } else { factory((root.esprima = {})); } }(this, function (exports) { 'use strict'; var Token, TokenName, FnExprTokens, Syntax, PropertyKind, Messages, Regex, SyntaxTreeDelegate, XHTMLEntities, ClassPropertyType, source, strict, index, lineNumber, lineStart, length, delegate, lookahead, state, extra; Token = { BooleanLiteral: 1, EOF: 2, Identifier: 3, Keyword: 4, NullLiteral: 5, NumericLiteral: 6, Punctuator: 7, StringLiteral: 8, RegularExpression: 9, Template: 10, XJSIdentifier: 11, XJSText: 12 }; TokenName = {}; TokenName[Token.BooleanLiteral] = 'Boolean'; TokenName[Token.EOF] = '<end>'; TokenName[Token.Identifier] = 'Identifier'; TokenName[Token.Keyword] = 'Keyword'; TokenName[Token.NullLiteral] = 'Null'; TokenName[Token.NumericLiteral] = 'Numeric'; TokenName[Token.Punctuator] = 'Punctuator'; TokenName[Token.StringLiteral] = 'String'; TokenName[Token.XJSIdentifier] = 'XJSIdentifier'; TokenName[Token.XJSText] = 'XJSText'; TokenName[Token.RegularExpression] = 'RegularExpression'; // A function following one of those tokens is an expression. FnExprTokens = ["(", "{", "[", "in", "typeof", "instanceof", "new", "return", "case", "delete", "throw", "void", // assignment operators "=", "+=", "-=", "*=", "/=", "%=", "<<=", ">>=", ">>>=", "&=", "|=", "^=", ",", // binary/unary operators "+", "-", "*", "/", "%", "++", "--", "<<", ">>", ">>>", "&", "|", "^", "!", "~", "&&", "||", "?", ":", "===", "==", ">=", "<=", "<", ">", "!=", "!=="]; Syntax = { ArrayExpression: 'ArrayExpression', ArrayPattern: 'ArrayPattern', ArrowFunctionExpression: 'ArrowFunctionExpression', AssignmentExpression: 'AssignmentExpression', BinaryExpression: 'BinaryExpression', BlockStatement: 'BlockStatement', BreakStatement: 'BreakStatement', CallExpression: 'CallExpression', CatchClause: 'CatchClause', ClassBody: 'ClassBody', ClassDeclaration: 'ClassDeclaration', ClassExpression: 'ClassExpression', ClassHeritage: 'ClassHeritage', ComprehensionBlock: 'ComprehensionBlock', ComprehensionExpression: 'ComprehensionExpression', ConditionalExpression: 'ConditionalExpression', ContinueStatement: 'ContinueStatement', DebuggerStatement: 'DebuggerStatement', DoWhileStatement: 'DoWhileStatement', EmptyStatement: 'EmptyStatement', ExportDeclaration: 'ExportDeclaration', ExportSpecifier: 'ExportSpecifier', ExportSpecifierSet: 'ExportSpecifierSet', ExpressionStatement: 'ExpressionStatement', ForInStatement: 'ForInStatement', ForOfStatement: 'ForOfStatement', ForStatement: 'ForStatement', FunctionDeclaration: 'FunctionDeclaration', FunctionExpression: 'FunctionExpression', Glob: 'Glob', Identifier: 'Identifier', IfStatement: 'IfStatement', ImportDeclaration: 'ImportDeclaration', ImportSpecifier: 'ImportSpecifier', LabeledStatement: 'LabeledStatement', Literal: 'Literal', LogicalExpression: 'LogicalExpression', MemberExpression: 'MemberExpression', MethodDefinition: 'MethodDefinition', ModuleDeclaration: 'ModuleDeclaration', NewExpression: 'NewExpression', ObjectExpression: 'ObjectExpression', ObjectPattern: 'ObjectPattern', Path: 'Path', Program: 'Program', Property: 'Property', ReturnStatement: 'ReturnStatement', SequenceExpression: 'SequenceExpression', SpreadElement: 'SpreadElement', SwitchCase: 'SwitchCase', SwitchStatement: 'SwitchStatement', TaggedTemplateExpression: 'TaggedTemplateExpression', TemplateElement: 'TemplateElement', TemplateLiteral: 'TemplateLiteral', ThisExpression: 'ThisExpression', ThrowStatement: 'ThrowStatement', TryStatement: 'TryStatement', UnaryExpression: 'UnaryExpression', UpdateExpression: 'UpdateExpression', VariableDeclaration: 'VariableDeclaration', VariableDeclarator: 'VariableDeclarator', WhileStatement: 'WhileStatement', WithStatement: 'WithStatement', XJSIdentifier: 'XJSIdentifier', XJSEmptyExpression: 'XJSEmptyExpression', XJSExpressionContainer: 'XJSExpressionContainer', XJSElement: 'XJSElement', XJSClosingElement: 'XJSClosingElement', XJSOpeningElement: 'XJSOpeningElement', XJSAttribute: 'XJSAttribute', XJSText: 'XJSText', YieldExpression: 'YieldExpression' }; PropertyKind = { Data: 1, Get: 2, Set: 4 }; ClassPropertyType = { static: 'static', prototype: 'prototype' }; // Error messages should be identical to V8. Messages = { UnexpectedToken: 'Unexpected token %0', UnexpectedNumber: 'Unexpected number', UnexpectedString: 'Unexpected string', UnexpectedIdentifier: 'Unexpected identifier', UnexpectedReserved: 'Unexpected reserved word', UnexpectedTemplate: 'Unexpected quasi %0', UnexpectedEOS: 'Unexpected end of input', NewlineAfterThrow: 'Illegal newline after throw', InvalidRegExp: 'Invalid regular expression', UnterminatedRegExp: 'Invalid regular expression: missing /', InvalidLHSInAssignment: 'Invalid left-hand side in assignment', InvalidLHSInFormalsList: 'Invalid left-hand side in formals list', InvalidLHSInForIn: 'Invalid left-hand side in for-in', MultipleDefaultsInSwitch: 'More than one default clause in switch statement', NoCatchOrFinally: 'Missing catch or finally after try', UnknownLabel: 'Undefined label \'%0\'', Redeclaration: '%0 \'%1\' has already been declared', IllegalContinue: 'Illegal continue statement', IllegalBreak: 'Illegal break statement', IllegalDuplicateClassProperty: 'Illegal duplicate property in class definition', IllegalReturn: 'Illegal return statement', IllegalYield: 'Illegal yield expression', IllegalSpread: 'Illegal spread element', StrictModeWith: 'Strict mode code may not include a with statement', StrictCatchVariable: 'Catch variable may not be eval or arguments in strict mode', StrictVarName: 'Variable name may not be eval or arguments in strict mode', StrictParamName: 'Parameter name eval or arguments is not allowed in strict mode', StrictParamDupe: 'Strict mode function may not have duplicate parameter names', ParameterAfterRestParameter: 'Rest parameter must be final parameter of an argument list', ElementAfterSpreadElement: 'Spread must be the final element of an element list', ObjectPatternAsRestParameter: 'Invalid rest parameter', ObjectPatternAsSpread: 'Invalid spread argument', StrictFunctionName: 'Function name may not be eval or arguments in strict mode', StrictOctalLiteral: 'Octal literals are not allowed in strict mode.', StrictDelete: 'Delete of an unqualified identifier in strict mode.', StrictDuplicateProperty: 'Duplicate data property in object literal not allowed in strict mode', AccessorDataProperty: 'Object literal may not have data and accessor property with the same name', AccessorGetSet: 'Object literal may not have multiple get/set accessors with the same name', StrictLHSAssignment: 'Assignment to eval or arguments is not allowed in strict mode', StrictLHSPostfix: 'Postfix increment/decrement may not have eval or arguments operand in strict mode', StrictLHSPrefix: 'Prefix increment/decrement may not have eval or arguments operand in strict mode', StrictReservedWord: 'Use of future reserved word in strict mode', NoFromAfterImport: 'Missing from after import', NoYieldInGenerator: 'Missing yield in generator', NoUnintializedConst: 'Const must be initialized', ComprehensionRequiresBlock: 'Comprehension must have at least one block', ComprehensionError: 'Comprehension Error', EachNotAllowed: 'Each is not supported', InvalidXJSTagName: 'XJS tag name can not be empty', InvalidXJSAttributeValue: 'XJS value should be either an expression or a quoted XJS text', ExpectedXJSClosingTag: 'Expected corresponding XJS closing tag for %0' }; // See also tools/generate-unicode-regex.py. Regex = { NonAsciiIdentifierStart: new RegExp('[\xaa\xb5\xba\xc0-\xd6\xd8-\xf6\xf8-\u02c1\u02c6-\u02d1\u02e0-\u02e4\u02ec\u02ee\u0370-\u0374\u0376\u0377\u037a-\u037d\u0386\u0388-\u038a\u038c\u038e-\u03a1\u03a3-\u03f5\u03f7-\u0481\u048a-\u0527\u0531-\u0556\u0559\u0561-\u0587\u05d0-\u05ea\u05f0-\u05f2\u0620-\u064a\u066e\u066f\u0671-\u06d3\u06d5\u06e5\u06e6\u06ee\u06ef\u06fa-\u06fc\u06ff\u0710\u0712-\u072f\u074d-\u07a5\u07b1\u07ca-\u07ea\u07f4\u07f5\u07fa\u0800-\u0815\u081a\u0824\u0828\u0840-\u0858\u08a0\u08a2-\u08ac\u0904-\u0939\u093d\u0950\u0958-\u0961\u0971-\u0977\u0979-\u097f\u0985-\u098c\u098f\u0990\u0993-\u09a8\u09aa-\u09b0\u09b2\u09b6-\u09b9\u09bd\u09ce\u09dc\u09dd\u09df-\u09e1\u09f0\u09f1\u0a05-\u0a0a\u0a0f\u0a10\u0a13-\u0a28\u0a2a-\u0a30\u0a32\u0a33\u0a35\u0a36\u0a38\u0a39\u0a59-\u0a5c\u0a5e\u0a72-\u0a74\u0a85-\u0a8d\u0a8f-\u0a91\u0a93-\u0aa8\u0aaa-\u0ab0\u0ab2\u0ab3\u0ab5-\u0ab9\u0abd\u0ad0\u0ae0\u0ae1\u0b05-\u0b0c\u0b0f\u0b10\u0b13-\u0b28\u0b2a-\u0b30\u0b32\u0b33\u0b35-\u0b39\u0b3d\u0b5c\u0b5d\u0b5f-\u0b61\u0b71\u0b83\u0b85-\u0b8a\u0b8e-\u0b90\u0b92-\u0b95\u0b99\u0b9a\u0b9c\u0b9e\u0b9f\u0ba3\u0ba4\u0ba8-\u0baa\u0bae-\u0bb9\u0bd0\u0c05-\u0c0c\u0c0e-\u0c10\u0c12-\u0c28\u0c2a-\u0c33\u0c35-\u0c39\u0c3d\u0c58\u0c59\u0c60\u0c61\u0c85-\u0c8c\u0c8e-\u0c90\u0c92-\u0ca8\u0caa-\u0cb3\u0cb5-\u0cb9\u0cbd\u0cde\u0ce0\u0ce1\u0cf1\u0cf2\u0d05-\u0d0c\u0d0e-\u0d10\u0d12-\u0d3a\u0d3d\u0d4e\u0d60\u0d61\u0d7a-\u0d7f\u0d85-\u0d96\u0d9a-\u0db1\u0db3-\u0dbb\u0dbd\u0dc0-\u0dc6\u0e01-\u0e30\u0e32\u0e33\u0e40-\u0e46\u0e81\u0e82\u0e84\u0e87\u0e88\u0e8a\u0e8d\u0e94-\u0e97\u0e99-\u0e9f\u0ea1-\u0ea3\u0ea5\u0ea7\u0eaa\u0eab\u0ead-\u0eb0\u0eb2\u0eb3\u0ebd\u0ec0-\u0ec4\u0ec6\u0edc-\u0edf\u0f00\u0f40-\u0f47\u0f49-\u0f6c\u0f88-\u0f8c\u1000-\u102a\u103f\u1050-\u1055\u105a-\u105d\u1061\u1065\u1066\u106e-\u1070\u1075-\u1081\u108e\u10a0-\u10c5\u10c7\u10cd\u10d0-\u10fa\u10fc-\u1248\u124a-\u124d\u1250-\u1256\u1258\u125a-\u125d\u1260-\u1288\u128a-\u128d\u1290-\u12b0\u12b2-\u12b5\u12b8-\u12be\u12c0\u12c2-\u12c5\u12c8-\u12d6\u12d8-\u1310\u1312-\u1315\u1318-\u135a\u1380-\u138f\u13a0-\u13f4\u1401-\u166c\u166f-\u167f\u1681-\u169a\u16a0-\u16ea\u16ee-\u16f0\u1700-\u170c\u170e-\u1711\u1720-\u1731\u1740-\u1751\u1760-\u176c\u176e-\u1770\u1780-\u17b3\u17d7\u17dc\u1820-\u1877\u1880-\u18a8\u18aa\u18b0-\u18f5\u1900-\u191c\u1950-\u196d\u1970-\u1974\u1980-\u19ab\u19c1-\u19c7\u1a00-\u1a16\u1a20-\u1a54\u1aa7\u1b05-\u1b33\u1b45-\u1b4b\u1b83-\u1ba0\u1bae\u1baf\u1bba-\u1be5\u1c00-\u1c23\u1c4d-\u1c4f\u1c5a-\u1c7d\u1ce9-\u1cec\u1cee-\u1cf1\u1cf5\u1cf6\u1d00-\u1dbf\u1e00-\u1f15\u1f18-\u1f1d\u1f20-\u1f45\u1f48-\u1f4d\u1f50-\u1f57\u1f59\u1f5b\u1f5d\u1f5f-\u1f7d\u1f80-\u1fb4\u1fb6-\u1fbc\u1fbe\u1fc2-\u1fc4\u1fc6-\u1fcc\u1fd0-\u1fd3\u1fd6-\u1fdb\u1fe0-\u1fec\u1ff2-\u1ff4\u1ff6-\u1ffc\u2071\u207f\u2090-\u209c\u2102\u2107\u210a-\u2113\u2115\u2119-\u211d\u2124\u2126\u2128\u212a-\u212d\u212f-\u2139\u213c-\u213f\u2145-\u2149\u214e\u2160-\u2188\u2c00-\u2c2e\u2c30-\u2c5e\u2c60-\u2ce4\u2ceb-\u2cee\u2cf2\u2cf3\u2d00-\u2d25\u2d27\u2d2d\u2d30-\u2d67\u2d6f\u2d80-\u2d96\u2da0-\u2da6\u2da8-\u2dae\u2db0-\u2db6\u2db8-\u2dbe\u2dc0-\u2dc6\u2dc8-\u2dce\u2dd0-\u2dd6\u2dd8-\u2dde\u2e2f\u3005-\u3007\u3021-\u3029\u3031-\u3035\u3038-\u303c\u3041-\u3096\u309d-\u309f\u30a1-\u30fa\u30fc-\u30ff\u3105-\u312d\u3131-\u318e\u31a0-\u31ba\u31f0-\u31ff\u3400-\u4db5\u4e00-\u9fcc\ua000-\ua48c\ua4d0-\ua4fd\ua500-\ua60c\ua610-\ua61f\ua62a\ua62b\ua640-\ua66e\ua67f-\ua697\ua6a0-\ua6ef\ua717-\ua71f\ua722-\ua788\ua78b-\ua78e\ua790-\ua793\ua7a0-\ua7aa\ua7f8-\ua801\ua803-\ua805\ua807-\ua80a\ua80c-\ua822\ua840-\ua873\ua882-\ua8b3\ua8f2-\ua8f7\ua8fb\ua90a-\ua925\ua930-\ua946\ua960-\ua97c\ua984-\ua9b2\ua9cf\uaa00-\uaa28\uaa40-\uaa42\uaa44-\uaa4b\uaa60-\uaa76\uaa7a\uaa80-\uaaaf\uaab1\uaab5\uaab6\uaab9-\uaabd\uaac0\uaac2\uaadb-\uaadd\uaae0-\uaaea\uaaf2-\uaaf4\uab01-\uab06\uab09-\uab0e\uab11-\uab16\uab20-\uab26\uab28-\uab2e\uabc0-\uabe2\uac00-\ud7a3\ud7b0-\ud7c6\ud7cb-\ud7fb\uf900-\ufa6d\ufa70-\ufad9\ufb00-\ufb06\ufb13-\ufb17\ufb1d\ufb1f-\ufb28\ufb2a-\ufb36\ufb38-\ufb3c\ufb3e\ufb40\ufb41\ufb43\ufb44\ufb46-\ufbb1\ufbd3-\ufd3d\ufd50-\ufd8f\ufd92-\ufdc7\ufdf0-\ufdfb\ufe70-\ufe74\ufe76-\ufefc\uff21-\uff3a\uff41-\uff5a\uff66-\uffbe\uffc2-\uffc7\uffca-\uffcf\uffd2-\uffd7\uffda-\uffdc]'), NonAsciiIdentifierPart: new RegExp('[\xaa\xb5\xba\xc0-\xd6\xd8-\xf6\xf8-\u02c1\u02c6-\u02d1\u02e0-\u02e4\u02ec\u02ee\u0300-\u0374\u0376\u0377\u037a-\u037d\u0386\u0388-\u038a\u038c\u038e-\u03a1\u03a3-\u03f5\u03f7-\u0481\u0483-\u0487\u048a-\u0527\u0531-\u0556\u0559\u0561-\u0587\u0591-\u05bd\u05bf\u05c1\u05c2\u05c4\u05c5\u05c7\u05d0-\u05ea\u05f0-\u05f2\u0610-\u061a\u0620-\u0669\u066e-\u06d3\u06d5-\u06dc\u06df-\u06e8\u06ea-\u06fc\u06ff\u0710-\u074a\u074d-\u07b1\u07c0-\u07f5\u07fa\u0800-\u082d\u0840-\u085b\u08a0\u08a2-\u08ac\u08e4-\u08fe\u0900-\u0963\u0966-\u096f\u0971-\u0977\u0979-\u097f\u0981-\u0983\u0985-\u098c\u098f\u0990\u0993-\u09a8\u09aa-\u09b0\u09b2\u09b6-\u09b9\u09bc-\u09c4\u09c7\u09c8\u09cb-\u09ce\u09d7\u09dc\u09dd\u09df-\u09e3\u09e6-\u09f1\u0a01-\u0a03\u0a05-\u0a0a\u0a0f\u0a10\u0a13-\u0a28\u0a2a-\u0a30\u0a32\u0a33\u0a35\u0a36\u0a38\u0a39\u0a3c\u0a3e-\u0a42\u0a47\u0a48\u0a4b-\u0a4d\u0a51\u0a59-\u0a5c\u0a5e\u0a66-\u0a75\u0a81-\u0a83\u0a85-\u0a8d\u0a8f-\u0a91\u0a93-\u0aa8\u0aaa-\u0ab0\u0ab2\u0ab3\u0ab5-\u0ab9\u0abc-\u0ac5\u0ac7-\u0ac9\u0acb-\u0acd\u0ad0\u0ae0-\u0ae3\u0ae6-\u0aef\u0b01-\u0b03\u0b05-\u0b0c\u0b0f\u0b10\u0b13-\u0b28\u0b2a-\u0b30\u0b32\u0b33\u0b35-\u0b39\u0b3c-\u0b44\u0b47\u0b48\u0b4b-\u0b4d\u0b56\u0b57\u0b5c\u0b5d\u0b5f-\u0b63\u0b66-\u0b6f\u0b71\u0b82\u0b83\u0b85-\u0b8a\u0b8e-\u0b90\u0b92-\u0b95\u0b99\u0b9a\u0b9c\u0b9e\u0b9f\u0ba3\u0ba4\u0ba8-\u0baa\u0bae-\u0bb9\u0bbe-\u0bc2\u0bc6-\u0bc8\u0bca-\u0bcd\u0bd0\u0bd7\u0be6-\u0bef\u0c01-\u0c03\u0c05-\u0c0c\u0c0e-\u0c10\u0c12-\u0c28\u0c2a-\u0c33\u0c35-\u0c39\u0c3d-\u0c44\u0c46-\u0c48\u0c4a-\u0c4d\u0c55\u0c56\u0c58\u0c59\u0c60-\u0c63\u0c66-\u0c6f\u0c82\u0c83\u0c85-\u0c8c\u0c8e-\u0c90\u0c92-\u0ca8\u0caa-\u0cb3\u0cb5-\u0cb9\u0cbc-\u0cc4\u0cc6-\u0cc8\u0cca-\u0ccd\u0cd5\u0cd6\u0cde\u0ce0-\u0ce3\u0ce6-\u0cef\u0cf1\u0cf2\u0d02\u0d03\u0d05-\u0d0c\u0d0e-\u0d10\u0d12-\u0d3a\u0d3d-\u0d44\u0d46-\u0d48\u0d4a-\u0d4e\u0d57\u0d60-\u0d63\u0d66-\u0d6f\u0d7a-\u0d7f\u0d82\u0d83\u0d85-\u0d96\u0d9a-\u0db1\u0db3-\u0dbb\u0dbd\u0dc0-\u0dc6\u0dca\u0dcf-\u0dd4\u0dd6\u0dd8-\u0ddf\u0df2\u0df3\u0e01-\u0e3a\u0e40-\u0e4e\u0e50-\u0e59\u0e81\u0e82\u0e84\u0e87\u0e88\u0e8a\u0e8d\u0e94-\u0e97\u0e99-\u0e9f\u0ea1-\u0ea3\u0ea5\u0ea7\u0eaa\u0eab\u0ead-\u0eb9\u0ebb-\u0ebd\u0ec0-\u0ec4\u0ec6\u0ec8-\u0ecd\u0ed0-\u0ed9\u0edc-\u0edf\u0f00\u0f18\u0f19\u0f20-\u0f29\u0f35\u0f37\u0f39\u0f3e-\u0f47\u0f49-\u0f6c\u0f71-\u0f84\u0f86-\u0f97\u0f99-\u0fbc\u0fc6\u1000-\u1049\u1050-\u109d\u10a0-\u10c5\u10c7\u10cd\u10d0-\u10fa\u10fc-\u1248\u124a-\u124d\u1250-\u1256\u1258\u125a-\u125d\u1260-\u1288\u128a-\u128d\u1290-\u12b0\u12b2-\u12b5\u12b8-\u12be\u12c0\u12c2-\u12c5\u12c8-\u12d6\u12d8-\u1310\u1312-\u1315\u1318-\u135a\u135d-\u135f\u1380-\u138f\u13a0-\u13f4\u1401-\u166c\u166f-\u167f\u1681-\u169a\u16a0-\u16ea\u16ee-\u16f0\u1700-\u170c\u170e-\u1714\u1720-\u1734\u1740-\u1753\u1760-\u176c\u176e-\u1770\u1772\u1773\u1780-\u17d3\u17d7\u17dc\u17dd\u17e0-\u17e9\u180b-\u180d\u1810-\u1819\u1820-\u1877\u1880-\u18aa\u18b0-\u18f5\u1900-\u191c\u1920-\u192b\u1930-\u193b\u1946-\u196d\u1970-\u1974\u1980-\u19ab\u19b0-\u19c9\u19d0-\u19d9\u1a00-\u1a1b\u1a20-\u1a5e\u1a60-\u1a7c\u1a7f-\u1a89\u1a90-\u1a99\u1aa7\u1b00-\u1b4b\u1b50-\u1b59\u1b6b-\u1b73\u1b80-\u1bf3\u1c00-\u1c37\u1c40-\u1c49\u1c4d-\u1c7d\u1cd0-\u1cd2\u1cd4-\u1cf6\u1d00-\u1de6\u1dfc-\u1f15\u1f18-\u1f1d\u1f20-\u1f45\u1f48-\u1f4d\u1f50-\u1f57\u1f59\u1f5b\u1f5d\u1f5f-\u1f7d\u1f80-\u1fb4\u1fb6-\u1fbc\u1fbe\u1fc2-\u1fc4\u1fc6-\u1fcc\u1fd0-\u1fd3\u1fd6-\u1fdb\u1fe0-\u1fec\u1ff2-\u1ff4\u1ff6-\u1ffc\u200c\u200d\u203f\u2040\u2054\u2071\u207f\u2090-\u209c\u20d0-\u20dc\u20e1\u20e5-\u20f0\u2102\u2107\u210a-\u2113\u2115\u2119-\u211d\u2124\u2126\u2128\u212a-\u212d\u212f-\u2139\u213c-\u213f\u2145-\u2149\u214e\u2160-\u2188\u2c00-\u2c2e\u2c30-\u2c5e\u2c60-\u2ce4\u2ceb-\u2cf3\u2d00-\u2d25\u2d27\u2d2d\u2d30-\u2d67\u2d6f\u2d7f-\u2d96\u2da0-\u2da6\u2da8-\u2dae\u2db0-\u2db6\u2db8-\u2dbe\u2dc0-\u2dc6\u2dc8-\u2dce\u2dd0-\u2dd6\u2dd8-\u2dde\u2de0-\u2dff\u2e2f\u3005-\u3007\u3021-\u302f\u3031-\u3035\u3038-\u303c\u3041-\u3096\u3099\u309a\u309d-\u309f\u30a1-\u30fa\u30fc-\u30ff\u3105-\u312d\u3131-\u318e\u31a0-\u31ba\u31f0-\u31ff\u3400-\u4db5\u4e00-\u9fcc\ua000-\ua48c\ua4d0-\ua4fd\ua500-\ua60c\ua610-\ua62b\ua640-\ua66f\ua674-\ua67d\ua67f-\ua697\ua69f-\ua6f1\ua717-\ua71f\ua722-\ua788\ua78b-\ua78e\ua790-\ua793\ua7a0-\ua7aa\ua7f8-\ua827\ua840-\ua873\ua880-\ua8c4\ua8d0-\ua8d9\ua8e0-\ua8f7\ua8fb\ua900-\ua92d\ua930-\ua953\ua960-\ua97c\ua980-\ua9c0\ua9cf-\ua9d9\uaa00-\uaa36\uaa40-\uaa4d\uaa50-\uaa59\uaa60-\uaa76\uaa7a\uaa7b\uaa80-\uaac2\uaadb-\uaadd\uaae0-\uaaef\uaaf2-\uaaf6\uab01-\uab06\uab09-\uab0e\uab11-\uab16\uab20-\uab26\uab28-\uab2e\uabc0-\uabea\uabec\uabed\uabf0-\uabf9\uac00-\ud7a3\ud7b0-\ud7c6\ud7cb-\ud7fb\uf900-\ufa6d\ufa70-\ufad9\ufb00-\ufb06\ufb13-\ufb17\ufb1d-\ufb28\ufb2a-\ufb36\ufb38-\ufb3c\ufb3e\ufb40\ufb41\ufb43\ufb44\ufb46-\ufbb1\ufbd3-\ufd3d\ufd50-\ufd8f\ufd92-\ufdc7\ufdf0-\ufdfb\ufe00-\ufe0f\ufe20-\ufe26\ufe33\ufe34\ufe4d-\ufe4f\ufe70-\ufe74\ufe76-\ufefc\uff10-\uff19\uff21-\uff3a\uff3f\uff41-\uff5a\uff66-\uffbe\uffc2-\uffc7\uffca-\uffcf\uffd2-\uffd7\uffda-\uffdc]') }; // Ensure the condition is true, otherwise throw an error. // This is only to have a better contract semantic, i.e. another safety net // to catch a logic error. The condition shall be fulfilled in normal case. // Do NOT use this to enforce a certain condition on any user input. function assert(condition, message) { if (!condition) { throw new Error('ASSERT: ' + message); } } function isDecimalDigit(ch) { return (ch >= 48 && ch <= 57); // 0..9 } function isHexDigit(ch) { return '0123456789abcdefABCDEF'.indexOf(ch) >= 0; } function isOctalDigit(ch) { return '01234567'.indexOf(ch) >= 0; } // 7.2 White Space function isWhiteSpace(ch) { return (ch === 32) || // space (ch === 9) || // tab (ch === 0xB) || (ch === 0xC) || (ch === 0xA0) || (ch >= 0x1680 && '\u1680\u180E\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200A\u202F\u205F\u3000\uFEFF'.indexOf(String.fromCharCode(ch)) > 0); } // 7.3 Line Terminators function isLineTerminator(ch) { return (ch === 10) || (ch === 13) || (ch === 0x2028) || (ch === 0x2029); } // 7.6 Identifier Names and Identifiers function isIdentifierStart(ch) { return (ch === 36) || (ch === 95) || // $ (dollar) and _ (underscore) (ch >= 65 && ch <= 90) || // A..Z (ch >= 97 && ch <= 122) || // a..z (ch === 92) || // \ (backslash) ((ch >= 0x80) && Regex.NonAsciiIdentifierStart.test(String.fromCharCode(ch))); } function isIdentifierPart(ch) { return (ch === 36) || (ch === 95) || // $ (dollar) and _ (underscore) (ch >= 65 && ch <= 90) || // A..Z (ch >= 97 && ch <= 122) || // a..z (ch >= 48 && ch <= 57) || // 0..9 (ch === 92) || // \ (backslash) ((ch >= 0x80) && Regex.NonAsciiIdentifierPart.test(String.fromCharCode(ch))); } // 7.6.1.2 Future Reserved Words function isFutureReservedWord(id) { switch (id) { case 'class': case 'enum': case 'export': case 'extends': case 'import': case 'super': return true; default: return false; } } function isStrictModeReservedWord(id) { switch (id) { case 'implements': case 'interface': case 'package': case 'private': case 'protected': case 'public': case 'static': case 'yield': case 'let': return true; default: return false; } } function isRestrictedWord(id) { return id === 'eval' || id === 'arguments'; } // 7.6.1.1 Keywords function isKeyword(id) { if (strict && isStrictModeReservedWord(id)) { return true; } // 'const' is specialized as Keyword in V8. // 'yield' and 'let' are for compatiblity with SpiderMonkey and ES.next. // Some others are from future reserved words. switch (id.length) { case 2: return (id === 'if') || (id === 'in') || (id === 'do'); case 3: return (id === 'var') || (id === 'for') || (id === 'new') || (id === 'try') || (id === 'let'); case 4: return (id === 'this') || (id === 'else') || (id === 'case') || (id === 'void') || (id === 'with') || (id === 'enum'); case 5: return (id === 'while') || (id === 'break') || (id === 'catch') || (id === 'throw') || (id === 'const') || (id === 'yield') || (id === 'class') || (id === 'super'); case 6: return (id === 'return') || (id === 'typeof') || (id === 'delete') || (id === 'switch') || (id === 'export') || (id === 'import'); case 7: return (id === 'default') || (id === 'finally') || (id === 'extends'); case 8: return (id === 'function') || (id === 'continue') || (id === 'debugger'); case 10: return (id === 'instanceof'); default: return false; } } // 7.4 Comments function skipComment() { var ch, blockComment, lineComment; blockComment = false; lineComment = false; while (index < length) { ch = source.charCodeAt(index); if (lineComment) { ++index; if (isLineTerminator(ch)) { lineComment = false; if (ch === 13 && source.charCodeAt(index) === 10) { ++index; } ++lineNumber; lineStart = index; } } else if (blockComment) { if (isLineTerminator(ch)) { if (ch === 13 && source.charCodeAt(index + 1) === 10) { ++index; } ++lineNumber; ++index; lineStart = index; if (index >= length) { throwError({}, Messages.UnexpectedToken, 'ILLEGAL'); } } else { ch = source.charCodeAt(index++); if (index >= length) { throwError({}, Messages.UnexpectedToken, 'ILLEGAL'); } // Block comment ends with '*/' (char #42, char #47). if (ch === 42) { ch = source.charCodeAt(index); if (ch === 47) { ++index; blockComment = false; } } } } else if (ch === 47) { ch = source.charCodeAt(index + 1); // Line comment starts with '//' (char #47, char #47). if (ch === 47) { index += 2; lineComment = true; } else if (ch === 42) { // Block comment starts with '/*' (char #47, char #42). index += 2; blockComment = true; if (index >= length) { throwError({}, Messages.UnexpectedToken, 'ILLEGAL'); } } else { break; } } else if (isWhiteSpace(ch)) { ++index; } else if (isLineTerminator(ch)) { ++index; if (ch === 13 && source.charCodeAt(index) === 10) { ++index; } ++lineNumber; lineStart = index; } else { break; } } } function scanHexEscape(prefix) { var i, len, ch, code = 0; len = (prefix === 'u') ? 4 : 2; for (i = 0; i < len; ++i) { if (index < length && isHexDigit(source[index])) { ch = source[index++]; code = code * 16 + '0123456789abcdef'.indexOf(ch.toLowerCase()); } else { return ''; } } return String.fromCharCode(code); } function scanUnicodeCodePointEscape() { var ch, code, cu1, cu2; ch = source[index]; code = 0; // At least, one hex digit is required. if (ch === '}') { throwError({}, Messages.UnexpectedToken, 'ILLEGAL'); } while (index < length) { ch = source[index++]; if (!isHexDigit(ch)) { break; } code = code * 16 + '0123456789abcdef'.indexOf(ch.toLowerCase()); } if (code > 0x10FFFF || ch !== '}') { throwError({}, Messages.UnexpectedToken, 'ILLEGAL'); } // UTF-16 Encoding if (code <= 0xFFFF) { return String.fromCharCode(code); } cu1 = ((code - 0x10000) >> 10) + 0xD800; cu2 = ((code - 0x10000) & 1023) + 0xDC00; return String.fromCharCode(cu1, cu2); } function getEscapedIdentifier() { var ch, id; ch = source.charCodeAt(index++); id = String.fromCharCode(ch); // '\u' (char #92, char #117) denotes an escaped character. if (ch === 92) { if (source.charCodeAt(index) !== 117) { throwError({}, Messages.UnexpectedToken, 'ILLEGAL'); } ++index; ch = scanHexEscape('u'); if (!ch || ch === '\\' || !isIdentifierStart(ch.charCodeAt(0))) { throwError({}, Messages.UnexpectedToken, 'ILLEGAL'); } id = ch; } while (index < length) { ch = source.charCodeAt(index); if (!isIdentifierPart(ch)) { break; } ++index; id += String.fromCharCode(ch); // '\u' (char #92, char #117) denotes an escaped character. if (ch === 92) { id = id.substr(0, id.length - 1); if (source.charCodeAt(index) !== 117) { throwError({}, Messages.UnexpectedToken, 'ILLEGAL'); } ++index; ch = scanHexEscape('u'); if (!ch || ch === '\\' || !isIdentifierPart(ch.charCodeAt(0))) { throwError({}, Messages.UnexpectedToken, 'ILLEGAL'); } id += ch; } } return id; } function getIdentifier() { var start, ch; start = index++; while (index < length) { ch = source.charCodeAt(index); if (ch === 92) { // Blackslash (char #92) marks Unicode escape sequence. index = start; return getEscapedIdentifier(); } if (isIdentifierPart(ch)) { ++index; } else { break; } } return source.slice(start, index); } function scanIdentifier() { var start, id, type; start = index; // Backslash (char #92) starts an escaped character. id = (source.charCodeAt(index) === 92) ? getEscapedIdentifier() : getIdentifier(); // There is no keyword or literal with only one character. // Thus, it must be an identifier. if (id.length === 1) { type = Token.Identifier; } else if (isKeyword(id)) { type = Token.Keyword; } else if (id === 'null') { type = Token.NullLiteral; } else if (id === 'true' || id === 'false') { type = Token.BooleanLiteral; } else { type = Token.Identifier; } return { type: type, value: id, lineNumber: lineNumber, lineStart: lineStart, range: [start, index] }; } // 7.7 Punctuators function scanPunctuator() { var start = index, code = source.charCodeAt(index), code2, ch1 = source[index], ch2, ch3, ch4; switch (code) { // Check for most common single-character punctuators. case 40: // ( open bracket case 41: // ) close bracket case 59: // ; semicolon case 44: // , comma case 123: // { open curly brace case 125: // } close curly brace case 91: // [ case 93: // ] case 58: // : case 63: // ? case 126: // ~ ++index; if (extra.tokenize) { if (code === 40) { extra.openParenToken = extra.tokens.length; } else if (code === 123) { extra.openCurlyToken = extra.tokens.length; } } return { type: Token.Punctuator, value: String.fromCharCode(code), lineNumber: lineNumber, lineStart: lineStart, range: [start, index] }; default: code2 = source.charCodeAt(index + 1); // '=' (char #61) marks an assignment or comparison operator. if (code2 === 61) { switch (code) { case 37: // % case 38: // & case 42: // *: case 43: // + case 45: // - case 47: // / case 60: // < case 62: // > case 94: // ^ case 124: // | index += 2; return { type: Token.Punctuator, value: String.fromCharCode(code) + String.fromCharCode(code2), lineNumber: lineNumber, lineStart: lineStart, range: [start, index] }; case 33: // ! case 61: // = index += 2; // !== and === if (source.charCodeAt(index) === 61) { ++index; } return { type: Token.Punctuator, value: source.slice(start, index), lineNumber: lineNumber, lineStart: lineStart, range: [start, index] }; default: break; } } break; } // Peek more characters. ch2 = source[index + 1]; ch3 = source[index + 2]; ch4 = source[index + 3]; // 4-character punctuator: >>>= if (ch1 === '>' && ch2 === '>' && ch3 === '>') { if (ch4 === '=') { index += 4; return { type: Token.Punctuator, value: '>>>=', lineNumber: lineNumber, lineStart: lineStart, range: [start, index] }; } } // 3-character punctuators: === !== >>> <<= >>= if (ch1 === '>' && ch2 === '>' && ch3 === '>') { index += 3; return { type: Token.Punctuator, value: '>>>', lineNumber: lineNumber, lineStart: lineStart, range: [start, index] }; } if (ch1 === '<' && ch2 === '<' && ch3 === '=') { index += 3; return { type: Token.Punctuator, value: '<<=', lineNumber: lineNumber, lineStart: lineStart, range: [start, index] }; } if (ch1 === '>' && ch2 === '>' && ch3 === '=') { index += 3; return { type: Token.Punctuator, value: '>>=', lineNumber: lineNumber, lineStart: lineStart, range: [start, index] }; } if (ch1 === '.' && ch2 === '.' && ch3 === '.') { index += 3; return { type: Token.Punctuator, value: '...', lineNumber: lineNumber, lineStart: lineStart, range: [start, index] }; } // Other 2-character punctuators: ++ -- << >> && || if (ch1 === ch2 && ('+-<>&|'.indexOf(ch1) >= 0)) { index += 2; return { type: Token.Punctuator, value: ch1 + ch2, lineNumber: lineNumber, lineStart: lineStart, range: [start, index] }; } if (ch1 === '=' && ch2 === '>') { index += 2; return { type: Token.Punctuator, value: '=>', lineNumber: lineNumber, lineStart: lineStart, range: [start, index] }; } if ('<>=!+-*%&|^/'.indexOf(ch1) >= 0) { ++index; return { type: Token.Punctuator, value: ch1, lineNumber: lineNumber, lineStart: lineStart, range: [start, index] }; } if (ch1 === '.') { ++index; return { type: Token.Punctuator, value: ch1, lineNumber: lineNumber, lineStart: lineStart, range: [start, index] }; } throwError({}, Messages.UnexpectedToken, 'ILLEGAL'); } // 7.8.3 Numeric Literals function scanHexLiteral(start) { var number = ''; while (index < length) { if (!isHexDigit(source[index])) { break; } number += source[index++]; } if (number.length === 0) { throwError({}, Messages.UnexpectedToken, 'ILLEGAL'); } if (isIdentifierStart(source.charCodeAt(index))) { throwError({}, Messages.UnexpectedToken, 'ILLEGAL'); } return { type: Token.NumericLiteral, value: parseInt('0x' + number, 16), lineNumber: lineNumber, lineStart: lineStart, range: [start, index] }; } function scanOctalLiteral(prefix, start) { var number, octal; if (isOctalDigit(prefix)) { octal = true; number = '0' + source[index++]; } else { octal = false; ++index; number = ''; } while (index < length) { if (!isOctalDigit(source[index])) { break; } number += source[index++]; } if (!octal && number.length === 0) { // only 0o or 0O throwError({}, Messages.UnexpectedToken, 'ILLEGAL'); } if (isIdentifierStart(source.charCodeAt(index)) || isDecimalDigit(source.charCodeAt(index))) { throwError({}, Messages.UnexpectedToken, 'ILLEGAL'); } return { type: Token.NumericLiteral, value: parseInt(number, 8), octal: octal, lineNumber: lineNumber, lineStart: lineStart, range: [start, index] }; } function scanNumericLiteral() { var number, start, ch, octal; ch = source[index]; assert(isDecimalDigit(ch.charCodeAt(0)) || (ch === '.'), 'Numeric literal must start with a decimal digit or a decimal point'); start = index; number = ''; if (ch !== '.') { number = source[index++]; ch = source[index]; // Hex number starts with '0x'. // Octal number starts with '0'. // Octal number in ES6 starts with '0o'. // Binary number in ES6 starts with '0b'. if (number === '0') { if (ch === 'x' || ch === 'X') { ++index; return scanHexLiteral(start); } if (ch === 'b' || ch === 'B') { ++index; number = ''; while (index < length) { ch = source[index]; if (ch !== '0' && ch !== '1') { break; } number += source[index++]; } if (number.length === 0) { // only 0b or 0B throwError({}, Messages.UnexpectedToken, 'ILLEGAL'); } if (index < length) { ch = source.charCodeAt(index); if (isIdentifierStart(ch) || isDecimalDigit(ch)) { throwError({}, Messages.UnexpectedToken, 'ILLEGAL'); } } return { type: Token.NumericLiteral, value: parseInt(number, 2), lineNumber: lineNumber, lineStart: lineStart, range: [start, index] }; } if (ch === 'o' || ch === 'O' || isOctalDigit(ch)) { return scanOctalLiteral(ch, start); } // decimal number starts with '0' such as '09' is illegal. if (ch && isDecimalDigit(ch.charCodeAt(0))) { throwError({}, Messages.UnexpectedToken, 'ILLEGAL'); } } while (isDecimalDigit(source.charCodeAt(index))) { number += source[index++]; } ch = source[index]; } if (ch === '.') { number += source[index++]; while (isDecimalDigit(source.charCodeAt(index))) { number += source[index++]; } ch = source[index]; } if (ch === 'e' || ch === 'E') { number += source[index++]; ch = source[index]; if (ch === '+' || ch === '-') { number += source[index++]; } if (isDecimalDigit(source.charCodeAt(index))) { while (isDecimalDigit(source.charCodeAt(index))) { number += source[index++]; } } else { throwError({}, Messages.UnexpectedToken, 'ILLEGAL'); } } if (isIdentifierStart(source.charCodeAt(index))) { throwError({}, Messages.UnexpectedToken, 'ILLEGAL'); } return { type: Token.NumericLiteral, value: parseFloat(number), lineNumber: lineNumber, lineStart: lineStart, range: [start, index] }; } // 7.8.4 String Literals function scanStringLiteral() { var str = '', quote, start, ch, code, unescaped, restore, octal = false; quote = source[index]; assert((quote === '\'' || quote === '"'), 'String literal must starts with a quote'); start = index; ++index; while (index < length) { ch = source[index++]; if (ch === quote) { quote = ''; break; } else if (ch === '\\') { ch = source[index++]; if (!ch || !isLineTerminator(ch.charCodeAt(0))) { switch (ch) { case 'n': str += '\n'; break; case 'r': str += '\r'; break; case 't': str += '\t'; break; case 'u': case 'x': if (source[index] === '{') { ++index; str += scanUnicodeCodePointEscape(); } else { restore = index; unescaped = scanHexEscape(ch); if (unescaped) { str += unescaped; } else { index = restore; str += ch; } } break; case 'b': str += '\b'; break; case 'f': str += '\f'; break; case 'v': str += '\x0B'; break; default: if (isOctalDigit(ch)) { code = '01234567'.indexOf(ch); // \0 is not octal escape sequence if (code !== 0) { octal = true; } if (index < length && isOctalDigit(source[index])) { octal = true; code = code * 8 + '01234567'.indexOf(source[index++]); // 3 digits are only allowed when string starts // with 0, 1, 2, 3 if ('0123'.indexOf(ch) >= 0 && index < length && isOctalDigit(source[index])) { code = code * 8 + '01234567'.indexOf(source[index++]); } } str += String.fromCharCode(code); } else { str += ch; } break; } } else { ++lineNumber; if (ch === '\r' && source[index] === '\n') { ++index; } } } else if (isLineTerminator(ch.charCodeAt(0))) { break; } else { str += ch; } } if (quote !== '') { throwError({}, Messages.UnexpectedToken, 'ILLEGAL'); } return { type: Token.StringLiteral, value: str, octal: octal, lineNumber: lineNumber, lineStart: lineStart, range: [start, index] }; } function scanTemplate() { var cooked = '', ch, start, terminated, tail, restore, unescaped, code, octal; terminated = false; tail = false; start = index; ++index; while (index < length) { ch = source[index++]; if (ch === '`') { tail = true; terminated = true; break; } else if (ch === '$') { if (source[index] === '{') { ++index; terminated = true; break; } cooked += ch; } else if (ch === '\\') { ch = source[index++]; if (!isLineTerminator(ch.charCodeAt(0))) { switch (ch) { case 'n': cooked += '\n'; break; case 'r': cooked += '\r'; break; case 't': cooked += '\t'; break; case 'u': case 'x': if (source[index] === '{') { ++index; cooked += scanUnicodeCodePointEscape(); } else { restore = index; unescaped = scanHexEscape(ch); if (unescaped) { cooked += unescaped; } else { index = restore; cooked += ch; } } break; case 'b': cooked += '\b'; break; case 'f': cooked += '\f'; break; case 'v': cooked += '\v'; break; default: if (isOctalDigit(ch)) { code = '01234567'.indexOf(ch); // \0 is not octal escape sequence if (code !== 0) { octal = true; } if (index < length && isOctalDigit(source[index])) { octal = true; code = code * 8 + '01234567'.indexOf(source[index++]); // 3 digits are only allowed when string starts // with 0, 1, 2, 3 if ('0123'.indexOf(ch) >= 0 && index < length && isOctalDigit(source[index])) { code = code * 8 + '01234567'.indexOf(source[index++]); } } cooked += String.fromCharCode(code); } else { cooked += ch; } break; } } else { ++lineNumber; if (ch === '\r' && source[index] === '\n') { ++index; } } } else if (isLineTerminator(ch.charCodeAt(0))) { ++lineNumber; if (ch === '\r' && source[index] === '\n') { ++index; } } else { cooked += ch; } } if (!terminated) { throwError({}, Messages.UnexpectedToken, 'ILLEGAL'); } return { type: Token.Template, value: { cooked: cooked, raw: source.slice(start + 1, index - ((tail) ? 1 : 2)) }, tail: tail, octal: octal, lineNumber: lineNumber, lineStart: lineStart, range: [start, index] }; } function scanTemplateElement(option) { var startsWith, template; lookahead = null; skipComment(); startsWith = (option.head) ? '`' : '}'; if (source[index] !== startsWith) { throwError({}, Messages.UnexpectedToken, 'ILLEGAL'); } template = scanTemplate(); peek(); return template; } function scanRegExp() { var str, ch, start, pattern, flags, value, classMarker = false, restore, terminated = false; lookahead = null; skipComment(); start = index; ch = source[index]; assert(ch === '/', 'Regular expression literal must start with a slash'); str = source[index++]; while (index < length) { ch = source[index++]; str += ch; if (classMarker) { if (ch === ']') { classMarker = false; } } else { if (ch === '\\') { ch = source[index++]; // ECMA-262 7.8.5 if (isLineTerminator(ch.charCodeAt(0))) { throwError({}, Messages.UnterminatedRegExp); } str += ch; } else if (ch === '/') { terminated = true; break; } else if (ch === '[') { classMarker = true; } else if (isLineTerminator(ch.charCodeAt(0))) { throwError({}, Messages.UnterminatedRegExp); } } } if (!terminated) { throwError({}, Messages.UnterminatedRegExp); } // Exclude leading and trailing slash. pattern = str.substr(1, str.length - 2); flags = ''; while (index < length) { ch = source[index]; if (!isIdentifierPart(ch.charCodeAt(0))) { break; } ++index; if (ch === '\\' && index < length) { ch = source[index]; if (ch === 'u') { ++index; restore = index; ch = scanHexEscape('u'); if (ch) { flags += ch; for (str += '\\u'; restore < index; ++restore) { str += source[restore]; } } else { index = restore; flags += 'u'; str += '\\u'; } } else { str += '\\'; } } else { flags += ch; str += ch; } } try { value = new RegExp(pattern, flags); } catch (e) { throwError({}, Messages.InvalidRegExp); } peek(); if (extra.tokenize) { return { type: Token.RegularExpression, value: value, lineNumber: lineNumber, lineStart: lineStart, range: [start, index] }; } return { literal: str, value: value, range: [start, index] }; } function isIdentifierName(token) { return token.type === Token.Identifier || token.type === Token.Keyword || token.type === Token.BooleanLiteral || token.type === Token.NullLiteral; } function advanceSlash() { var prevToken, checkToken; // Using the following algorithm: // https://github.com/mozilla/sweet.js/wiki/design prevToken = extra.tokens[extra.tokens.length - 1]; if (!prevToken) { // Nothing before that: it cannot be a division. return scanRegExp(); } if (prevToken.type === "Punctuator") { if (prevToken.value === ")") { checkToken = extra.tokens[extra.openParenToken - 1]; if (checkToken && checkToken.type === "Keyword" && (checkToken.value === "if" || checkToken.value === "while" || checkToken.value === "for" || checkToken.value === "with")) { return scanRegExp(); } return scanPunctuator(); } if (prevToken.value === "}") { // Dividing a function by anything makes little sense, // but we have to check for that. if (extra.tokens[extra.openCurlyToken - 3] && extra.tokens[extra.openCurlyToken - 3].type === "Keyword") { // Anonymous function. checkToken = extra.tokens[extra.openCurlyToken - 4]; if (!checkToken) { return scanPunctuator(); } } else if (extra.tokens[extra.openCurlyToken - 4] && extra.tokens[extra.openCurlyToken - 4].type === "Keyword") { // Named function. checkToken = extra.tokens[extra.openCurlyToken - 5]; if (!checkToken) { return scanRegExp(); } } else { return scanPunctuator(); } // checkToken determines whether the function is // a declaration or an expression. if (FnExprTokens.indexOf(checkToken.value) >= 0) { // It is an expression. return scanPunctuator(); } // It is a declaration. return scanRegExp(); } return scanRegExp(); } if (prevToken.type === "Keyword") { return scanRegExp(); } return scanPunctuator(); } function advance() { var ch; if (state.inXJSChild) { return advanceXJSChild(); } skipComment(); if (index >= length) { return { type: Token.EOF, lineNumber: lineNumber, lineStart: lineStart, range: [index, index] }; } ch = source.charCodeAt(index); // Very common: ( and ) and ; if (ch === 40 || ch === 41 || ch === 58) { return scanPunctuator(); } // String literal starts with single quote (#39) or double quote (#34). if (ch === 39 || ch === 34) { if (state.inXJSTag) { return scanXJSStringLiteral(); } return scanStringLiteral(); } if (state.inXJSTag && isXJSIdentifierStart(ch)) { return scanXJSIdentifier(); } if (ch === 96) { return scanTemplate(); } if (isIdentifierStart(ch)) { return scanIdentifier(); } // Dot (.) char #46 can also start a floating-point number, hence the need // to check the next character. if (ch === 46) { if (isDecimalDigit(source.charCodeAt(index + 1))) { return scanNumericLiteral(); } return scanPunctuator(); } if (isDecimalDigit(ch)) { return scanNumericLiteral(); } // Slash (/) char #47 can also start a regex. if (extra.tokenize && ch === 47) { return advanceSlash(); } return scanPunctuator(); } function lex() { var token; token = lookahead; index = token.range[1]; lineNumber = token.lineNumber; lineStart = token.lineStart; lookahead = advance(); index = token.range[1]; lineNumber = token.lineNumber; lineStart = token.lineStart; return token; } function peek() { var pos, line, start; pos = index; line = lineNumber; start = lineStart; lookahead = advance(); index = pos; lineNumber = line; lineStart = start; } function lookahead2() { var adv, pos, line, start, result; // If we are collecting the tokens, don't grab the next one yet. adv = (typeof extra.advance === 'function') ? extra.advance : advance; pos = index; line = lineNumber; start = lineStart; // Scan for the next immediate token. if (lookahead === null) { lookahead = adv(); } index = lookahead.range[1]; lineNumber = lookahead.lineNumber; lineStart = lookahead.lineStart; // Grab the token right after. result = adv(); index = pos; lineNumber = line; lineStart = start; return result; } SyntaxTreeDelegate = { name: 'SyntaxTree', postProcess: function (node) { return node; }, createArrayExpression: function (elements) { return { type: Syntax.ArrayExpression, elements: elements }; }, createAssignmentExpression: function (operator, left, right) { return { type: Syntax.AssignmentExpression, operator: operator, left: left, right: right }; }, createBinaryExpression: function (operator, left, right) { var type = (operator === '||' || operator === '&&') ? Syntax.LogicalExpression : Syntax.BinaryExpression; return { type: type, operator: operator, left: left, right: right }; }, createBlockStatement: function (body) { return { type: Syntax.BlockStatement, body: body }; }, createBreakStatement: function (label) { return { type: Syntax.BreakStatement, label: label }; }, createCallExpression: function (callee, args) { return { type: Syntax.CallExpression, callee: callee, 'arguments': args }; }, createCatchClause: function (param, body) { return { type: Syntax.CatchClause, param: param, body: body }; }, createConditionalExpression: function (test, consequent, alternate) { return { type: Syntax.ConditionalExpression, test: test, consequent: consequent, alternate: alternate }; }, createContinueStatement: function (label) { return { type: Syntax.ContinueStatement, label: label }; }, createDebuggerStatement: function () { return { type: Syntax.DebuggerStatement }; }, createDoWhileStatement: function (body, test) { return { type: Syntax.DoWhileStatement, body: body, test: test }; }, createEmptyStatement: function () { return { type: Syntax.EmptyStatement }; }, createExpressionStatement: function (expression) { return { type: Syntax.ExpressionStatement, expression: expression }; }, createForStatement: function (init, test, update, body) { return { type: Syntax.ForStatement, init: init, test: test, update: update, body: body }; }, createForInStatement: function (left, right, body) { return { type: Syntax.ForInStatement, left: left, right: right, body: body, each: false }; }, createForOfStatement: function (left, right, body) { return { type: Syntax.ForOfStatement, left: left, right: right, body: body, }; }, createFunctionDeclaration: function (id, params, defaults, body, rest, generator, expression) { return { type: Syntax.FunctionDeclaration, id: id, params: params, defaults: defaults, body: body, rest: rest, generator: generator, expression: expression }; }, createFunctionExpression: function (id, params, defaults, body, rest, generator, expression) { return { type: Syntax.FunctionExpression, id: id, params: params, defaults: defaults, body: body, rest: rest, generator: generator, expression: expression }; }, createIdentifier: function (name) { return { type: Syntax.Identifier, name: name }; }, createXJSAttribute: function (name, value) { return { type: Syntax.XJSAttribute, name: name, value: value }; }, createXJSIdentifier: function (name, namespace) { return { type: Syntax.XJSIdentifier, name: name, namespace: namespace }; }, createXJSElement: function (openingElement, closingElement, children) { return { type: Syntax.XJSElement, name: openingElement.name, selfClosing: openingElement.selfClosing, openingElement: openingElement, closingElement: closingElement, attributes: openingElement.attributes, children: children }; }, createXJSEmptyExpression: function () { return { type: Syntax.XJSEmptyExpression }; }, createXJSExpressionContainer: function (expression) { return { type: Syntax.XJSExpressionContainer, expression: expression }; }, createXJSOpeningElement: function (name, attributes, selfClosing) { return { type: Syntax.XJSOpeningElement, name: name, selfClosing: selfClosing, attributes: attributes }; }, createXJSClosingElement: function (name) { return { type: Syntax.XJSClosingElement, name: name }; }, createIfStatement: function (test, consequent, alternate) { return { type: Syntax.IfStatement, test: test, consequent: consequent, alternate: alternate }; }, createLabeledStatement: function (label, body) { return { type: Syntax.LabeledStatement, label: label, body: body }; }, createLiteral: function (token) { return { type: Syntax.Literal, value: token.value, raw: source.slice(token.range[0], token.range[1]) }; }, createMemberExpression: function (accessor, object, property) { return { type: Syntax.MemberExpression, computed: accessor === '[', object: object, property: property }; }, createNewExpression: function (callee, args) { return { type: Syntax.NewExpression, callee: callee, 'arguments': args }; }, createObjectExpression: function (properties) { return { type: Syntax.ObjectExpression, properties: properties }; }, createPostfixExpression: function (operator, argument) { return { type: Syntax.UpdateExpression, operator: operator, argument: argument, prefix: false }; }, createProgram: function (body) { return { type: Syntax.Program, body: body }; }, createProperty: function (kind, key, value, method, shorthand) { return { type: Syntax.Property, key: key, value: value, kind: kind, method: method, shorthand: shorthand }; }, createReturnStatement: function (argument) { return { type: Syntax.ReturnStatement, argument: argument }; }, createSequenceExpression: function (expressions) { return { type: Syntax.SequenceExpression, expressions: expressions }; }, createSwitchCase: function (test, consequent) { return { type: Syntax.SwitchCase, test: test, consequent: consequent }; }, createSwitchStatement: function (discriminant, cases) { return { type: Syntax.SwitchStatement, discriminant: discriminant, cases: cases }; }, createThisExpression: function () { return { type: Syntax.ThisExpression }; }, createThrowStatement: function (argument) { return { type: Syntax.ThrowStatement, argument: argument }; }, createTryStatement: function (block, guardedHandlers, handlers, finalizer) { return { type: Syntax.TryStatement, block: block, guardedHandlers: guardedHandlers, handlers: handlers, finalizer: finalizer }; }, createUnaryExpression: function (operator, argument) { if (operator === '++' || operator === '--') { return { type: Syntax.UpdateExpression, operator: operator, argument: argument, prefix: true }; } return { type: Syntax.UnaryExpression, operator: operator, argument: argument }; }, createVariableDeclaration: function (declarations, kind) { return { type: Syntax.VariableDeclaration, declarations: declarations, kind: kind }; }, createVariableDeclarator: function (id, init) { return { type: Syntax.VariableDeclarator, id: id, init: init }; }, createWhileStatement: function (test, body) { return { type: Syntax.WhileStatement, test: test, body: body }; }, createWithStatement: function (object, body) { return { type: Syntax.WithStatement, object: object, body: body }; }, createTemplateElement: function (value, tail) { return { type: Syntax.TemplateElement, value: value, tail: tail }; }, createTemplateLiteral: function (quasis, expressions) { return { type: Syntax.TemplateLiteral, quasis: quasis, expressions: expressions }; }, createSpreadElement: function (argument) { return { type: Syntax.SpreadElement, argument: argument }; }, createTaggedTemplateExpression: function (tag, quasi) { return { type: Syntax.TaggedTemplateExpression, tag: tag, quasi: quasi }; }, createArrowFunctionExpression: function (params, defaults, body, rest, expression) { return { type: Syntax.ArrowFunctionExpression, id: null, params: params, defaults: defaults, body: body, rest: rest, generator: false, expression: expression }; }, createMethodDefinition: function (propertyType, kind, key, value) { return { type: Syntax.MethodDefinition, key: key, value: value, kind: kind, 'static': propertyType === ClassPropertyType.static }; }, createClassBody: function (body) { return { type: Syntax.ClassBody, body: body }; }, createClassExpression: function (id, superClass, body) { return { type: Syntax.ClassExpression, id: id, superClass: superClass, body: body }; }, createClassDeclaration: function (id, superClass, body) { return { type: Syntax.ClassDeclaration, id: id, superClass: superClass, body: body }; }, createPath: function (body) { return { type: Syntax.Path, body: body }; }, createGlob: function () { return { type: Syntax.Glob }; }, createExportSpecifier: function (id, from) { return { type: Syntax.ExportSpecifier, id: id, from: from }; }, createExportSpecifierSet: function (specifiers) { return { type: Syntax.ExportSpecifierSet, specifiers: specifiers }; }, createExportDeclaration: function (declaration, specifiers) { return { type: Syntax.ExportDeclaration, declaration: declaration, specifiers: specifiers }; }, createImportSpecifier: function (id, from) { return { type: Syntax.ImportSpecifier, id: id, from: from }; }, createImportDeclaration: function (specifiers, from) { return { type: Syntax.ImportDeclaration, specifiers: specifiers, from: from }; }, createYieldExpression: function (argument, delegate) { return { type: Syntax.YieldExpression, argument: argument, delegate: delegate }; }, createModuleDeclaration: function (id, from, body) { return { type: Syntax.ModuleDeclaration, id: id, from: from, body: body }; } }; // Return true if there is a line terminator before the next token. function peekLineTerminator() { var pos, line, start, found; pos = index; line = lineNumber; start = lineStart; skipComment(); found = lineNumber !== line; index = pos; lineNumber = line; lineStart = start; return found; } // Throw an exception function throwError(token, messageFormat) { var error, args = Array.prototype.slice.call(arguments, 2), msg = messageFormat.replace( /%(\d)/g, function (whole, index) { assert(index < args.length, 'Message reference must be in range'); return args[index]; } ); if (typeof token.lineNumber === 'number') { error = new Error('Line ' + token.lineNumber + ': ' + msg); error.index = token.range[0]; error.lineNumber = token.lineNumber; error.column = token.range[0] - lineStart + 1; } else { error = new Error('Line ' + lineNumber + ': ' + msg); error.index = index; error.lineNumber = lineNumber; error.column = index - lineStart + 1; } error.description = msg; throw error; } function throwErrorTolerant() { try { throwError.apply(null, arguments); } catch (e) { if (extra.errors) { extra.errors.push(e); } else { throw e; } } } // Throw an exception because of the token. function throwUnexpected(token) { if (token.type === Token.EOF) { throwError(token, Messages.UnexpectedEOS); } if (token.type === Token.NumericLiteral) { throwError(token, Messages.UnexpectedNumber); } if (token.type === Token.StringLiteral) { throwError(token, Messages.UnexpectedString); } if (token.type === Token.Identifier) { throwError(token, Messages.UnexpectedIdentifier); } if (token.type === Token.Keyword) { if (isFutureReservedWord(token.value)) { throwError(token, Messages.UnexpectedReserved); } else if (strict && isStrictModeReservedWord(token.value)) { throwErrorTolerant(token, Messages.StrictReservedWord); return; } throwError(token, Messages.UnexpectedToken, token.value); } if (token.type === Token.Template) { throwError(token, Messages.UnexpectedTemplate, token.value.raw); } // BooleanLiteral, NullLiteral, or Punctuator. throwError(token, Messages.UnexpectedToken, token.value); } // Expect the next token to match the specified punctuator. // If not, an exception will be thrown. function expect(value) { var token = lex(); if (token.type !== Token.Punctuator || token.value !== value) { throwUnexpected(token); } } // Expect the next token to match the specified keyword. // If not, an exception will be thrown. function expectKeyword(keyword) { var token = lex(); if (token.type !== Token.Keyword || token.value !== keyword) { throwUnexpected(token); } } // Return true if the next token matches the specified punctuator. function match(value) { return lookahead.type === Token.Punctuator && lookahead.value === value; } // Return true if the next token matches the specified keyword function matchKeyword(keyword) { return lookahead.type === Token.Keyword && lookahead.value === keyword; } // Return true if the next token matches the specified contextual keyword function matchContextualKeyword(keyword) { return lookahead.type === Token.Identifier && lookahead.value === keyword; } // Return true if the next token is an assignment operator function matchAssign() { var op; if (lookahead.type !== Token.Punctuator) { return false; } op = lookahead.value; return op === '=' || op === '*=' || op === '/=' || op === '%=' || op === '+=' || op === '-=' || op === '<<=' || op === '>>=' || op === '>>>=' || op === '&=' || op === '^=' || op === '|='; } function consumeSemicolon() { var line; // Catch the very common case first: immediately a semicolon (char #59). if (source.charCodeAt(index) === 59) { lex(); return; } line = lineNumber; skipComment(); if (lineNumber !== line) { return; } if (match(';')) { lex(); return; } if (lookahead.type !== Token.EOF && !match('}')) { throwUnexpected(lookahead); } } // Return true if provided expression is LeftHandSideExpression function isLeftHandSide(expr) { return expr.type === Syntax.Identifier || expr.type === Syntax.MemberExpression; } function isAssignableLeftHandSide(expr) { return isLeftHandSide(expr) || expr.type === Syntax.ObjectPattern || expr.type === Syntax.ArrayPattern; } // 11.1.4 Array Initialiser function parseArrayInitialiser() { var elements = [], blocks = [], filter = null, tmp, possiblecomprehension = true, body; expect('['); while (!match(']')) { if (lookahead.value === 'for' && lookahead.type === Token.Keyword) { if (!possiblecomprehension) { throwError({}, Messages.ComprehensionError); } matchKeyword('for'); tmp = parseForStatement({ignore_body: true}); tmp.of = tmp.type === Syntax.ForOfStatement; tmp.type = Syntax.ComprehensionBlock; if (tmp.left.kind) { // can't be let or const throwError({}, Messages.ComprehensionError); } blocks.push(tmp); } else if (lookahead.value === 'if' && lookahead.type === Token.Keyword) { if (!possiblecomprehension) { throwError({}, Messages.ComprehensionError); } expectKeyword('if'); expect('('); filter = parseExpression(); expect(')'); } else if (lookahead.value === ',' && lookahead.type === Token.Punctuator) { possiblecomprehension = false; // no longer allowed. lex(); elements.push(null); } else { tmp = parseSpreadOrAssignmentExpression(); elements.push(tmp); if (tmp && tmp.type === Syntax.SpreadElement) { if (!match(']')) { throwError({}, Messages.ElementAfterSpreadElement); } } else if (!(match(']') || matchKeyword('for') || matchKeyword('if'))) { expect(','); // this lexes. possiblecomprehension = false; } } } expect(']'); if (filter && !blocks.length) { throwError({}, Messages.ComprehensionRequiresBlock); } if (blocks.length) { if (elements.length !== 1) { throwError({}, Messages.ComprehensionError); } return { type: Syntax.ComprehensionExpression, filter: filter, blocks: blocks, body: elements[0] }; } return delegate.createArrayExpression(elements); } // 11.1.5 Object Initialiser function parsePropertyFunction(options) { var previousStrict, previousYieldAllowed, params, body; previousStrict = strict; previousYieldAllowed = state.yieldAllowed; state.yieldAllowed = options.generator; params = options.params || []; body = parseConciseBody(); if (options.name && strict && isRestrictedWord(params[0].name)) { throwErrorTolerant(options.name, Messages.StrictParamName); } if (state.yieldAllowed && !state.yieldFound) { throwError({}, Messages.NoYieldInGenerator); } strict = previousStrict; state.yieldAllowed = previousYieldAllowed; return delegate.createFunctionExpression(null, params, [], body, options.rest || null, options.generator, body.type !== Syntax.BlockStatement); } function parsePropertyMethodFunction(options) { var previousStrict, tmp, method; previousStrict = strict; strict = true; tmp = parseParams(); if (tmp.stricted) { throwErrorTolerant(tmp.stricted, tmp.message); } method = parsePropertyFunction({ params: tmp.params, rest: tmp.rest, generator: options.generator }); strict = previousStrict; return method; } function parseObjectPropertyKey() { var token = lex(); // Note: This function is called only from parseObjectProperty(), where // EOF and Punctuator tokens are already filtered out. if (token.type === Token.StringLiteral || token.type === Token.NumericLiteral) { if (strict && token.octal) { throwErrorTolerant(token, Messages.StrictOctalLiteral); } return delegate.createLiteral(token); } return delegate.createIdentifier(token.value); } function parseObjectProperty() { var token, key, id, value, param; token = lookahead; if (token.type === Token.Identifier) { id = parseObjectPropertyKey(); // Property Assignment: Getter and Setter. if (token.value === 'get' && !(match(':') || match('('))) { key = parseObjectPropertyKey(); expect('('); expect(')'); return delegate.createProperty('get', key, parsePropertyFunction({ generator: false }), false, false); } if (token.value === 'set' && !(match(':') || match('('))) { key = parseObjectPropertyKey(); expect('('); token = lookahead; param = [ parseVariableIdentifier() ]; expect(')'); return delegate.createProperty('set', key, parsePropertyFunction({ params: param, generator: false, name: token }), false, false); } if (match(':')) { lex(); return delegate.createProperty('init', id, parseAssignmentExpression(), false, false); } if (match('(')) { return delegate.createProperty('init', id, parsePropertyMethodFunction({ generator: false }), true, false); } return delegate.createProperty('init', id, id, false, true); } if (token.type === Token.EOF || token.type === Token.Punctuator) { if (!match('*')) { throwUnexpected(token); } lex(); id = parseObjectPropertyKey(); if (!match('(')) { throwUnexpected(lex()); } return delegate.createProperty('init', id, parsePropertyMethodFunction({ generator: true }), true, false); } key = parseObjectPropertyKey(); if (match(':')) { lex(); return delegate.createProperty('init', key, parseAssignmentExpression(), false, false); } if (match('(')) { return delegate.createProperty('init', key, parsePropertyMethodFunction({ generator: false }), true, false); } throwUnexpected(lex()); } function parseObjectInitialiser() { var properties = [], property, name, key, kind, map = {}, toString = String; expect('{'); while (!match('}')) { property = parseObjectProperty(); if (property.key.type === Syntax.Identifier) { name = property.key.name; } else { name = toString(property.key.value); } kind = (property.kind === 'init') ? PropertyKind.Data : (property.kind === 'get') ? PropertyKind.Get : PropertyKind.Set; key = '$' + name; if (Object.prototype.hasOwnProperty.call(map, key)) { if (map[key] === PropertyKind.Data) { if (strict && kind === PropertyKind.Data) { throwErrorTolerant({}, Messages.StrictDuplicateProperty); } else if (kind !== PropertyKind.Data) { throwErrorTolerant({}, Messages.AccessorDataProperty); } } else { if (kind === PropertyKind.Data) { throwErrorTolerant({}, Messages.AccessorDataProperty); } else if (map[key] & kind) { throwErrorTolerant({}, Messages.AccessorGetSet); } } map[key] |= kind; } else { map[key] = kind; } properties.push(property); if (!match('}')) { expect(','); } } expect('}'); return delegate.createObjectExpression(properties); } function parseTemplateElement(option) { var token = scanTemplateElement(option); if (strict && token.octal) { throwError(token, Messages.StrictOctalLiteral); } return delegate.createTemplateElement({ raw: token.value.raw, cooked: token.value.cooked }, token.tail); } function parseTemplateLiteral() { var quasi, quasis, expressions; quasi = parseTemplateElement({ head: true }); quasis = [ quasi ]; expressions = []; while (!quasi.tail) { expressions.push(parseExpression()); quasi = parseTemplateElement({ head: false }); quasis.push(quasi); } return delegate.createTemplateLiteral(quasis, expressions); } // 11.1.6 The Grouping Operator function parseGroupExpression() { var expr; expect('('); ++state.parenthesizedCount; state.allowArrowFunction = !state.allowArrowFunction; expr = parseExpression(); state.allowArrowFunction = false; if (expr.type !== Syntax.ArrowFunctionExpression) { expect(')'); } return expr; } // 11.1 Primary Expressions function parsePrimaryExpression() { var type, token; token = lookahead; type = lookahead.type; if (type === Token.Identifier) { lex(); return delegate.createIdentifier(token.value); } if (type === Token.StringLiteral || type === Token.NumericLiteral) { if (strict && lookahead.octal) { throwErrorTolerant(lookahead, Messages.StrictOctalLiteral); } return delegate.createLiteral(lex()); } if (type === Token.Keyword) { if (matchKeyword('this')) { lex(); return delegate.createThisExpression(); } if (matchKeyword('function')) { return parseFunctionExpression(); } if (matchKeyword('class')) { return parseClassExpression(); } if (matchKeyword('super')) { lex(); return delegate.createIdentifier('super'); } } if (type === Token.BooleanLiteral) { token = lex(); token.value = (token.value === 'true'); return delegate.createLiteral(token); } if (type === Token.NullLiteral) { token = lex(); token.value = null; return delegate.createLiteral(token); } if (match('[')) { return parseArrayInitialiser(); } if (match('{')) { return parseObjectInitialiser(); } if (match('(')) { return parseGroupExpression(); } if (match('/') || match('/=')) { return delegate.createLiteral(scanRegExp()); } if (type === Token.Template) { return parseTemplateLiteral(); } if (match('<')) { return parseXJSElement(); } return throwUnexpected(lex()); } // 11.2 Left-Hand-Side Expressions function parseArguments() { var args = [], arg; expect('('); if (!match(')')) { while (index < length) { arg = parseSpreadOrAssignmentExpression(); args.push(arg); if (match(')')) { break; } else if (arg.type === Syntax.SpreadElement) { throwError({}, Messages.ElementAfterSpreadElement); } expect(','); } } expect(')'); return args; } function parseSpreadOrAssignmentExpression() { if (match('...')) { lex(); return delegate.createSpreadElement(parseAssignmentExpression()); } return parseAssignmentExpression(); } function parseNonComputedProperty() { var token = lex(); if (!isIdentifierName(token)) { throwUnexpected(token); } return delegate.createIdentifier(token.value); } function parseNonComputedMember() { expect('.'); return parseNonComputedProperty(); } function parseComputedMember() { var expr; expect('['); expr = parseExpression(); expect(']'); return expr; } function parseNewExpression() { var callee, args; expectKeyword('new'); callee = parseLeftHandSideExpression(); args = match('(') ? parseArguments() : []; return delegate.createNewExpression(callee, args); } function parseLeftHandSideExpressionAllowCall() { var expr, args, property; expr = matchKeyword('new') ? parseNewExpression() : parsePrimaryExpression(); while (match('.') || match('[') || match('(') || lookahead.type === Token.Template) { if (match('(')) { args = parseArguments(); expr = delegate.createCallExpression(expr, args); } else if (match('[')) { expr = delegate.createMemberExpression('[', expr, parseComputedMember()); } else if (match('.')) { expr = delegate.createMemberExpression('.', expr, parseNonComputedMember()); } else { expr = delegate.createTaggedTemplateExpression(expr, parseTemplateLiteral()); } } return expr; } function parseLeftHandSideExpression() { var expr, property; expr = matchKeyword('new') ? parseNewExpression() : parsePrimaryExpression(); while (match('.') || match('[') || lookahead.type === Token.Template) { if (match('[')) { expr = delegate.createMemberExpression('[', expr, parseComputedMember()); } else if (match('.')) { expr = delegate.createMemberExpression('.', expr, parseNonComputedMember()); } else { expr = delegate.createTaggedTemplateExpression(expr, parseTemplateLiteral()); } } return expr; } // 11.3 Postfix Expressions function parsePostfixExpression() { var expr = parseLeftHandSideExpressionAllowCall(), token = lookahead; if (lookahead.type !== Token.Punctuator) { return expr; } if ((match('++') || match('--')) && !peekLineTerminator()) { // 11.3.1, 11.3.2 if (strict && expr.type === Syntax.Identifier && isRestrictedWord(expr.name)) { throwErrorTolerant({}, Messages.StrictLHSPostfix); } if (!isLeftHandSide(expr)) { throwError({}, Messages.InvalidLHSInAssignment); } token = lex(); expr = delegate.createPostfixExpression(token.value, expr); } return expr; } // 11.4 Unary Operators function parseUnaryExpression() { var token, expr; if (lookahead.type !== Token.Punctuator && lookahead.type !== Token.Keyword) { return parsePostfixExpression(); } if (match('++') || match('--')) { token = lex(); expr = parseUnaryExpression(); // 11.4.4, 11.4.5 if (strict && expr.type === Syntax.Identifier && isRestrictedWord(expr.name)) { throwErrorTolerant({}, Messages.StrictLHSPrefix); } if (!isLeftHandSide(expr)) { throwError({}, Messages.InvalidLHSInAssignment); } return delegate.createUnaryExpression(token.value, expr); } if (match('+') || match('-') || match('~') || match('!')) { token = lex(); expr = parseUnaryExpression(); return delegate.createUnaryExpression(token.value, expr); } if (matchKeyword('delete') || matchKeyword('void') || matchKeyword('typeof')) { token = lex(); expr = parseUnaryExpression(); expr = delegate.createUnaryExpression(token.value, expr); if (strict && expr.operator === 'delete' && expr.argument.type === Syntax.Identifier) { throwErrorTolerant({}, Messages.StrictDelete); } return expr; } return parsePostfixExpression(); } function binaryPrecedence(token, allowIn) { var prec = 0; if (token.type !== Token.Punctuator && token.type !== Token.Keyword) { return 0; } switch (token.value) { case '||': prec = 1; break; case '&&': prec = 2; break; case '|': prec = 3; break; case '^': prec = 4; break; case '&': prec = 5; break; case '==': case '!=': case '===': case '!==': prec = 6; break; case '<': case '>': case '<=': case '>=': case 'instanceof': prec = 7; break; case 'in': prec = allowIn ? 7 : 0; break; case '<<': case '>>': case '>>>': prec = 8; break; case '+': case '-': prec = 9; break; case '*': case '/': case '%': prec = 11; break; default: break; } return prec; } // 11.5 Multiplicative Operators // 11.6 Additive Operators // 11.7 Bitwise Shift Operators // 11.8 Relational Operators // 11.9 Equality Operators // 11.10 Binary Bitwise Operators // 11.11 Binary Logical Operators function parseBinaryExpression() { var expr, token, prec, previousAllowIn, stack, right, operator, left, i; previousAllowIn = state.allowIn; state.allowIn = true; expr = parseUnaryExpression(); token = lookahead; prec = binaryPrecedence(token, previousAllowIn); if (prec === 0) { return expr; } token.prec = prec; lex(); stack = [expr, token, parseUnaryExpression()]; while ((prec = binaryPrecedence(lookahead, previousAllowIn)) > 0) { // Reduce: make a binary expression from the three topmost entries. while ((stack.length > 2) && (prec <= stack[stack.length - 2].prec)) { right = stack.pop(); operator = stack.pop().value; left = stack.pop(); stack.push(delegate.createBinaryExpression(operator, left, right)); } // Shift. token = lex(); token.prec = prec; stack.push(token); stack.push(parseUnaryExpression()); } state.allowIn = previousAllowIn; // Final reduce to clean-up the stack. i = stack.length - 1; expr = stack[i]; while (i > 1) { expr = delegate.createBinaryExpression(stack[i - 1].value, stack[i - 2], expr); i -= 2; } return expr; } // 11.12 Conditional Operator function parseConditionalExpression() { var expr, previousAllowIn, consequent, alternate; expr = parseBinaryExpression(); if (match('?')) { lex(); previousAllowIn = state.allowIn; state.allowIn = true; consequent = parseAssignmentExpression(); state.allowIn = previousAllowIn; expect(':'); alternate = parseAssignmentExpression(); expr = delegate.createConditionalExpression(expr, consequent, alternate); } return expr; } // 11.13 Assignment Operators function reinterpretAsAssignmentBindingPattern(expr) { var i, len, property, element; if (expr.type === Syntax.ObjectExpression) { expr.type = Syntax.ObjectPattern; for (i = 0, len = expr.properties.length; i < len; i += 1) { property = expr.properties[i]; if (property.kind !== 'init') { throwError({}, Messages.InvalidLHSInAssignment); } reinterpretAsAssignmentBindingPattern(property.value); } } else if (expr.type === Syntax.ArrayExpression) { expr.type = Syntax.ArrayPattern; for (i = 0, len = expr.elements.length; i < len; i += 1) { element = expr.elements[i]; if (element) { reinterpretAsAssignmentBindingPattern(element); } } } else if (expr.type === Syntax.Identifier) { if (isRestrictedWord(expr.name)) { throwError({}, Messages.InvalidLHSInAssignment); } } else if (expr.type === Syntax.SpreadElement) { reinterpretAsAssignmentBindingPattern(expr.argument); if (expr.argument.type === Syntax.ObjectPattern) { throwError({}, Messages.ObjectPatternAsSpread); } } else { if (expr.type !== Syntax.MemberExpression && expr.type !== Syntax.CallExpression && expr.type !== Syntax.NewExpression) { throwError({}, Messages.InvalidLHSInAssignment); } } } function reinterpretAsDestructuredParameter(options, expr) { var i, len, property, element; if (expr.type === Syntax.ObjectExpression) { expr.type = Syntax.ObjectPattern; for (i = 0, len = expr.properties.length; i < len; i += 1) { property = expr.properties[i]; if (property.kind !== 'init') { throwError({}, Messages.InvalidLHSInFormalsList); } reinterpretAsDestructuredParameter(options, property.value); } } else if (expr.type === Syntax.ArrayExpression) { expr.type = Syntax.ArrayPattern; for (i = 0, len = expr.elements.length; i < len; i += 1) { element = expr.elements[i]; if (element) { reinterpretAsDestructuredParameter(options, element); } } } else if (expr.type === Syntax.Identifier) { validateParam(options, expr, expr.name); } else { if (expr.type !== Syntax.MemberExpression) { throwError({}, Messages.InvalidLHSInFormalsList); } } } function reinterpretAsCoverFormalsList(expressions) { var i, len, param, params, options, rest; params = []; rest = null; options = { paramSet: {} }; for (i = 0, len = expressions.length; i < len; i += 1) { param = expressions[i]; if (param.type === Syntax.Identifier) { params.push(param); validateParam(options, param, param.name); } else if (param.type === Syntax.ObjectExpression || param.type === Syntax.ArrayExpression) { reinterpretAsDestructuredParameter(options, param); params.push(param); } else if (param.type === Syntax.SpreadElement) { assert(i === len - 1, "It is guaranteed that SpreadElement is last element by parseExpression"); reinterpretAsDestructuredParameter(options, param.argument); rest = param.argument; } else { return null; } } if (options.firstRestricted) { throwError(options.firstRestricted, options.message); } if (options.stricted) { throwErrorTolerant(options.stricted, options.message); } return { params: params, rest: rest }; } function parseArrowFunctionExpression(options) { var previousStrict, previousYieldAllowed, body; expect('=>'); previousStrict = strict; previousYieldAllowed = state.yieldAllowed; strict = true; state.yieldAllowed = false; body = parseConciseBody(); strict = previousStrict; state.yieldAllowed = previousYieldAllowed; return delegate.createArrowFunctionExpression(options.params, [], body, options.rest, body.type !== Syntax.BlockStatement); } function parseAssignmentExpression() { var expr, token, params, oldParenthesizedCount; if (matchKeyword('yield')) { return parseYieldExpression(); } oldParenthesizedCount = state.parenthesizedCount; if (match('(')) { token = lookahead2(); if ((token.type === Token.Punctuator && token.value === ')') || token.value === '...') { params = parseParams(); if (!match('=>')) { throwUnexpected(lex()); } return parseArrowFunctionExpression(params); } } token = lookahead; expr = parseConditionalExpression(); if (match('=>') && expr.type === Syntax.Identifier) { if (state.parenthesizedCount === oldParenthesizedCount || state.parenthesizedCount === (oldParenthesizedCount + 1)) { if (isRestrictedWord(expr.name)) { throwError({}, Messages.StrictParamName); } return parseArrowFunctionExpression({ params: [ expr ], rest: null }); } } if (matchAssign()) { // 11.13.1 if (strict && expr.type === Syntax.Identifier && isRestrictedWord(expr.name)) { throwErrorTolerant(token, Messages.StrictLHSAssignment); } // ES.next draf 11.13 Runtime Semantics step 1 if (match('=') && (expr.type === Syntax.ObjectExpression || expr.type === Syntax.ArrayExpression)) { reinterpretAsAssignmentBindingPattern(expr); } else if (!isLeftHandSide(expr)) { throwError({}, Messages.InvalidLHSInAssignment); } expr = delegate.createAssignmentExpression(lex().value, expr, parseAssignmentExpression()); } return expr; } // 11.14 Comma Operator function parseExpression() { var expr, expressions, sequence, coverFormalsList, spreadFound, token; expr = parseAssignmentExpression(); expressions = [ expr ]; if (match(',')) { while (index < length) { if (!match(',')) { break; } lex(); expr = parseSpreadOrAssignmentExpression(); expressions.push(expr); if (expr.type === Syntax.SpreadElement) { spreadFound = true; if (!match(')')) { throwError({}, Messages.ElementAfterSpreadElement); } break; } } sequence = delegate.createSequenceExpression(expressions); } if (state.allowArrowFunction && match(')')) { token = lookahead2(); if (token.value === '=>') { lex(); state.allowArrowFunction = false; expr = expressions; coverFormalsList = reinterpretAsCoverFormalsList(expr); if (coverFormalsList) { return parseArrowFunctionExpression(coverFormalsList); } throwUnexpected(token); } } if (spreadFound) { throwError({}, Messages.IllegalSpread); } return sequence || expr; } // 12.1 Block function parseStatementList() { var list = [], statement; while (index < length) { if (match('}')) { break; } statement = parseSourceElement(); if (typeof statement === 'undefined') { break; } list.push(statement); } return list; } function parseBlock() { var block; expect('{'); block = parseStatementList(); expect('}'); return delegate.createBlockStatement(block); } // 12.2 Variable Statement function parseVariableIdentifier() { var token = lex(); if (token.type !== Token.Identifier) { throwUnexpected(token); } return delegate.createIdentifier(token.value); } function parseVariableDeclaration(kind) { var id, init = null; if (match('{')) { id = parseObjectInitialiser(); reinterpretAsAssignmentBindingPattern(id); } else if (match('[')) { id = parseArrayInitialiser(); reinterpretAsAssignmentBindingPattern(id); } else { id = parseVariableIdentifier(); // 12.2.1 if (strict && isRestrictedWord(id.name)) { throwErrorTolerant({}, Messages.StrictVarName); } } if (kind === 'const') { if (!match('=')) { throwError({}, Messages.NoUnintializedConst); } expect('='); init = parseAssignmentExpression(); } else if (match('=')) { lex(); init = parseAssignmentExpression(); } return delegate.createVariableDeclarator(id, init); } function parseVariableDeclarationList(kind) { var list = []; do { list.push(parseVariableDeclaration(kind)); if (!match(',')) { break; } lex(); } while (index < length); return list; } function parseVariableStatement() { var declarations; expectKeyword('var'); declarations = parseVariableDeclarationList(); consumeSemicolon(); return delegate.createVariableDeclaration(declarations, 'var'); } // kind may be `const` or `let` // Both are experimental and not in the specification yet. // see http://wiki.ecmascript.org/doku.php?id=harmony:const // and http://wiki.ecmascript.org/doku.php?id=harmony:let function parseConstLetDeclaration(kind) { var declarations; expectKeyword(kind); declarations = parseVariableDeclarationList(kind); consumeSemicolon(); return delegate.createVariableDeclaration(declarations, kind); } // http://wiki.ecmascript.org/doku.php?id=harmony:modules function parsePath() { var body = []; while (true) { body.push(parseVariableIdentifier()); if (!match('.')) { break; } lex(); } return delegate.createPath(body); } function parseGlob() { expect('*'); return delegate.createGlob(); } function parseModuleDeclaration() { var id, token, from = null; lex(); id = parseVariableIdentifier(); if (match('{')) { return delegate.createModuleDeclaration(id, from, parseModuleBlock()); } expect('='); token = lookahead; if (token.type === Token.StringLiteral) { from = parsePrimaryExpression(); } else { from = parsePath(); } consumeSemicolon(); return delegate.createModuleDeclaration(id, from, null); } function parseExportSpecifierSetProperty() { var id, from = null; id = parseVariableIdentifier(); if (match(':')) { lex(); from = parsePath(); } return delegate.createExportSpecifier(id, from); } function parseExportSpecifier() { var specifiers, id, from; if (match('{')) { lex(); specifiers = []; do { specifiers.push(parseExportSpecifierSetProperty()); } while (match(',') && lex()); expect('}'); return delegate.createExportSpecifierSet(specifiers); } from = null; if (match('*')) { id = parseGlob(); if (matchContextualKeyword('from')) { lex(); from = parsePath(); } } else { id = parseVariableIdentifier(); } return delegate.createExportSpecifier(id, from); } function parseExportDeclaration() { var token, specifiers; expectKeyword('export'); token = lookahead; if (token.type === Token.Keyword || (token.type === Token.Identifier && token.value === 'module')) { switch (token.value) { case 'function': return delegate.createExportDeclaration(parseFunctionDeclaration(), null); case 'module': return delegate.createExportDeclaration(parseModuleDeclaration(), null); case 'let': case 'const': return delegate.createExportDeclaration(parseConstLetDeclaration(token.value), null); case 'var': return delegate.createExportDeclaration(parseStatement(), null); case 'class': return delegate.createExportDeclaration(parseClassDeclaration(), null); } throwUnexpected(lex()); } specifiers = [ parseExportSpecifier() ]; if (match(',')) { while (index < length) { if (!match(',')) { break; } lex(); specifiers.push(parseExportSpecifier()); } } consumeSemicolon(); return delegate.createExportDeclaration(null, specifiers); } function parseImportDeclaration() { var specifiers, from; expectKeyword('import'); if (match('*')) { specifiers = [parseGlob()]; } else if (match('{')) { lex(); specifiers = []; do { specifiers.push(parseImportSpecifier()); } while (match(',') && lex()); expect('}'); } else { specifiers = [parseVariableIdentifier()]; } if (!matchContextualKeyword('from')) { throwError({}, Messages.NoFromAfterImport); } lex(); if (lookahead.type === Token.StringLiteral) { from = parsePrimaryExpression(); } else { from = parsePath(); } consumeSemicolon(); return delegate.createImportDeclaration(specifiers, from); } function parseImportSpecifier() { var id, from; id = parseVariableIdentifier(); from = null; if (match(':')) { lex(); from = parsePath(); } return delegate.createImportSpecifier(id, from); } // 12.3 Empty Statement function parseEmptyStatement() { expect(';'); return delegate.createEmptyStatement(); } // 12.4 Expression Statement function parseExpressionStatement() { var expr = parseExpression(); consumeSemicolon(); return delegate.createExpressionStatement(expr); } // 12.5 If statement function parseIfStatement() { var test, consequent, alternate; expectKeyword('if'); expect('('); test = parseExpression(); expect(')'); consequent = parseStatement(); if (matchKeyword('else')) { lex(); alternate = parseStatement(); } else { alternate = null; } return delegate.createIfStatement(test, consequent, alternate); } // 12.6 Iteration Statements function parseDoWhileStatement() { var body, test, oldInIteration; expectKeyword('do'); oldInIteration = state.inIteration; state.inIteration = true; body = parseStatement(); state.inIteration = oldInIteration; expectKeyword('while'); expect('('); test = parseExpression(); expect(')'); if (match(';')) { lex(); } return delegate.createDoWhileStatement(body, test); } function parseWhileStatement() { var test, body, oldInIteration; expectKeyword('while'); expect('('); test = parseExpression(); expect(')'); oldInIteration = state.inIteration; state.inIteration = true; body = parseStatement(); state.inIteration = oldInIteration; return delegate.createWhileStatement(test, body); } function parseForVariableDeclaration() { var token = lex(), declarations = parseVariableDeclarationList(); return delegate.createVariableDeclaration(declarations, token.value); } function parseForStatement(opts) { var init, test, update, left, right, body, operator, oldInIteration; init = test = update = null; expectKeyword('for'); // http://wiki.ecmascript.org/doku.php?id=proposals:iterators_and_generators&s=each if (matchContextualKeyword("each")) { throwError({}, Messages.EachNotAllowed); } expect('('); if (match(';')) { lex(); } else { if (matchKeyword('var') || matchKeyword('let') || matchKeyword('const')) { state.allowIn = false; init = parseForVariableDeclaration(); state.allowIn = true; if (init.declarations.length === 1) { if (matchKeyword('in') || matchContextualKeyword('of')) { operator = lookahead; if (!((operator.value === 'in' || init.kind !== 'var') && init.declarations[0].init)) { lex(); left = init; right = parseExpression(); init = null; } } } } else { state.allowIn = false; init = parseExpression(); state.allowIn = true; if (matchContextualKeyword('of')) { operator = lex(); left = init; right = parseExpression(); init = null; } else if (matchKeyword('in')) { // LeftHandSideExpression if (!isAssignableLeftHandSide(init)) { throwError({}, Messages.InvalidLHSInForIn); } operator = lex(); left = init; right = parseExpression(); init = null; } } if (typeof left === 'undefined') { expect(';'); } } if (typeof left === 'undefined') { if (!match(';')) { test = parseExpression(); } expect(';'); if (!match(')')) { update = parseExpression(); } } expect(')'); oldInIteration = state.inIteration; state.inIteration = true; if (!(opts !== undefined && opts.ignore_body)) { body = parseStatement(); } state.inIteration = oldInIteration; if (typeof left === 'undefined') { return delegate.createForStatement(init, test, update, body); } if (operator.value === 'in') { return delegate.createForInStatement(left, right, body); } return delegate.createForOfStatement(left, right, body); } // 12.7 The continue statement function parseContinueStatement() { var label = null, key; expectKeyword('continue'); // Optimize the most common form: 'continue;'. if (source.charCodeAt(index) === 59) { lex(); if (!state.inIteration) { throwError({}, Messages.IllegalContinue); } return delegate.createContinueStatement(null); } if (peekLineTerminator()) { if (!state.inIteration) { throwError({}, Messages.IllegalContinue); } return delegate.createContinueStatement(null); } if (lookahead.type === Token.Identifier) { label = parseVariableIdentifier(); key = '$' + label.name; if (!Object.prototype.hasOwnProperty.call(state.labelSet, key)) { throwError({}, Messages.UnknownLabel, label.name); } } consumeSemicolon(); if (label === null && !state.inIteration) { throwError({}, Messages.IllegalContinue); } return delegate.createContinueStatement(label); } // 12.8 The break statement function parseBreakStatement() { var label = null, key; expectKeyword('break'); // Catch the very common case first: immediately a semicolon (char #59). if (source.charCodeAt(index) === 59) { lex(); if (!(state.inIteration || state.inSwitch)) { throwError({}, Messages.IllegalBreak); } return delegate.createBreakStatement(null); } if (peekLineTerminator()) { if (!(state.inIteration || state.inSwitch)) { throwError({}, Messages.IllegalBreak); } return delegate.createBreakStatement(null); } if (lookahead.type === Token.Identifier) { label = parseVariableIdentifier(); key = '$' + label.name; if (!Object.prototype.hasOwnProperty.call(state.labelSet, key)) { throwError({}, Messages.UnknownLabel, label.name); } } consumeSemicolon(); if (label === null && !(state.inIteration || state.inSwitch)) { throwError({}, Messages.IllegalBreak); } return delegate.createBreakStatement(label); } // 12.9 The return statement function parseReturnStatement() { var argument = null; expectKeyword('return'); if (!state.inFunctionBody) { throwErrorTolerant({}, Messages.IllegalReturn); } // 'return' followed by a space and an identifier is very common. if (source.charCodeAt(index) === 32) { if (isIdentifierStart(source.charCodeAt(index + 1))) { argument = parseExpression(); consumeSemicolon(); return delegate.createReturnStatement(argument); } } if (peekLineTerminator()) { return delegate.createReturnStatement(null); } if (!match(';')) { if (!match('}') && lookahead.type !== Token.EOF) { argument = parseExpression(); } } consumeSemicolon(); return delegate.createReturnStatement(argument); } // 12.10 The with statement function parseWithStatement() { var object, body; if (strict) { throwErrorTolerant({}, Messages.StrictModeWith); } expectKeyword('with'); expect('('); object = parseExpression(); expect(')'); body = parseStatement(); return delegate.createWithStatement(object, body); } // 12.10 The swith statement function parseSwitchCase() { var test, consequent = [], sourceElement; if (matchKeyword('default')) { lex(); test = null; } else { expectKeyword('case'); test = parseExpression(); } expect(':'); while (index < length) { if (match('}') || matchKeyword('default') || matchKeyword('case')) { break; } sourceElement = parseSourceElement(); if (typeof sourceElement === 'undefined') { break; } consequent.push(sourceElement); } return delegate.createSwitchCase(test, consequent); } function parseSwitchStatement() { var discriminant, cases, clause, oldInSwitch, defaultFound; expectKeyword('switch'); expect('('); discriminant = parseExpression(); expect(')'); expect('{'); if (match('}')) { lex(); return delegate.createSwitchStatement(discriminant); } cases = []; oldInSwitch = state.inSwitch; state.inSwitch = true; defaultFound = false; while (index < length) { if (match('}')) { break; } clause = parseSwitchCase(); if (clause.test === null) { if (defaultFound) { throwError({}, Messages.MultipleDefaultsInSwitch); } defaultFound = true; } cases.push(clause); } state.inSwitch = oldInSwitch; expect('}'); return delegate.createSwitchStatement(discriminant, cases); } // 12.13 The throw statement function parseThrowStatement() { var argument; expectKeyword('throw'); if (peekLineTerminator()) { throwError({}, Messages.NewlineAfterThrow); } argument = parseExpression(); consumeSemicolon(); return delegate.createThrowStatement(argument); } // 12.14 The try statement function parseCatchClause() { var param, body; expectKeyword('catch'); expect('('); if (match(')')) { throwUnexpected(lookahead); } param = parseExpression(); // 12.14.1 if (strict && param.type === Syntax.Identifier && isRestrictedWord(param.name)) { throwErrorTolerant({}, Messages.StrictCatchVariable); } expect(')'); body = parseBlock(); return delegate.createCatchClause(param, body); } function parseTryStatement() { var block, handlers = [], finalizer = null; expectKeyword('try'); block = parseBlock(); if (matchKeyword('catch')) { handlers.push(parseCatchClause()); } if (matchKeyword('finally')) { lex(); finalizer = parseBlock(); } if (handlers.length === 0 && !finalizer) { throwError({}, Messages.NoCatchOrFinally); } return delegate.createTryStatement(block, [], handlers, finalizer); } // 12.15 The debugger statement function parseDebuggerStatement() { expectKeyword('debugger'); consumeSemicolon(); return delegate.createDebuggerStatement(); } // 12 Statements function parseStatement() { var type = lookahead.type, expr, labeledBody, key; if (type === Token.EOF) { throwUnexpected(lookahead); } if (type === Token.Punctuator) { switch (lookahead.value) { case ';': return parseEmptyStatement(); case '{': return parseBlock(); case '(': return parseExpressionStatement(); default: break; } } if (type === Token.Keyword) { switch (lookahead.value) { case 'break': return parseBreakStatement(); case 'continue': return parseContinueStatement(); case 'debugger': return parseDebuggerStatement(); case 'do': return parseDoWhileStatement(); case 'for': return parseForStatement(); case 'function': return parseFunctionDeclaration(); case 'class': return parseClassDeclaration(); case 'if': return parseIfStatement(); case 'return': return parseReturnStatement(); case 'switch': return parseSwitchStatement(); case 'throw': return parseThrowStatement(); case 'try': return parseTryStatement(); case 'var': return parseVariableStatement(); case 'while': return parseWhileStatement(); case 'with': return parseWithStatement(); default: break; } } expr = parseExpression(); // 12.12 Labelled Statements if ((expr.type === Syntax.Identifier) && match(':')) { lex(); key = '$' + expr.name; if (Object.prototype.hasOwnProperty.call(state.labelSet, key)) { throwError({}, Messages.Redeclaration, 'Label', expr.name); } state.labelSet[key] = true; labeledBody = parseStatement(); delete state.labelSet[key]; return delegate.createLabeledStatement(expr, labeledBody); } consumeSemicolon(); return delegate.createExpressionStatement(expr); } // 13 Function Definition function parseConciseBody() { if (match('{')) { return parseFunctionSourceElements(); } return parseAssignmentExpression(); } function parseFunctionSourceElements() { var sourceElement, sourceElements = [], token, directive, firstRestricted, oldLabelSet, oldInIteration, oldInSwitch, oldInFunctionBody, oldParenthesizedCount; expect('{'); while (index < length) { if (lookahead.type !== Token.StringLiteral) { break; } token = lookahead; sourceElement = parseSourceElement(); sourceElements.push(sourceElement); if (sourceElement.expression.type !== Syntax.Literal) { // this is not directive break; } directive = source.slice(token.range[0] + 1, token.range[1] - 1); if (directive === 'use strict') { strict = true; if (firstRestricted) { throwErrorTolerant(firstRestricted, Messages.StrictOctalLiteral); } } else { if (!firstRestricted && token.octal) { firstRestricted = token; } } } oldLabelSet = state.labelSet; oldInIteration = state.inIteration; oldInSwitch = state.inSwitch; oldInFunctionBody = state.inFunctionBody; oldParenthesizedCount = state.parenthesizedCount; state.labelSet = {}; state.inIteration = false; state.inSwitch = false; state.inFunctionBody = true; state.parenthesizedCount = 0; while (index < length) { if (match('}')) { break; } sourceElement = parseSourceElement(); if (typeof sourceElement === 'undefined') { break; } sourceElements.push(sourceElement); } expect('}'); state.labelSet = oldLabelSet; state.inIteration = oldInIteration; state.inSwitch = oldInSwitch; state.inFunctionBody = oldInFunctionBody; state.parenthesizedCount = oldParenthesizedCount; return delegate.createBlockStatement(sourceElements); } function validateParam(options, param, name) { var key = '$' + name; if (strict) { if (isRestrictedWord(name)) { options.stricted = param; options.message = Messages.StrictParamName; } if (Object.prototype.hasOwnProperty.call(options.paramSet, key)) { options.stricted = param; options.message = Messages.StrictParamDupe; } } else if (!options.firstRestricted) { if (isRestrictedWord(name)) { options.firstRestricted = param; options.message = Messages.StrictParamName; } else if (isStrictModeReservedWord(name)) { options.firstRestricted = param; options.message = Messages.StrictReservedWord; } else if (Object.prototype.hasOwnProperty.call(options.paramSet, key)) { options.firstRestricted = param; options.message = Messages.StrictParamDupe; } } options.paramSet[key] = true; } function parseParam(options) { var token, rest, param; token = lookahead; if (token.value === '...') { token = lex(); rest = true; } if (match('[')) { param = parseArrayInitialiser(); reinterpretAsDestructuredParameter(options, param); } else if (match('{')) { if (rest) { throwError({}, Messages.ObjectPatternAsRestParameter); } param = parseObjectInitialiser(); reinterpretAsDestructuredParameter(options, param); } else { param = parseVariableIdentifier(); validateParam(options, token, token.value); } if (rest) { if (!match(')')) { throwError({}, Messages.ParameterAfterRestParameter); } options.rest = param; return false; } options.params.push(param); return !match(')'); } function parseParams(firstRestricted) { var options; options = { params: [], rest: null, firstRestricted: firstRestricted }; expect('('); if (!match(')')) { options.paramSet = {}; while (index < length) { if (!parseParam(options)) { break; } expect(','); } } expect(')'); return options; } function parseFunctionDeclaration() { var id, body, token, tmp, firstRestricted, message, previousStrict, previousYieldAllowed, generator, expression; expectKeyword('function'); generator = false; if (match('*')) { lex(); generator = true; } token = lookahead; id = parseVariableIdentifier(); if (strict) { if (isRestrictedWord(token.value)) { throwErrorTolerant(token, Messages.StrictFunctionName); } } else { if (isRestrictedWord(token.value)) { firstRestricted = token; message = Messages.StrictFunctionName; } else if (isStrictModeReservedWord(token.value)) { firstRestricted = token; message = Messages.StrictReservedWord; } } tmp = parseParams(firstRestricted); firstRestricted = tmp.firstRestricted; if (tmp.message) { message = tmp.message; } previousStrict = strict; previousYieldAllowed = state.yieldAllowed; state.yieldAllowed = generator; // here we redo some work in order to set 'expression' expression = !match('{'); body = parseConciseBody(); if (strict && firstRestricted) { throwError(firstRestricted, message); } if (strict && tmp.stricted) { throwErrorTolerant(tmp.stricted, message); } if (state.yieldAllowed && !state.yieldFound) { throwError({}, Messages.NoYieldInGenerator); } strict = previousStrict; state.yieldAllowed = previousYieldAllowed; return delegate.createFunctionDeclaration(id, tmp.params, [], body, tmp.rest, generator, expression); } function parseFunctionExpression() { var token, id = null, firstRestricted, message, tmp, body, previousStrict, previousYieldAllowed, generator, expression; expectKeyword('function'); generator = false; if (match('*')) { lex(); generator = true; } if (!match('(')) { token = lookahead; id = parseVariableIdentifier(); if (strict) { if (isRestrictedWord(token.value)) { throwErrorTolerant(token, Messages.StrictFunctionName); } } else { if (isRestrictedWord(token.value)) { firstRestricted = token; message = Messages.StrictFunctionName; } else if (isStrictModeReservedWord(token.value)) { firstRestricted = token; message = Messages.StrictReservedWord; } } } tmp = parseParams(firstRestricted); firstRestricted = tmp.firstRestricted; if (tmp.message) { message = tmp.message; } previousStrict = strict; previousYieldAllowed = state.yieldAllowed; state.yieldAllowed = generator; // here we redo some work in order to set 'expression' expression = !match('{'); body = parseConciseBody(); if (strict && firstRestricted) { throwError(firstRestricted, message); } if (strict && tmp.stricted) { throwErrorTolerant(tmp.stricted, message); } if (state.yieldAllowed && !state.yieldFound) { throwError({}, Messages.NoYieldInGenerator); } strict = previousStrict; state.yieldAllowed = previousYieldAllowed; return delegate.createFunctionExpression(id, tmp.params, [], body, tmp.rest, generator, expression); } function parseYieldExpression() { var delegateFlag, expr, previousYieldAllowed; expectKeyword('yield'); if (!state.yieldAllowed) { throwErrorTolerant({}, Messages.IllegalYield); } delegateFlag = false; if (match('*')) { lex(); delegateFlag = true; } // It is a Syntax Error if any AssignmentExpression Contains YieldExpression. previousYieldAllowed = state.yieldAllowed; state.yieldAllowed = false; expr = parseAssignmentExpression(); state.yieldAllowed = previousYieldAllowed; state.yieldFound = true; return delegate.createYieldExpression(expr, delegateFlag); } // 14 Classes function parseMethodDefinition(existingPropNames) { var token, key, param, propType, isValidDuplicateProp = false; if (lookahead.value === 'static') { propType = ClassPropertyType.static; lex(); } else { propType = ClassPropertyType.prototype; } if (match('*')) { lex(); return delegate.createMethodDefinition( propType, '', parseObjectPropertyKey(), parsePropertyMethodFunction({ generator: true }) ); } token = lookahead; key = parseObjectPropertyKey(); if (token.value === 'get' && !match('(')) { key = parseObjectPropertyKey(); // It is a syntax error if any other properties have a name // duplicating this one unless they are a setter if (existingPropNames[propType].hasOwnProperty(key.name)) { isValidDuplicateProp = // There isn't already a getter for this prop existingPropNames[propType][key.name].get === undefined // There isn't already a data prop by this name && existingPropNames[propType][key.name].data === undefined // The only existing prop by this name is a setter && existingPropNames[propType][key.name].set !== undefined; if (!isValidDuplicateProp) { throwError(key, Messages.IllegalDuplicateClassProperty); } } else { existingPropNames[propType][key.name] = {}; } existingPropNames[propType][key.name].get = true; expect('('); expect(')'); return delegate.createMethodDefinition( propType, 'get', key, parsePropertyFunction({ generator: false }) ); } if (token.value === 'set' && !match('(')) { key = parseObjectPropertyKey(); // It is a syntax error if any other properties have a name // duplicating this one unless they are a getter if (existingPropNames[propType].hasOwnProperty(key.name)) { isValidDuplicateProp = // There isn't already a setter for this prop existingPropNames[propType][key.name].set === undefined // There isn't already a data prop by this name && existingPropNames[propType][key.name].data === undefined // The only existing prop by this name is a getter && existingPropNames[propType][key.name].get !== undefined; if (!isValidDuplicateProp) { throwError(key, Messages.IllegalDuplicateClassProperty); } } else { existingPropNames[propType][key.name] = {}; } existingPropNames[propType][key.name].set = true; expect('('); token = lookahead; param = [ parseVariableIdentifier() ]; expect(')'); return delegate.createMethodDefinition( propType, 'set', key, parsePropertyFunction({ params: param, generator: false, name: token }) ); } // It is a syntax error if any other properties have the same name as a // non-getter, non-setter method if (existingPropNames[propType].hasOwnProperty(key.name)) { throwError(key, Messages.IllegalDuplicateClassProperty); } else { existingPropNames[propType][key.name] = {}; } existingPropNames[propType][key.name].data = true; return delegate.createMethodDefinition( propType, '', key, parsePropertyMethodFunction({ generator: false }) ); } function parseClassElement(existingProps) { if (match(';')) { lex(); return; } return parseMethodDefinition(existingProps); } function parseClassBody() { var classElement, classElements = [], existingProps = {}; existingProps[ClassPropertyType.static] = {}; existingProps[ClassPropertyType.prototype] = {}; expect('{'); while (index < length) { if (match('}')) { break; } classElement = parseClassElement(existingProps); if (typeof classElement !== 'undefined') { classElements.push(classElement); } } expect('}'); return delegate.createClassBody(classElements); } function parseClassExpression() { var id, previousYieldAllowed, superClass = null; expectKeyword('class'); if (!matchKeyword('extends') && !match('{')) { id = parseVariableIdentifier(); } if (matchKeyword('extends')) { expectKeyword('extends'); previousYieldAllowed = state.yieldAllowed; state.yieldAllowed = false; superClass = parseAssignmentExpression(); state.yieldAllowed = previousYieldAllowed; } return delegate.createClassExpression(id, superClass, parseClassBody()); } function parseClassDeclaration() { var token, id, previousYieldAllowed, superClass = null; expectKeyword('class'); token = lookahead; id = parseVariableIdentifier(); if (matchKeyword('extends')) { expectKeyword('extends'); previousYieldAllowed = state.yieldAllowed; state.yieldAllowed = false; superClass = parseAssignmentExpression(); state.yieldAllowed = previousYieldAllowed; } return delegate.createClassDeclaration(id, superClass, parseClassBody()); } // 15 Program function parseSourceElement() { if (lookahead.type === Token.Keyword) { switch (lookahead.value) { case 'const': case 'let': return parseConstLetDeclaration(lookahead.value); case 'function': return parseFunctionDeclaration(); default: return parseStatement(); } } if (lookahead.type !== Token.EOF) { return parseStatement(); } } function parseProgramElement() { var lineNumber, token; if (lookahead.type === Token.Keyword) { switch (lookahead.value) { case 'export': return parseExportDeclaration(); case 'import': return parseImportDeclaration(); } } if (lookahead.value === 'module' && lookahead.type === Token.Identifier) { lineNumber = lookahead.lineNumber; token = lookahead2(); if (token.type === Token.Identifier && token.lineNumber === lineNumber) { return parseModuleDeclaration(); } } return parseSourceElement(); } function parseProgramElements() { var sourceElement, sourceElements = [], token, directive, firstRestricted; while (index < length) { token = lookahead; if (token.type !== Token.StringLiteral) { break; } sourceElement = parseProgramElement(); sourceElements.push(sourceElement); if (sourceElement.expression.type !== Syntax.Literal) { // this is not directive break; } directive = source.slice(token.range[0] + 1, token.range[1] - 1); if (directive === 'use strict') { strict = true; if (firstRestricted) { throwErrorTolerant(firstRestricted, Messages.StrictOctalLiteral); } } else { if (!firstRestricted && token.octal) { firstRestricted = token; } } } while (index < length) { sourceElement = parseProgramElement(); if (typeof sourceElement === 'undefined') { break; } sourceElements.push(sourceElement); } return sourceElements; } function parseModuleElement() { return parseProgramElement(); } function parseModuleElements() { var list = [], statement; while (index < length) { if (match('}')) { break; } statement = parseModuleElement(); if (typeof statement === 'undefined') { break; } list.push(statement); } return list; } function parseModuleBlock() { var block; expect('{'); block = parseModuleElements(); expect('}'); return delegate.createBlockStatement(block); } function parseProgram() { var body; strict = false; peek(); body = parseProgramElements(); return delegate.createProgram(body); } // The following functions are needed only when the option to preserve // the comments is active. function addComment(type, value, start, end, loc) { assert(typeof start === 'number', 'Comment must have valid position'); // Because the way the actual token is scanned, often the comments // (if any) are skipped twice during the lexical analysis. // Thus, we need to skip adding a comment if the comment array already // handled it. if (extra.comments.length > 0) { if (extra.comments[extra.comments.length - 1].range[1] > start) { return; } } extra.comments.push({ type: type, value: value, range: [start, end], loc: loc }); } function scanComment() { var comment, ch, loc, start, blockComment, lineComment; comment = ''; blockComment = false; lineComment = false; while (index < length) { ch = source[index]; if (lineComment) { ch = source[index++]; if (isLineTerminator(ch.charCodeAt(0))) { loc.end = { line: lineNumber, column: index - lineStart - 1 }; lineComment = false; addComment('Line', comment, start, index - 1, loc); if (ch === '\r' && source[index] === '\n') { ++index; } ++lineNumber; lineStart = index; comment = ''; } else if (index >= length) { lineComment = false; comment += ch; loc.end = { line: lineNumber, column: length - lineStart }; addComment('Line', comment, start, length, loc); } else { comment += ch; } } else if (blockComment) { if (isLineTerminator(ch.charCodeAt(0))) { if (ch === '\r' && source[index + 1] === '\n') { ++index; comment += '\r\n'; } else { comment += ch; } ++lineNumber; ++index; lineStart = index; if (index >= length) { throwError({}, Messages.UnexpectedToken, 'ILLEGAL'); } } else { ch = source[index++]; if (index >= length) { throwError({}, Messages.UnexpectedToken, 'ILLEGAL'); } comment += ch; if (ch === '*') { ch = source[index]; if (ch === '/') { comment = comment.substr(0, comment.length - 1); blockComment = false; ++index; loc.end = { line: lineNumber, column: index - lineStart }; addComment('Block', comment, start, index, loc); comment = ''; } } } } else if (ch === '/') { ch = source[index + 1]; if (ch === '/') { loc = { start: { line: lineNumber, column: index - lineStart } }; start = index; index += 2; lineComment = true; if (index >= length) { loc.end = { line: lineNumber, column: index - lineStart }; lineComment = false; addComment('Line', comment, start, index, loc); } } else if (ch === '*') { start = index; index += 2; blockComment = true; loc = { start: { line: lineNumber, column: index - lineStart - 2 } }; if (index >= length) { throwError({}, Messages.UnexpectedToken, 'ILLEGAL'); } } else { break; } } else if (isWhiteSpace(ch.charCodeAt(0))) { ++index; } else if (isLineTerminator(ch.charCodeAt(0))) { ++index; if (ch === '\r' && source[index] === '\n') { ++index; } ++lineNumber; lineStart = index; } else { break; } } } function filterCommentLocation() { var i, entry, comment, comments = []; for (i = 0; i < extra.comments.length; ++i) { entry = extra.comments[i]; comment = { type: entry.type, value: entry.value }; if (extra.range) { comment.range = entry.range; } if (extra.loc) { comment.loc = entry.loc; } comments.push(comment); } extra.comments = comments; } // 16 XJS XHTMLEntities = { quot: '\u0022', amp: '&', apos: "\u0027", lt: "<", gt: ">", nbsp: "\u00A0", iexcl: "\u00A1", cent: "\u00A2", pound: "\u00A3", curren: "\u00A4", yen: "\u00A5", brvbar: "\u00A6", sect: "\u00A7", uml: "\u00A8", copy: "\u00A9", ordf: "\u00AA", laquo: "\u00AB", not: "\u00AC", shy: "\u00AD", reg: "\u00AE", macr: "\u00AF", deg: "\u00B0", plusmn: "\u00B1", sup2: "\u00B2", sup3: "\u00B3", acute: "\u00B4", micro: "\u00B5", para: "\u00B6", middot: "\u00B7", cedil: "\u00B8", sup1: "\u00B9", ordm: "\u00BA", raquo: "\u00BB", frac14: "\u00BC", frac12: "\u00BD", frac34: "\u00BE", iquest: "\u00BF", Agrave: "\u00C0", Aacute: "\u00C1", Acirc: "\u00C2", Atilde: "\u00C3", Auml: "\u00C4", Aring: "\u00C5", AElig: "\u00C6", Ccedil: "\u00C7", Egrave: "\u00C8", Eacute: "\u00C9", Ecirc: "\u00CA", Euml: "\u00CB", Igrave: "\u00CC", Iacute: "\u00CD", Icirc: "\u00CE", Iuml: "\u00CF", ETH: "\u00D0", Ntilde: "\u00D1", Ograve: "\u00D2", Oacute: "\u00D3", Ocirc: "\u00D4", Otilde: "\u00D5", Ouml: "\u00D6", times: "\u00D7", Oslash: "\u00D8", Ugrave: "\u00D9", Uacute: "\u00DA", Ucirc: "\u00DB", Uuml: "\u00DC", Yacute: "\u00DD", THORN: "\u00DE", szlig: "\u00DF", agrave: "\u00E0", aacute: "\u00E1", acirc: "\u00E2", atilde: "\u00E3", auml: "\u00E4", aring: "\u00E5", aelig: "\u00E6", ccedil: "\u00E7", egrave: "\u00E8", eacute: "\u00E9", ecirc: "\u00EA", euml: "\u00EB", igrave: "\u00EC", iacute: "\u00ED", icirc: "\u00EE", iuml: "\u00EF", eth: "\u00F0", ntilde: "\u00F1", ograve: "\u00F2", oacute: "\u00F3", ocirc: "\u00F4", otilde: "\u00F5", ouml: "\u00F6", divide: "\u00F7", oslash: "\u00F8", ugrave: "\u00F9", uacute: "\u00FA", ucirc: "\u00FB", uuml: "\u00FC", yacute: "\u00FD", thorn: "\u00FE", yuml: "\u00FF", OElig: "\u0152", oelig: "\u0153", Scaron: "\u0160", scaron: "\u0161", Yuml: "\u0178", fnof: "\u0192", circ: "\u02C6", tilde: "\u02DC", Alpha: "\u0391", Beta: "\u0392", Gamma: "\u0393", Delta: "\u0394", Epsilon: "\u0395", Zeta: "\u0396", Eta: "\u0397", Theta: "\u0398", Iota: "\u0399", Kappa: "\u039A", Lambda: "\u039B", Mu: "\u039C", Nu: "\u039D", Xi: "\u039E", Omicron: "\u039F", Pi: "\u03A0", Rho: "\u03A1", Sigma: "\u03A3", Tau: "\u03A4", Upsilon: "\u03A5", Phi: "\u03A6", Chi: "\u03A7", Psi: "\u03A8", Omega: "\u03A9", alpha: "\u03B1", beta: "\u03B2", gamma: "\u03B3", delta: "\u03B4", epsilon: "\u03B5", zeta: "\u03B6", eta: "\u03B7", theta: "\u03B8", iota: "\u03B9", kappa: "\u03BA", lambda: "\u03BB", mu: "\u03BC", nu: "\u03BD", xi: "\u03BE", omicron: "\u03BF", pi: "\u03C0", rho: "\u03C1", sigmaf: "\u03C2", sigma: "\u03C3", tau: "\u03C4", upsilon: "\u03C5", phi: "\u03C6", chi: "\u03C7", psi: "\u03C8", omega: "\u03C9", thetasym: "\u03D1", upsih: "\u03D2", piv: "\u03D6", ensp: "\u2002", emsp: "\u2003", thinsp: "\u2009", zwnj: "\u200C", zwj: "\u200D", lrm: "\u200E", rlm: "\u200F", ndash: "\u2013", mdash: "\u2014", lsquo: "\u2018", rsquo: "\u2019", sbquo: "\u201A", ldquo: "\u201C", rdquo: "\u201D", bdquo: "\u201E", dagger: "\u2020", Dagger: "\u2021", bull: "\u2022", hellip: "\u2026", permil: "\u2030", prime: "\u2032", Prime: "\u2033", lsaquo: "\u2039", rsaquo: "\u203A", oline: "\u203E", frasl: "\u2044", euro: "\u20AC", image: "\u2111", weierp: "\u2118", real: "\u211C", trade: "\u2122", alefsym: "\u2135", larr: "\u2190", uarr: "\u2191", rarr: "\u2192", darr: "\u2193", harr: "\u2194", crarr: "\u21B5", lArr: "\u21D0", uArr: "\u21D1", rArr: "\u21D2", dArr: "\u21D3", hArr: "\u21D4", forall: "\u2200", part: "\u2202", exist: "\u2203", empty: "\u2205", nabla: "\u2207", isin: "\u2208", notin: "\u2209", ni: "\u220B", prod: "\u220F", sum: "\u2211", minus: "\u2212", lowast: "\u2217", radic: "\u221A", prop: "\u221D", infin: "\u221E", ang: "\u2220", and: "\u2227", or: "\u2228", cap: "\u2229", cup: "\u222A", "int": "\u222B", there4: "\u2234", sim: "\u223C", cong: "\u2245", asymp: "\u2248", ne: "\u2260", equiv: "\u2261", le: "\u2264", ge: "\u2265", sub: "\u2282", sup: "\u2283", nsub: "\u2284", sube: "\u2286", supe: "\u2287", oplus: "\u2295", otimes: "\u2297", perp: "\u22A5", sdot: "\u22C5", lceil: "\u2308", rceil: "\u2309", lfloor: "\u230A", rfloor: "\u230B", lang: "\u2329", rang: "\u232A", loz: "\u25CA", spades: "\u2660", clubs: "\u2663", hearts: "\u2665", diams: "\u2666" }; function isXJSIdentifierStart(ch) { // exclude backslash (\) return (ch !== 92) && isIdentifierStart(ch); } function isXJSIdentifierPart(ch) { // exclude backslash (\) and add hyphen (-) return (ch !== 92) && (ch === 45 || isIdentifierPart(ch)); } function scanXJSIdentifier() { var ch, start, id = '', namespace; start = index; while (index < length) { ch = source.charCodeAt(index); if (!isXJSIdentifierPart(ch)) { break; } id += source[index++]; } if (ch === 58) { // : ++index; namespace = id; id = ''; while (index < length) { ch = source.charCodeAt(index); if (!isXJSIdentifierPart(ch)) { break; } id += source[index++]; } } if (!id) { throwError({}, Messages.InvalidXJSTagName); } return { type: Token.XJSIdentifier, value: id, namespace: namespace, lineNumber: lineNumber, lineStart: lineStart, range: [start, index] }; } function scanXJSEntity() { var ch, str = '', count = 0, entity; ch = source[index]; assert(ch === '&', 'Entity must start with an ampersand'); index++; while (index < length && count++ < 10) { ch = source[index++]; if (ch === ';') { break; } str += ch; } if (str[0] === '#' && str[1] === 'x') { entity = String.fromCharCode(parseInt(str.substr(2), 16)); } else if (str[0] === '#') { entity = String.fromCharCode(parseInt(str.substr(1), 10)); } else { entity = XHTMLEntities[str]; } return entity; } function scanXJSText(stopChars) { var ch, str = '', start; start = index; while (index < length) { ch = source[index]; if (stopChars.indexOf(ch) !== -1) { break; } if (ch === '&') { str += scanXJSEntity(); } else { ch = source[index++]; if (isLineTerminator(ch.charCodeAt(0))) { ++lineNumber; lineStart = index; } str += ch; } } return { type: Token.XJSText, value: str, lineNumber: lineNumber, lineStart: lineStart, range: [start, index] }; } function scanXJSStringLiteral() { var innerToken, quote, start; quote = source[index]; assert((quote === '\'' || quote === '"'), 'String literal must starts with a quote'); start = index; ++index; innerToken = scanXJSText([quote]); if (quote !== source[index]) { throwError({}, Messages.UnexpectedToken, 'ILLEGAL'); } ++index; innerToken.range = [start, index]; return innerToken; } /** * Between XJS opening and closing tags (e.g. <foo>HERE</foo>), anything that * is not another XJS tag and is not an expression wrapped by {} is text. */ function advanceXJSChild() { var ch = source.charCodeAt(index); // { (123) and < (60) if (ch !== 123 && ch !== 60) { return scanXJSText(['<', '{']); } return scanPunctuator(); } function parseXJSIdentifier() { var token; if (lookahead.type !== Token.XJSIdentifier) { throwError({}, Messages.InvalidXJSTagName); } token = lex(); return delegate.createXJSIdentifier(token.value, token.namespace); } function parseXJSAttributeValue() { var value; if (match('{')) { value = parseXJSExpressionContainer(); if (value.expression.type === Syntax.XJSEmptyExpression) { throwError( value, 'XJS attributes must only be assigned a non-empty ' + 'expression' ); } } else if (lookahead.type === Token.XJSText) { value = delegate.createLiteral(lex()); } else { throwError({}, Messages.InvalidXJSAttributeValue); } return value; } function parseXJSEmptyExpression() { while (source.charAt(index) !== '}') { index++; } return delegate.createXJSEmptyExpression(); } function parseXJSExpressionContainer() { var expression, origInXJSChild, origInXJSTag; origInXJSChild = state.inXJSChild; origInXJSTag = state.inXJSTag; state.inXJSChild = false; state.inXJSTag = false; expect('{'); if (match('}')) { expression = parseXJSEmptyExpression(); } else { expression = parseExpression(); } state.inXJSChild = origInXJSChild; state.inXJSTag = origInXJSTag; expect('}'); return delegate.createXJSExpressionContainer(expression); } function parseXJSAttribute() { var token, name, value; name = parseXJSIdentifier(); // HTML empty attribute if (match('=')) { lex(); return delegate.createXJSAttribute(name, parseXJSAttributeValue()); } return delegate.createXJSAttribute(name); } function parseXJSChild() { var token; if (match('{')) { token = parseXJSExpressionContainer(); } else if (lookahead.type === Token.XJSText) { token = delegate.createLiteral(lex()); } else { state.inXJSChild = false; token = parseXJSElement(); state.inXJSChild = true; } return token; } function parseXJSClosingElement() { var name, origInXJSTag; origInXJSTag = state.inXJSTag; state.inXJSTag = true; state.inXJSChild = false; expect('<'); expect('/'); name = parseXJSIdentifier(); state.inXJSTag = origInXJSTag; expect('>'); return delegate.createXJSClosingElement(name); } function parseXJSOpeningElement() { var name, attribute, attributes = [], selfClosing = false, origInXJSTag; origInXJSTag = state.inXJSTag; state.inXJSTag = true; expect('<'); name = parseXJSIdentifier(); while (index < length && lookahead.value !== '/' && lookahead.value !== '>') { attributes.push(parseXJSAttribute()); } state.inXJSTag = origInXJSTag; if (lookahead.value === '/') { expect('/'); expect('>'); selfClosing = true; } else { state.inXJSChild = true; expect('>'); } return delegate.createXJSOpeningElement(name, attributes, selfClosing); } function parseXJSElement() { var openingElement, closingElement, children = [], origInXJSChild; openingElement = parseXJSOpeningElement(); if (!openingElement.selfClosing) { origInXJSChild = state.inXJSChild; while (index < length) { state.inXJSChild = false; // </ should not be considered in the child if (lookahead.value === '<' && lookahead2().value === '/') { break; } state.inXJSChild = true; peek(); // reset lookahead token children.push(parseXJSChild()); } state.inXJSChild = origInXJSChild; closingElement = parseXJSClosingElement(); if (closingElement.name.namespace !== openingElement.name.namespace || closingElement.name.name !== openingElement.name.name) { throwError({}, Messages.ExpectedXJSClosingTag, openingElement.name.namespace ? openingElement.name.namespace + ':' + openingElement.name.name : openingElement.name.name); } } return delegate.createXJSElement(openingElement, closingElement, children); } function collectToken() { var start, loc, token, range, value; skipComment(); start = index; loc = { start: { line: lineNumber, column: index - lineStart } }; token = extra.advance(); loc.end = { line: lineNumber, column: index - lineStart }; if (token.type !== Token.EOF) { range = [token.range[0], token.range[1]]; value = source.slice(token.range[0], token.range[1]); extra.tokens.push({ type: TokenName[token.type], value: value, range: range, loc: loc }); } return token; } function collectRegex() { var pos, loc, regex, token; skipComment(); pos = index; loc = { start: { line: lineNumber, column: index - lineStart } }; regex = extra.scanRegExp(); loc.end = { line: lineNumber, column: index - lineStart }; if (!extra.tokenize) { // Pop the previous token, which is likely '/' or '/=' if (extra.tokens.length > 0) { token = extra.tokens[extra.tokens.length - 1]; if (token.range[0] === pos && token.type === 'Punctuator') { if (token.value === '/' || token.value === '/=') { extra.tokens.pop(); } } } extra.tokens.push({ type: 'RegularExpression', value: regex.literal, range: [pos, index], loc: loc }); } return regex; } function filterTokenLocation() { var i, entry, token, tokens = []; for (i = 0; i < extra.tokens.length; ++i) { entry = extra.tokens[i]; token = { type: entry.type, value: entry.value }; if (extra.range) { token.range = entry.range; } if (extra.loc) { token.loc = entry.loc; } tokens.push(token); } extra.tokens = tokens; } function createLocationMarker() { var marker = {}; marker.range = [index, index]; marker.loc = { start: { line: lineNumber, column: index - lineStart }, end: { line: lineNumber, column: index - lineStart } }; marker.end = function () { this.range[1] = index; this.loc.end.line = lineNumber; this.loc.end.column = index - lineStart; }; marker.applyGroup = function (node) { if (extra.range) { node.groupRange = [this.range[0], this.range[1]]; } if (extra.loc) { node.groupLoc = { start: { line: this.loc.start.line, column: this.loc.start.column }, end: { line: this.loc.end.line, column: this.loc.end.column } }; node = delegate.postProcess(node); } }; marker.apply = function (node) { var nodeType = typeof node; assert(nodeType === "object", "Applying location marker to an unexpected node type: " + nodeType); if (extra.range) { node.range = [this.range[0], this.range[1]]; } if (extra.loc) { node.loc = { start: { line: this.loc.start.line, column: this.loc.start.column }, end: { line: this.loc.end.line, column: this.loc.end.column } }; node = delegate.postProcess(node); } }; return marker; } function trackGroupExpression() { var marker, expr; skipComment(); marker = createLocationMarker(); expect('('); ++state.parenthesizedCount; state.allowArrowFunction = !state.allowArrowFunction; expr = parseExpression(); state.allowArrowFunction = false; if (expr.type === 'ArrowFunctionExpression') { marker.end(); marker.apply(expr); } else { expect(')'); marker.end(); marker.applyGroup(expr); } return expr; } function trackLeftHandSideExpression() { var marker, expr; skipComment(); marker = createLocationMarker(); expr = matchKeyword('new') ? parseNewExpression() : parsePrimaryExpression(); while (match('.') || match('[') || lookahead.type === Token.Template) { if (match('[')) { expr = delegate.createMemberExpression('[', expr, parseComputedMember()); marker.end(); marker.apply(expr); } else if (match('.')) { expr = delegate.createMemberExpression('.', expr, parseNonComputedMember()); marker.end(); marker.apply(expr); } else { expr = delegate.createTaggedTemplateExpression(expr, parseTemplateLiteral()); marker.end(); marker.apply(expr); } } return expr; } function trackLeftHandSideExpressionAllowCall() { var marker, expr, args; skipComment(); marker = createLocationMarker(); expr = matchKeyword('new') ? parseNewExpression() : parsePrimaryExpression(); while (match('.') || match('[') || match('(') || lookahead.type === Token.Template) { if (match('(')) { args = parseArguments(); expr = delegate.createCallExpression(expr, args); marker.end(); marker.apply(expr); } else if (match('[')) { expr = delegate.createMemberExpression('[', expr, parseComputedMember()); marker.end(); marker.apply(expr); } else if (match('.')) { expr = delegate.createMemberExpression('.', expr, parseNonComputedMember()); marker.end(); marker.apply(expr); } else { expr = delegate.createTaggedTemplateExpression(expr, parseTemplateLiteral()); marker.end(); marker.apply(expr); } } return expr; } function filterGroup(node) { var n, i, entry; n = (Object.prototype.toString.apply(node) === '[object Array]') ? [] : {}; for (i in node) { if (node.hasOwnProperty(i) && i !== 'groupRange' && i !== 'groupLoc') { entry = node[i]; if (entry === null || typeof entry !== 'object' || entry instanceof RegExp) { n[i] = entry; } else { n[i] = filterGroup(entry); } } } return n; } function wrapTrackingFunction(range, loc, preserveWhitespace) { return function (parseFunction) { function isBinary(node) { return node.type === Syntax.LogicalExpression || node.type === Syntax.BinaryExpression; } function visit(node) { var start, end; if (isBinary(node.left)) { visit(node.left); } if (isBinary(node.right)) { visit(node.right); } if (range) { if (node.left.groupRange || node.right.groupRange) { start = node.left.groupRange ? node.left.groupRange[0] : node.left.range[0]; end = node.right.groupRange ? node.right.groupRange[1] : node.right.range[1]; node.range = [start, end]; } else if (typeof node.range === 'undefined') { start = node.left.range[0]; end = node.right.range[1]; node.range = [start, end]; } } if (loc) { if (node.left.groupLoc || node.right.groupLoc) { start = node.left.groupLoc ? node.left.groupLoc.start : node.left.loc.start; end = node.right.groupLoc ? node.right.groupLoc.end : node.right.loc.end; node.loc = { start: start, end: end }; node = delegate.postProcess(node); } else if (typeof node.loc === 'undefined') { node.loc = { start: node.left.loc.start, end: node.right.loc.end }; node = delegate.postProcess(node); } } } return function () { var marker, node; if (!preserveWhitespace) { skipComment(); } marker = createLocationMarker(); node = parseFunction.apply(null, arguments); marker.end(); if (range && typeof node.range === 'undefined') { marker.apply(node); } if (loc && typeof node.loc === 'undefined') { marker.apply(node); } if (isBinary(node)) { visit(node); } return node; }; }; } function patch() { var wrapTracking, wrapTrackingPreserveWhitespace; if (extra.comments) { extra.skipComment = skipComment; skipComment = scanComment; } if (extra.range || extra.loc) { extra.parseGroupExpression = parseGroupExpression; extra.parseLeftHandSideExpression = parseLeftHandSideExpression; extra.parseLeftHandSideExpressionAllowCall = parseLeftHandSideExpressionAllowCall; parseGroupExpression = trackGroupExpression; parseLeftHandSideExpression = trackLeftHandSideExpression; parseLeftHandSideExpressionAllowCall = trackLeftHandSideExpressionAllowCall; wrapTracking = wrapTrackingFunction(extra.range, extra.loc); wrapTrackingPreserveWhitespace = wrapTrackingFunction(extra.range, extra.loc, true); extra.parseAssignmentExpression = parseAssignmentExpression; extra.parseBinaryExpression = parseBinaryExpression; extra.parseBlock = parseBlock; extra.parseFunctionSourceElements = parseFunctionSourceElements; extra.parseCatchClause = parseCatchClause; extra.parseComputedMember = parseComputedMember; extra.parseConditionalExpression = parseConditionalExpression; extra.parseConstLetDeclaration = parseConstLetDeclaration; extra.parseExportDeclaration = parseExportDeclaration; extra.parseExportSpecifier = parseExportSpecifier; extra.parseExportSpecifierSetProperty = parseExportSpecifierSetProperty; extra.parseExpression = parseExpression; extra.parseForVariableDeclaration = parseForVariableDeclaration; extra.parseFunctionDeclaration = parseFunctionDeclaration; extra.parseFunctionExpression = parseFunctionExpression; extra.parseParams = parseParams; extra.parseGlob = parseGlob; extra.parseImportDeclaration = parseImportDeclaration; extra.parseImportSpecifier = parseImportSpecifier; extra.parseModuleDeclaration = parseModuleDeclaration; extra.parseModuleBlock = parseModuleBlock; extra.parseNewExpression = parseNewExpression; extra.parseNonComputedProperty = parseNonComputedProperty; extra.parseObjectProperty = parseObjectProperty; extra.parseObjectPropertyKey = parseObjectPropertyKey; extra.parsePath = parsePath; extra.parsePostfixExpression = parsePostfixExpression; extra.parsePrimaryExpression = parsePrimaryExpression; extra.parseProgram = parseProgram; extra.parsePropertyFunction = parsePropertyFunction; extra.parseSpreadOrAssignmentExpression = parseSpreadOrAssignmentExpression; extra.parseTemplateElement = parseTemplateElement; extra.parseTemplateLiteral = parseTemplateLiteral; extra.parseStatement = parseStatement; extra.parseSwitchCase = parseSwitchCase; extra.parseUnaryExpression = parseUnaryExpression; extra.parseVariableDeclaration = parseVariableDeclaration; extra.parseVariableIdentifier = parseVariableIdentifier; extra.parseMethodDefinition = parseMethodDefinition; extra.parseClassDeclaration = parseClassDeclaration; extra.parseClassExpression = parseClassExpression; extra.parseClassBody = parseClassBody; extra.parseXJSIdentifier = parseXJSIdentifier; extra.parseXJSChild = parseXJSChild; extra.parseXJSAttribute = parseXJSAttribute; extra.parseXJSAttributeValue = parseXJSAttributeValue; extra.parseXJSExpressionContainer = parseXJSExpressionContainer; extra.parseXJSEmptyExpression = parseXJSEmptyExpression; extra.parseXJSElement = parseXJSElement; extra.parseXJSClosingElement = parseXJSClosingElement; extra.parseXJSOpeningElement = parseXJSOpeningElement; parseAssignmentExpression = wrapTracking(extra.parseAssignmentExpression); parseBinaryExpression = wrapTracking(extra.parseBinaryExpression); parseBlock = wrapTracking(extra.parseBlock); parseFunctionSourceElements = wrapTracking(extra.parseFunctionSourceElements); parseCatchClause = wrapTracking(extra.parseCatchClause); parseComputedMember = wrapTracking(extra.parseComputedMember); parseConditionalExpression = wrapTracking(extra.parseConditionalExpression); parseConstLetDeclaration = wrapTracking(extra.parseConstLetDeclaration); parseExportDeclaration = wrapTracking(parseExportDeclaration); parseExportSpecifier = wrapTracking(parseExportSpecifier); parseExportSpecifierSetProperty = wrapTracking(parseExportSpecifierSetProperty); parseExpression = wrapTracking(extra.parseExpression); parseForVariableDeclaration = wrapTracking(extra.parseForVariableDeclaration); parseFunctionDeclaration = wrapTracking(extra.parseFunctionDeclaration); parseFunctionExpression = wrapTracking(extra.parseFunctionExpression); parseParams = wrapTracking(extra.parseParams); parseGlob = wrapTracking(extra.parseGlob); parseImportDeclaration = wrapTracking(extra.parseImportDeclaration); parseImportSpecifier = wrapTracking(extra.parseImportSpecifier); parseModuleDeclaration = wrapTracking(extra.parseModuleDeclaration); parseModuleBlock = wrapTracking(extra.parseModuleBlock); parseLeftHandSideExpression = wrapTracking(parseLeftHandSideExpression); parseNewExpression = wrapTracking(extra.parseNewExpression); parseNonComputedProperty = wrapTracking(extra.parseNonComputedProperty); parseObjectProperty = wrapTracking(extra.parseObjectProperty); parseObjectPropertyKey = wrapTracking(extra.parseObjectPropertyKey); parsePath = wrapTracking(extra.parsePath); parsePostfixExpression = wrapTracking(extra.parsePostfixExpression); parsePrimaryExpression = wrapTracking(extra.parsePrimaryExpression); parseProgram = wrapTracking(extra.parseProgram); parsePropertyFunction = wrapTracking(extra.parsePropertyFunction); parseTemplateElement = wrapTracking(extra.parseTemplateElement); parseTemplateLiteral = wrapTracking(extra.parseTemplateLiteral); parseSpreadOrAssignmentExpression = wrapTracking(extra.parseSpreadOrAssignmentExpression); parseStatement = wrapTracking(extra.parseStatement); parseSwitchCase = wrapTracking(extra.parseSwitchCase); parseUnaryExpression = wrapTracking(extra.parseUnaryExpression); parseVariableDeclaration = wrapTracking(extra.parseVariableDeclaration); parseVariableIdentifier = wrapTracking(extra.parseVariableIdentifier); parseMethodDefinition = wrapTracking(extra.parseMethodDefinition); parseClassDeclaration = wrapTracking(extra.parseClassDeclaration); parseClassExpression = wrapTracking(extra.parseClassExpression); parseClassBody = wrapTracking(extra.parseClassBody); parseXJSIdentifier = wrapTracking(extra.parseXJSIdentifier); parseXJSChild = wrapTrackingPreserveWhitespace(extra.parseXJSChild); parseXJSAttribute = wrapTracking(extra.parseXJSAttribute); parseXJSAttributeValue = wrapTracking(extra.parseXJSAttributeValue); parseXJSExpressionContainer = wrapTracking(extra.parseXJSExpressionContainer); parseXJSEmptyExpression = wrapTrackingPreserveWhitespace(extra.parseXJSEmptyExpression); parseXJSElement = wrapTracking(extra.parseXJSElement); parseXJSClosingElement = wrapTracking(extra.parseXJSClosingElement); parseXJSOpeningElement = wrapTracking(extra.parseXJSOpeningElement); } if (typeof extra.tokens !== 'undefined') { extra.advance = advance; extra.scanRegExp = scanRegExp; advance = collectToken; scanRegExp = collectRegex; } } function unpatch() { if (typeof extra.skipComment === 'function') { skipComment = extra.skipComment; } if (extra.range || extra.loc) { parseAssignmentExpression = extra.parseAssignmentExpression; parseBinaryExpression = extra.parseBinaryExpression; parseBlock = extra.parseBlock; parseFunctionSourceElements = extra.parseFunctionSourceElements; parseCatchClause = extra.parseCatchClause; parseComputedMember = extra.parseComputedMember; parseConditionalExpression = extra.parseConditionalExpression; parseConstLetDeclaration = extra.parseConstLetDeclaration; parseExportDeclaration = extra.parseExportDeclaration; parseExportSpecifier = extra.parseExportSpecifier; parseExportSpecifierSetProperty = extra.parseExportSpecifierSetProperty; parseExpression = extra.parseExpression; parseForVariableDeclaration = extra.parseForVariableDeclaration; parseFunctionDeclaration = extra.parseFunctionDeclaration; parseFunctionExpression = extra.parseFunctionExpression; parseGlob = extra.parseGlob; parseImportDeclaration = extra.parseImportDeclaration; parseImportSpecifier = extra.parseImportSpecifier; parseGroupExpression = extra.parseGroupExpression; parseLeftHandSideExpression = extra.parseLeftHandSideExpression; parseLeftHandSideExpressionAllowCall = extra.parseLeftHandSideExpressionAllowCall; parseModuleDeclaration = extra.parseModuleDeclaration; parseModuleBlock = extra.parseModuleBlock; parseNewExpression = extra.parseNewExpression; parseNonComputedProperty = extra.parseNonComputedProperty; parseObjectProperty = extra.parseObjectProperty; parseObjectPropertyKey = extra.parseObjectPropertyKey; parsePath = extra.parsePath; parsePostfixExpression = extra.parsePostfixExpression; parsePrimaryExpression = extra.parsePrimaryExpression; parseProgram = extra.parseProgram; parsePropertyFunction = extra.parsePropertyFunction; parseTemplateElement = extra.parseTemplateElement; parseTemplateLiteral = extra.parseTemplateLiteral; parseSpreadOrAssignmentExpression = extra.parseSpreadOrAssignmentExpression; parseStatement = extra.parseStatement; parseSwitchCase = extra.parseSwitchCase; parseUnaryExpression = extra.parseUnaryExpression; parseVariableDeclaration = extra.parseVariableDeclaration; parseVariableIdentifier = extra.parseVariableIdentifier; parseMethodDefinition = extra.parseMethodDefinition; parseClassDeclaration = extra.parseClassDeclaration; parseClassExpression = extra.parseClassExpression; parseClassBody = extra.parseClassBody; parseXJSIdentifier = extra.parseXJSIdentifier; parseXJSChild = extra.parseXJSChild; parseXJSAttribute = extra.parseXJSAttribute; parseXJSAttributeValue = extra.parseXJSAttributeValue; parseXJSExpressionContainer = extra.parseXJSExpressionContainer; parseXJSEmptyExpression = extra.parseXJSEmptyExpression; parseXJSElement = extra.parseXJSElement; parseXJSClosingElement = extra.parseXJSClosingElement; parseXJSOpeningElement = extra.parseXJSOpeningElement; } if (typeof extra.scanRegExp === 'function') { advance = extra.advance; scanRegExp = extra.scanRegExp; } } // This is used to modify the delegate. function extend(object, properties) { var entry, result = {}; for (entry in object) { if (object.hasOwnProperty(entry)) { result[entry] = object[entry]; } } for (entry in properties) { if (properties.hasOwnProperty(entry)) { result[entry] = properties[entry]; } } return result; } function tokenize(code, options) { var toString, token, tokens; toString = String; if (typeof code !== 'string' && !(code instanceof String)) { code = toString(code); } delegate = SyntaxTreeDelegate; source = code; index = 0; lineNumber = (source.length > 0) ? 1 : 0; lineStart = 0; length = source.length; lookahead = null; state = { allowIn: true, labelSet: {}, inFunctionBody: false, inIteration: false, inSwitch: false }; extra = {}; // Options matching. options = options || {}; // Of course we collect tokens here. options.tokens = true; extra.tokens = []; extra.tokenize = true; // The following two fields are necessary to compute the Regex tokens. extra.openParenToken = -1; extra.openCurlyToken = -1; extra.range = (typeof options.range === 'boolean') && options.range; extra.loc = (typeof options.loc === 'boolean') && options.loc; if (typeof options.comment === 'boolean' && options.comment) { extra.comments = []; } if (typeof options.tolerant === 'boolean' && options.tolerant) { extra.errors = []; } if (length > 0) { if (typeof source[0] === 'undefined') { // Try first to convert to a string. This is good as fast path // for old IE which understands string indexing for string // literals only and not for string object. if (code instanceof String) { source = code.valueOf(); } } } patch(); try { peek(); if (lookahead.type === Token.EOF) { return extra.tokens; } token = lex(); while (lookahead.type !== Token.EOF) { try { token = lex(); } catch (lexError) { token = lookahead; if (extra.errors) { extra.errors.push(lexError); // We have to break on the first error // to avoid infinite loops. break; } else { throw lexError; } } } filterTokenLocation(); tokens = extra.tokens; if (typeof extra.comments !== 'undefined') { filterCommentLocation(); tokens.comments = extra.comments; } if (typeof extra.errors !== 'undefined') { tokens.errors = extra.errors; } } catch (e) { throw e; } finally { unpatch(); extra = {}; } return tokens; } function parse(code, options) { var program, toString; toString = String; if (typeof code !== 'string' && !(code instanceof String)) { code = toString(code); } delegate = SyntaxTreeDelegate; source = code; index = 0; lineNumber = (source.length > 0) ? 1 : 0; lineStart = 0; length = source.length; lookahead = null; state = { allowIn: true, labelSet: {}, parenthesizedCount: 0, inFunctionBody: false, inIteration: false, inSwitch: false, yieldAllowed: false, yieldFound: false }; extra = {}; if (typeof options !== 'undefined') { extra.range = (typeof options.range === 'boolean') && options.range; extra.loc = (typeof options.loc === 'boolean') && options.loc; if (extra.loc && options.source !== null && options.source !== undefined) { delegate = extend(delegate, { 'postProcess': function (node) { node.loc.source = toString(options.source); return node; } }); } if (typeof options.tokens === 'boolean' && options.tokens) { extra.tokens = []; } if (typeof options.comment === 'boolean' && options.comment) { extra.comments = []; } if (typeof options.tolerant === 'boolean' && options.tolerant) { extra.errors = []; } } if (length > 0) { if (typeof source[0] === 'undefined') { // Try first to convert to a string. This is good as fast path // for old IE which understands string indexing for string // literals only and not for string object. if (code instanceof String) { source = code.valueOf(); } } } patch(); try { program = parseProgram(); if (typeof extra.comments !== 'undefined') { filterCommentLocation(); program.comments = extra.comments; } if (typeof extra.tokens !== 'undefined') { filterTokenLocation(); program.tokens = extra.tokens; } if (typeof extra.errors !== 'undefined') { program.errors = extra.errors; } if (extra.range || extra.loc) { program.body = filterGroup(program.body); } } catch (e) { throw e; } finally { unpatch(); extra = {}; } return program; } // Sync with package.json and component.json. exports.version = '1.1.0-dev-harmony'; exports.tokenize = tokenize; exports.parse = parse; // Deep copy. exports.Syntax = (function () { var name, types = {}; if (typeof Object.create === 'function') { types = Object.create(null); } for (name in Syntax) { if (Syntax.hasOwnProperty(name)) { types[name] = Syntax[name]; } } if (typeof Object.freeze === 'function') { Object.freeze(types); } return types; }()); })); /* vim: set sw=4 ts=4 et tw=80 : */ },{}],5:[function(require,module,exports){ /* * Copyright 2009-2011 Mozilla Foundation and contributors * Licensed under the New BSD license. See LICENSE.txt or: * http://opensource.org/licenses/BSD-3-Clause */ exports.SourceMapGenerator = require('./source-map/source-map-generator').SourceMapGenerator; exports.SourceMapConsumer = require('./source-map/source-map-consumer').SourceMapConsumer; exports.SourceNode = require('./source-map/source-node').SourceNode; },{"./source-map/source-map-consumer":10,"./source-map/source-map-generator":11,"./source-map/source-node":12}],6:[function(require,module,exports){ /* -*- Mode: js; js-indent-level: 2; -*- */ /* * Copyright 2011 Mozilla Foundation and contributors * Licensed under the New BSD license. See LICENSE or: * http://opensource.org/licenses/BSD-3-Clause */ if (typeof define !== 'function') { var define = require('amdefine')(module, require); } define(function (require, exports, module) { var util = require('./util'); /** * A data structure which is a combination of an array and a set. Adding a new * member is O(1), testing for membership is O(1), and finding the index of an * element is O(1). Removing elements from the set is not supported. Only * strings are supported for membership. */ function ArraySet() { this._array = []; this._set = {}; } /** * Static method for creating ArraySet instances from an existing array. */ ArraySet.fromArray = function ArraySet_fromArray(aArray, aAllowDuplicates) { var set = new ArraySet(); for (var i = 0, len = aArray.length; i < len; i++) { set.add(aArray[i], aAllowDuplicates); } return set; }; /** * Add the given string to this set. * * @param String aStr */ ArraySet.prototype.add = function ArraySet_add(aStr, aAllowDuplicates) { var isDuplicate = this.has(aStr); var idx = this._array.length; if (!isDuplicate || aAllowDuplicates) { this._array.push(aStr); } if (!isDuplicate) { this._set[util.toSetString(aStr)] = idx; } }; /** * Is the given string a member of this set? * * @param String aStr */ ArraySet.prototype.has = function ArraySet_has(aStr) { return Object.prototype.hasOwnProperty.call(this._set, util.toSetString(aStr)); }; /** * What is the index of the given string in the array? * * @param String aStr */ ArraySet.prototype.indexOf = function ArraySet_indexOf(aStr) { if (this.has(aStr)) { return this._set[util.toSetString(aStr)]; } throw new Error('"' + aStr + '" is not in the set.'); }; /** * What is the element at the given index? * * @param Number aIdx */ ArraySet.prototype.at = function ArraySet_at(aIdx) { if (aIdx >= 0 && aIdx < this._array.length) { return this._array[aIdx]; } throw new Error('No element indexed by ' + aIdx); }; /** * Returns the array representation of this set (which has the proper indices * indicated by indexOf). Note that this is a copy of the internal array used * for storing the members so that no one can mess with internal state. */ ArraySet.prototype.toArray = function ArraySet_toArray() { return this._array.slice(); }; exports.ArraySet = ArraySet; }); },{"./util":13,"amdefine":14}],7:[function(require,module,exports){ /* -*- Mode: js; js-indent-level: 2; -*- */ /* * Copyright 2011 Mozilla Foundation and contributors * Licensed under the New BSD license. See LICENSE or: * http://opensource.org/licenses/BSD-3-Clause * * Based on the Base 64 VLQ implementation in Closure Compiler: * https://code.google.com/p/closure-compiler/source/browse/trunk/src/com/google/debugging/sourcemap/Base64VLQ.java * * Copyright 2011 The Closure Compiler Authors. All rights reserved. * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. * * Neither the name of Google Inc. nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ if (typeof define !== 'function') { var define = require('amdefine')(module, require); } define(function (require, exports, module) { var base64 = require('./base64'); // A single base 64 digit can contain 6 bits of data. For the base 64 variable // length quantities we use in the source map spec, the first bit is the sign, // the next four bits are the actual value, and the 6th bit is the // continuation bit. The continuation bit tells us whether there are more // digits in this value following this digit. // // Continuation // | Sign // | | // V V // 101011 var VLQ_BASE_SHIFT = 5; // binary: 100000 var VLQ_BASE = 1 << VLQ_BASE_SHIFT; // binary: 011111 var VLQ_BASE_MASK = VLQ_BASE - 1; // binary: 100000 var VLQ_CONTINUATION_BIT = VLQ_BASE; /** * Converts from a two-complement value to a value where the sign bit is * is placed in the least significant bit. For example, as decimals: * 1 becomes 2 (10 binary), -1 becomes 3 (11 binary) * 2 becomes 4 (100 binary), -2 becomes 5 (101 binary) */ function toVLQSigned(aValue) { return aValue < 0 ? ((-aValue) << 1) + 1 : (aValue << 1) + 0; } /** * Converts to a two-complement value from a value where the sign bit is * is placed in the least significant bit. For example, as decimals: * 2 (10 binary) becomes 1, 3 (11 binary) becomes -1 * 4 (100 binary) becomes 2, 5 (101 binary) becomes -2 */ function fromVLQSigned(aValue) { var isNegative = (aValue & 1) === 1; var shifted = aValue >> 1; return isNegative ? -shifted : shifted; } /** * Returns the base 64 VLQ encoded value. */ exports.encode = function base64VLQ_encode(aValue) { var encoded = ""; var digit; var vlq = toVLQSigned(aValue); do { digit = vlq & VLQ_BASE_MASK; vlq >>>= VLQ_BASE_SHIFT; if (vlq > 0) { // There are still more digits in this value, so we must make sure the // continuation bit is marked. digit |= VLQ_CONTINUATION_BIT; } encoded += base64.encode(digit); } while (vlq > 0); return encoded; }; /** * Decodes the next base 64 VLQ value from the given string and returns the * value and the rest of the string. */ exports.decode = function base64VLQ_decode(aStr) { var i = 0; var strLen = aStr.length; var result = 0; var shift = 0; var continuation, digit; do { if (i >= strLen) { throw new Error("Expected more digits in base 64 VLQ value."); } digit = base64.decode(aStr.charAt(i++)); continuation = !!(digit & VLQ_CONTINUATION_BIT); digit &= VLQ_BASE_MASK; result = result + (digit << shift); shift += VLQ_BASE_SHIFT; } while (continuation); return { value: fromVLQSigned(result), rest: aStr.slice(i) }; }; }); },{"./base64":8,"amdefine":14}],8:[function(require,module,exports){ /* -*- Mode: js; js-indent-level: 2; -*- */ /* * Copyright 2011 Mozilla Foundation and contributors * Licensed under the New BSD license. See LICENSE or: * http://opensource.org/licenses/BSD-3-Clause */ if (typeof define !== 'function') { var define = require('amdefine')(module, require); } define(function (require, exports, module) { var charToIntMap = {}; var intToCharMap = {}; 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/' .split('') .forEach(function (ch, index) { charToIntMap[ch] = index; intToCharMap[index] = ch; }); /** * Encode an integer in the range of 0 to 63 to a single base 64 digit. */ exports.encode = function base64_encode(aNumber) { if (aNumber in intToCharMap) { return intToCharMap[aNumber]; } throw new TypeError("Must be between 0 and 63: " + aNumber); }; /** * Decode a single base 64 digit to an integer. */ exports.decode = function base64_decode(aChar) { if (aChar in charToIntMap) { return charToIntMap[aChar]; } throw new TypeError("Not a valid base 64 digit: " + aChar); }; }); },{"amdefine":14}],9:[function(require,module,exports){ /* -*- Mode: js; js-indent-level: 2; -*- */ /* * Copyright 2011 Mozilla Foundation and contributors * Licensed under the New BSD license. See LICENSE or: * http://opensource.org/licenses/BSD-3-Clause */ if (typeof define !== 'function') { var define = require('amdefine')(module, require); } define(function (require, exports, module) { /** * Recursive implementation of binary search. * * @param aLow Indices here and lower do not contain the needle. * @param aHigh Indices here and higher do not contain the needle. * @param aNeedle The element being searched for. * @param aHaystack The non-empty array being searched. * @param aCompare Function which takes two elements and returns -1, 0, or 1. */ function recursiveSearch(aLow, aHigh, aNeedle, aHaystack, aCompare) { // This function terminates when one of the following is true: // // 1. We find the exact element we are looking for. // // 2. We did not find the exact element, but we can return the next // closest element that is less than that element. // // 3. We did not find the exact element, and there is no next-closest // element which is less than the one we are searching for, so we // return null. var mid = Math.floor((aHigh - aLow) / 2) + aLow; var cmp = aCompare(aNeedle, aHaystack[mid], true); if (cmp === 0) { // Found the element we are looking for. return aHaystack[mid]; } else if (cmp > 0) { // aHaystack[mid] is greater than our needle. if (aHigh - mid > 1) { // The element is in the upper half. return recursiveSearch(mid, aHigh, aNeedle, aHaystack, aCompare); } // We did not find an exact match, return the next closest one // (termination case 2). return aHaystack[mid]; } else { // aHaystack[mid] is less than our needle. if (mid - aLow > 1) { // The element is in the lower half. return recursiveSearch(aLow, mid, aNeedle, aHaystack, aCompare); } // The exact needle element was not found in this haystack. Determine if // we are in termination case (2) or (3) and return the appropriate thing. return aLow < 0 ? null : aHaystack[aLow]; } } /** * This is an implementation of binary search which will always try and return * the next lowest value checked if there is no exact hit. This is because * mappings between original and generated line/col pairs are single points, * and there is an implicit region between each of them, so a miss just means * that you aren't on the very start of a region. * * @param aNeedle The element you are looking for. * @param aHaystack The array that is being searched. * @param aCompare A function which takes the needle and an element in the * array and returns -1, 0, or 1 depending on whether the needle is less * than, equal to, or greater than the element, respectively. */ exports.search = function search(aNeedle, aHaystack, aCompare) { return aHaystack.length > 0 ? recursiveSearch(-1, aHaystack.length, aNeedle, aHaystack, aCompare) : null; }; }); },{"amdefine":14}],10:[function(require,module,exports){ /* -*- Mode: js; js-indent-level: 2; -*- */ /* * Copyright 2011 Mozilla Foundation and contributors * Licensed under the New BSD license. See LICENSE or: * http://opensource.org/licenses/BSD-3-Clause */ if (typeof define !== 'function') { var define = require('amdefine')(module, require); } define(function (require, exports, module) { var util = require('./util'); var binarySearch = require('./binary-search'); var ArraySet = require('./array-set').ArraySet; var base64VLQ = require('./base64-vlq'); /** * A SourceMapConsumer instance represents a parsed source map which we can * query for information about the original file positions by giving it a file * position in the generated source. * * The only parameter is the raw source map (either as a JSON string, or * already parsed to an object). According to the spec, source maps have the * following attributes: * * - version: Which version of the source map spec this map is following. * - sources: An array of URLs to the original source files. * - names: An array of identifiers which can be referrenced by individual mappings. * - sourceRoot: Optional. The URL root from which all sources are relative. * - sourcesContent: Optional. An array of contents of the original source files. * - mappings: A string of base64 VLQs which contain the actual mappings. * - file: The generated file this source map is associated with. * * Here is an example source map, taken from the source map spec[0]: * * { * version : 3, * file: "out.js", * sourceRoot : "", * sources: ["foo.js", "bar.js"], * names: ["src", "maps", "are", "fun"], * mappings: "AA,AB;;ABCDE;" * } * * [0]: https://docs.google.com/document/d/1U1RGAehQwRypUTovF1KRlpiOFze0b-_2gc6fAH0KY0k/edit?pli=1# */ function SourceMapConsumer(aSourceMap) { var sourceMap = aSourceMap; if (typeof aSourceMap === 'string') { sourceMap = JSON.parse(aSourceMap.replace(/^\)\]\}'/, '')); } var version = util.getArg(sourceMap, 'version'); var sources = util.getArg(sourceMap, 'sources'); // Sass 3.3 leaves out the 'names' array, so we deviate from the spec (which // requires the array) to play nice here. var names = util.getArg(sourceMap, 'names', []); var sourceRoot = util.getArg(sourceMap, 'sourceRoot', null); var sourcesContent = util.getArg(sourceMap, 'sourcesContent', null); var mappings = util.getArg(sourceMap, 'mappings'); var file = util.getArg(sourceMap, 'file', null); // Once again, Sass deviates from the spec and supplies the version as a // string rather than a number, so we use loose equality checking here. if (version != this._version) { throw new Error('Unsupported version: ' + version); } // Pass `true` below to allow duplicate names and sources. While source maps // are intended to be compressed and deduplicated, the TypeScript compiler // sometimes generates source maps with duplicates in them. See Github issue // #72 and bugzil.la/889492. this._names = ArraySet.fromArray(names, true); this._sources = ArraySet.fromArray(sources, true); this.sourceRoot = sourceRoot; this.sourcesContent = sourcesContent; this._mappings = mappings; this.file = file; } /** * Create a SourceMapConsumer from a SourceMapGenerator. * * @param SourceMapGenerator aSourceMap * The source map that will be consumed. * @returns SourceMapConsumer */ SourceMapConsumer.fromSourceMap = function SourceMapConsumer_fromSourceMap(aSourceMap) { var smc = Object.create(SourceMapConsumer.prototype); smc._names = ArraySet.fromArray(aSourceMap._names.toArray(), true); smc._sources = ArraySet.fromArray(aSourceMap._sources.toArray(), true); smc.sourceRoot = aSourceMap._sourceRoot; smc.sourcesContent = aSourceMap._generateSourcesContent(smc._sources.toArray(), smc.sourceRoot); smc.file = aSourceMap._file; smc.__generatedMappings = aSourceMap._mappings.slice() .sort(util.compareByGeneratedPositions); smc.__originalMappings = aSourceMap._mappings.slice() .sort(util.compareByOriginalPositions); return smc; }; /** * The version of the source mapping spec that we are consuming. */ SourceMapConsumer.prototype._version = 3; /** * The list of original sources. */ Object.defineProperty(SourceMapConsumer.prototype, 'sources', { get: function () { return this._sources.toArray().map(function (s) { return this.sourceRoot ? util.join(this.sourceRoot, s) : s; }, this); } }); // `__generatedMappings` and `__originalMappings` are arrays that hold the // parsed mapping coordinates from the source map's "mappings" attribute. They // are lazily instantiated, accessed via the `_generatedMappings` and // `_originalMappings` getters respectively, and we only parse the mappings // and create these arrays once queried for a source location. We jump through // these hoops because there can be many thousands of mappings, and parsing // them is expensive, so we only want to do it if we must. // // Each object in the arrays is of the form: // // { // generatedLine: The line number in the generated code, // generatedColumn: The column number in the generated code, // source: The path to the original source file that generated this // chunk of code, // originalLine: The line number in the original source that // corresponds to this chunk of generated code, // originalColumn: The column number in the original source that // corresponds to this chunk of generated code, // name: The name of the original symbol which generated this chunk of // code. // } // // All properties except for `generatedLine` and `generatedColumn` can be // `null`. // // `_generatedMappings` is ordered by the generated positions. // // `_originalMappings` is ordered by the original positions. SourceMapConsumer.prototype.__generatedMappings = null; Object.defineProperty(SourceMapConsumer.prototype, '_generatedMappings', { get: function () { if (!this.__generatedMappings) { this.__generatedMappings = []; this.__originalMappings = []; this._parseMappings(this._mappings, this.sourceRoot); } return this.__generatedMappings; } }); SourceMapConsumer.prototype.__originalMappings = null; Object.defineProperty(SourceMapConsumer.prototype, '_originalMappings', { get: function () { if (!this.__originalMappings) { this.__generatedMappings = []; this.__originalMappings = []; this._parseMappings(this._mappings, this.sourceRoot); } return this.__originalMappings; } }); /** * Parse the mappings in a string in to a data structure which we can easily * query (the ordered arrays in the `this.__generatedMappings` and * `this.__originalMappings` properties). */ SourceMapConsumer.prototype._parseMappings = function SourceMapConsumer_parseMappings(aStr, aSourceRoot) { var generatedLine = 1; var previousGeneratedColumn = 0; var previousOriginalLine = 0; var previousOriginalColumn = 0; var previousSource = 0; var previousName = 0; var mappingSeparator = /^[,;]/; var str = aStr; var mapping; var temp; while (str.length > 0) { if (str.charAt(0) === ';') { generatedLine++; str = str.slice(1); previousGeneratedColumn = 0; } else if (str.charAt(0) === ',') { str = str.slice(1); } else { mapping = {}; mapping.generatedLine = generatedLine; // Generated column. temp = base64VLQ.decode(str); mapping.generatedColumn = previousGeneratedColumn + temp.value; previousGeneratedColumn = mapping.generatedColumn; str = temp.rest; if (str.length > 0 && !mappingSeparator.test(str.charAt(0))) { // Original source. temp = base64VLQ.decode(str); mapping.source = this._sources.at(previousSource + temp.value); previousSource += temp.value; str = temp.rest; if (str.length === 0 || mappingSeparator.test(str.charAt(0))) { throw new Error('Found a source, but no line and column'); } // Original line. temp = base64VLQ.decode(str); mapping.originalLine = previousOriginalLine + temp.value; previousOriginalLine = mapping.originalLine; // Lines are stored 0-based mapping.originalLine += 1; str = temp.rest; if (str.length === 0 || mappingSeparator.test(str.charAt(0))) { throw new Error('Found a source and line, but no column'); } // Original column. temp = base64VLQ.decode(str); mapping.originalColumn = previousOriginalColumn + temp.value; previousOriginalColumn = mapping.originalColumn; str = temp.rest; if (str.length > 0 && !mappingSeparator.test(str.charAt(0))) { // Original name. temp = base64VLQ.decode(str); mapping.name = this._names.at(previousName + temp.value); previousName += temp.value; str = temp.rest; } } this.__generatedMappings.push(mapping); if (typeof mapping.originalLine === 'number') { this.__originalMappings.push(mapping); } } } this.__originalMappings.sort(util.compareByOriginalPositions); }; /** * Find the mapping that best matches the hypothetical "needle" mapping that * we are searching for in the given "haystack" of mappings. */ SourceMapConsumer.prototype._findMapping = function SourceMapConsumer_findMapping(aNeedle, aMappings, aLineName, aColumnName, aComparator) { // To return the position we are searching for, we must first find the // mapping for the given position and then return the opposite position it // points to. Because the mappings are sorted, we can use binary search to // find the best mapping. if (aNeedle[aLineName] <= 0) { throw new TypeError('Line must be greater than or equal to 1, got ' + aNeedle[aLineName]); } if (aNeedle[aColumnName] < 0) { throw new TypeError('Column must be greater than or equal to 0, got ' + aNeedle[aColumnName]); } return binarySearch.search(aNeedle, aMappings, aComparator); }; /** * Returns the original source, line, and column information for the generated * source's line and column positions provided. The only argument is an object * with the following properties: * * - line: The line number in the generated source. * - column: The column number in the generated source. * * and an object is returned with the following properties: * * - source: The original source file, or null. * - line: The line number in the original source, or null. * - column: The column number in the original source, or null. * - name: The original identifier, or null. */ SourceMapConsumer.prototype.originalPositionFor = function SourceMapConsumer_originalPositionFor(aArgs) { var needle = { generatedLine: util.getArg(aArgs, 'line'), generatedColumn: util.getArg(aArgs, 'column') }; var mapping = this._findMapping(needle, this._generatedMappings, "generatedLine", "generatedColumn", util.compareByGeneratedPositions); if (mapping) { var source = util.getArg(mapping, 'source', null); if (source && this.sourceRoot) { source = util.join(this.sourceRoot, source); } return { source: source, line: util.getArg(mapping, 'originalLine', null), column: util.getArg(mapping, 'originalColumn', null), name: util.getArg(mapping, 'name', null) }; } return { source: null, line: null, column: null, name: null }; }; /** * Returns the original source content. The only argument is the url of the * original source file. Returns null if no original source content is * availible. */ SourceMapConsumer.prototype.sourceContentFor = function SourceMapConsumer_sourceContentFor(aSource) { if (!this.sourcesContent) { return null; } if (this.sourceRoot) { aSource = util.relative(this.sourceRoot, aSource); } if (this._sources.has(aSource)) { return this.sourcesContent[this._sources.indexOf(aSource)]; } var url; if (this.sourceRoot && (url = util.urlParse(this.sourceRoot))) { // XXX: file:// URIs and absolute paths lead to unexpected behavior for // many users. We can help them out when they expect file:// URIs to // behave like it would if they were running a local HTTP server. See // https://bugzilla.mozilla.org/show_bug.cgi?id=885597. var fileUriAbsPath = aSource.replace(/^file:\/\//, ""); if (url.scheme == "file" && this._sources.has(fileUriAbsPath)) { return this.sourcesContent[this._sources.indexOf(fileUriAbsPath)] } if ((!url.path || url.path == "/") && this._sources.has("/" + aSource)) { return this.sourcesContent[this._sources.indexOf("/" + aSource)]; } } throw new Error('"' + aSource + '" is not in the SourceMap.'); }; /** * Returns the generated line and column information for the original source, * line, and column positions provided. The only argument is an object with * the following properties: * * - source: The filename of the original source. * - line: The line number in the original source. * - column: The column number in the original source. * * and an object is returned with the following properties: * * - line: The line number in the generated source, or null. * - column: The column number in the generated source, or null. */ SourceMapConsumer.prototype.generatedPositionFor = function SourceMapConsumer_generatedPositionFor(aArgs) { var needle = { source: util.getArg(aArgs, 'source'), originalLine: util.getArg(aArgs, 'line'), originalColumn: util.getArg(aArgs, 'column') }; if (this.sourceRoot) { needle.source = util.relative(this.sourceRoot, needle.source); } var mapping = this._findMapping(needle, this._originalMappings, "originalLine", "originalColumn", util.compareByOriginalPositions); if (mapping) { return { line: util.getArg(mapping, 'generatedLine', null), column: util.getArg(mapping, 'generatedColumn', null) }; } return { line: null, column: null }; }; SourceMapConsumer.GENERATED_ORDER = 1; SourceMapConsumer.ORIGINAL_ORDER = 2; /** * Iterate over each mapping between an original source/line/column and a * generated line/column in this source map. * * @param Function aCallback * The function that is called with each mapping. * @param Object aContext * Optional. If specified, this object will be the value of `this` every * time that `aCallback` is called. * @param aOrder * Either `SourceMapConsumer.GENERATED_ORDER` or * `SourceMapConsumer.ORIGINAL_ORDER`. Specifies whether you want to * iterate over the mappings sorted by the generated file's line/column * order or the original's source/line/column order, respectively. Defaults to * `SourceMapConsumer.GENERATED_ORDER`. */ SourceMapConsumer.prototype.eachMapping = function SourceMapConsumer_eachMapping(aCallback, aContext, aOrder) { var context = aContext || null; var order = aOrder || SourceMapConsumer.GENERATED_ORDER; var mappings; switch (order) { case SourceMapConsumer.GENERATED_ORDER: mappings = this._generatedMappings; break; case SourceMapConsumer.ORIGINAL_ORDER: mappings = this._originalMappings; break; default: throw new Error("Unknown order of iteration."); } var sourceRoot = this.sourceRoot; mappings.map(function (mapping) { var source = mapping.source; if (source && sourceRoot) { source = util.join(sourceRoot, source); } return { source: source, generatedLine: mapping.generatedLine, generatedColumn: mapping.generatedColumn, originalLine: mapping.originalLine, originalColumn: mapping.originalColumn, name: mapping.name }; }).forEach(aCallback, context); }; exports.SourceMapConsumer = SourceMapConsumer; }); },{"./array-set":6,"./base64-vlq":7,"./binary-search":9,"./util":13,"amdefine":14}],11:[function(require,module,exports){ /* -*- Mode: js; js-indent-level: 2; -*- */ /* * Copyright 2011 Mozilla Foundation and contributors * Licensed under the New BSD license. See LICENSE or: * http://opensource.org/licenses/BSD-3-Clause */ if (typeof define !== 'function') { var define = require('amdefine')(module, require); } define(function (require, exports, module) { var base64VLQ = require('./base64-vlq'); var util = require('./util'); var ArraySet = require('./array-set').ArraySet; /** * An instance of the SourceMapGenerator represents a source map which is * being built incrementally. To create a new one, you must pass an object * with the following properties: * * - file: The filename of the generated source. * - sourceRoot: An optional root for all URLs in this source map. */ function SourceMapGenerator(aArgs) { this._file = util.getArg(aArgs, 'file'); this._sourceRoot = util.getArg(aArgs, 'sourceRoot', null); this._sources = new ArraySet(); this._names = new ArraySet(); this._mappings = []; this._sourcesContents = null; } SourceMapGenerator.prototype._version = 3; /** * Creates a new SourceMapGenerator based on a SourceMapConsumer * * @param aSourceMapConsumer The SourceMap. */ SourceMapGenerator.fromSourceMap = function SourceMapGenerator_fromSourceMap(aSourceMapConsumer) { var sourceRoot = aSourceMapConsumer.sourceRoot; var generator = new SourceMapGenerator({ file: aSourceMapConsumer.file, sourceRoot: sourceRoot }); aSourceMapConsumer.eachMapping(function (mapping) { var newMapping = { generated: { line: mapping.generatedLine, column: mapping.generatedColumn } }; if (mapping.source) { newMapping.source = mapping.source; if (sourceRoot) { newMapping.source = util.relative(sourceRoot, newMapping.source); } newMapping.original = { line: mapping.originalLine, column: mapping.originalColumn }; if (mapping.name) { newMapping.name = mapping.name; } } generator.addMapping(newMapping); }); aSourceMapConsumer.sources.forEach(function (sourceFile) { var content = aSourceMapConsumer.sourceContentFor(sourceFile); if (content) { generator.setSourceContent(sourceFile, content); } }); return generator; }; /** * Add a single mapping from original source line and column to the generated * source's line and column for this source map being created. The mapping * object should have the following properties: * * - generated: An object with the generated line and column positions. * - original: An object with the original line and column positions. * - source: The original source file (relative to the sourceRoot). * - name: An optional original token name for this mapping. */ SourceMapGenerator.prototype.addMapping = function SourceMapGenerator_addMapping(aArgs) { var generated = util.getArg(aArgs, 'generated'); var original = util.getArg(aArgs, 'original', null); var source = util.getArg(aArgs, 'source', null); var name = util.getArg(aArgs, 'name', null); this._validateMapping(generated, original, source, name); if (source && !this._sources.has(source)) { this._sources.add(source); } if (name && !this._names.has(name)) { this._names.add(name); } this._mappings.push({ generatedLine: generated.line, generatedColumn: generated.column, originalLine: original != null && original.line, originalColumn: original != null && original.column, source: source, name: name }); }; /** * Set the source content for a source file. */ SourceMapGenerator.prototype.setSourceContent = function SourceMapGenerator_setSourceContent(aSourceFile, aSourceContent) { var source = aSourceFile; if (this._sourceRoot) { source = util.relative(this._sourceRoot, source); } if (aSourceContent !== null) { // Add the source content to the _sourcesContents map. // Create a new _sourcesContents map if the property is null. if (!this._sourcesContents) { this._sourcesContents = {}; } this._sourcesContents[util.toSetString(source)] = aSourceContent; } else { // Remove the source file from the _sourcesContents map. // If the _sourcesContents map is empty, set the property to null. delete this._sourcesContents[util.toSetString(source)]; if (Object.keys(this._sourcesContents).length === 0) { this._sourcesContents = null; } } }; /** * Applies the mappings of a sub-source-map for a specific source file to the * source map being generated. Each mapping to the supplied source file is * rewritten using the supplied source map. Note: The resolution for the * resulting mappings is the minimium of this map and the supplied map. * * @param aSourceMapConsumer The source map to be applied. * @param aSourceFile Optional. The filename of the source file. * If omitted, SourceMapConsumer's file property will be used. */ SourceMapGenerator.prototype.applySourceMap = function SourceMapGenerator_applySourceMap(aSourceMapConsumer, aSourceFile) { // If aSourceFile is omitted, we will use the file property of the SourceMap if (!aSourceFile) { aSourceFile = aSourceMapConsumer.file; } var sourceRoot = this._sourceRoot; // Make "aSourceFile" relative if an absolute Url is passed. if (sourceRoot) { aSourceFile = util.relative(sourceRoot, aSourceFile); } // Applying the SourceMap can add and remove items from the sources and // the names array. var newSources = new ArraySet(); var newNames = new ArraySet(); // Find mappings for the "aSourceFile" this._mappings.forEach(function (mapping) { if (mapping.source === aSourceFile && mapping.originalLine) { // Check if it can be mapped by the source map, then update the mapping. var original = aSourceMapConsumer.originalPositionFor({ line: mapping.originalLine, column: mapping.originalColumn }); if (original.source !== null) { // Copy mapping if (sourceRoot) { mapping.source = util.relative(sourceRoot, original.source); } else { mapping.source = original.source; } mapping.originalLine = original.line; mapping.originalColumn = original.column; if (original.name !== null && mapping.name !== null) { // Only use the identifier name if it's an identifier // in both SourceMaps mapping.name = original.name; } } } var source = mapping.source; if (source && !newSources.has(source)) { newSources.add(source); } var name = mapping.name; if (name && !newNames.has(name)) { newNames.add(name); } }, this); this._sources = newSources; this._names = newNames; // Copy sourcesContents of applied map. aSourceMapConsumer.sources.forEach(function (sourceFile) { var content = aSourceMapConsumer.sourceContentFor(sourceFile); if (content) { if (sourceRoot) { sourceFile = util.relative(sourceRoot, sourceFile); } this.setSourceContent(sourceFile, content); } }, this); }; /** * A mapping can have one of the three levels of data: * * 1. Just the generated position. * 2. The Generated position, original position, and original source. * 3. Generated and original position, original source, as well as a name * token. * * To maintain consistency, we validate that any new mapping being added falls * in to one of these categories. */ SourceMapGenerator.prototype._validateMapping = function SourceMapGenerator_validateMapping(aGenerated, aOriginal, aSource, aName) { if (aGenerated && 'line' in aGenerated && 'column' in aGenerated && aGenerated.line > 0 && aGenerated.column >= 0 && !aOriginal && !aSource && !aName) { // Case 1. return; } else if (aGenerated && 'line' in aGenerated && 'column' in aGenerated && aOriginal && 'line' in aOriginal && 'column' in aOriginal && aGenerated.line > 0 && aGenerated.column >= 0 && aOriginal.line > 0 && aOriginal.column >= 0 && aSource) { // Cases 2 and 3. return; } else { throw new Error('Invalid mapping: ' + JSON.stringify({ generated: aGenerated, source: aSource, orginal: aOriginal, name: aName })); } }; /** * Serialize the accumulated mappings in to the stream of base 64 VLQs * specified by the source map format. */ SourceMapGenerator.prototype._serializeMappings = function SourceMapGenerator_serializeMappings() { var previousGeneratedColumn = 0; var previousGeneratedLine = 1; var previousOriginalColumn = 0; var previousOriginalLine = 0; var previousName = 0; var previousSource = 0; var result = ''; var mapping; // The mappings must be guaranteed to be in sorted order before we start // serializing them or else the generated line numbers (which are defined // via the ';' separators) will be all messed up. Note: it might be more // performant to maintain the sorting as we insert them, rather than as we // serialize them, but the big O is the same either way. this._mappings.sort(util.compareByGeneratedPositions); for (var i = 0, len = this._mappings.length; i < len; i++) { mapping = this._mappings[i]; if (mapping.generatedLine !== previousGeneratedLine) { previousGeneratedColumn = 0; while (mapping.generatedLine !== previousGeneratedLine) { result += ';'; previousGeneratedLine++; } } else { if (i > 0) { if (!util.compareByGeneratedPositions(mapping, this._mappings[i - 1])) { continue; } result += ','; } } result += base64VLQ.encode(mapping.generatedColumn - previousGeneratedColumn); previousGeneratedColumn = mapping.generatedColumn; if (mapping.source) { result += base64VLQ.encode(this._sources.indexOf(mapping.source) - previousSource); previousSource = this._sources.indexOf(mapping.source); // lines are stored 0-based in SourceMap spec version 3 result += base64VLQ.encode(mapping.originalLine - 1 - previousOriginalLine); previousOriginalLine = mapping.originalLine - 1; result += base64VLQ.encode(mapping.originalColumn - previousOriginalColumn); previousOriginalColumn = mapping.originalColumn; if (mapping.name) { result += base64VLQ.encode(this._names.indexOf(mapping.name) - previousName); previousName = this._names.indexOf(mapping.name); } } } return result; }; SourceMapGenerator.prototype._generateSourcesContent = function SourceMapGenerator_generateSourcesContent(aSources, aSourceRoot) { return aSources.map(function (source) { if (!this._sourcesContents) { return null; } if (aSourceRoot) { source = util.relative(aSourceRoot, source); } var key = util.toSetString(source); return Object.prototype.hasOwnProperty.call(this._sourcesContents, key) ? this._sourcesContents[key] : null; }, this); }; /** * Externalize the source map. */ SourceMapGenerator.prototype.toJSON = function SourceMapGenerator_toJSON() { var map = { version: this._version, file: this._file, sources: this._sources.toArray(), names: this._names.toArray(), mappings: this._serializeMappings() }; if (this._sourceRoot) { map.sourceRoot = this._sourceRoot; } if (this._sourcesContents) { map.sourcesContent = this._generateSourcesContent(map.sources, map.sourceRoot); } return map; }; /** * Render the source map being generated to a string. */ SourceMapGenerator.prototype.toString = function SourceMapGenerator_toString() { return JSON.stringify(this); }; exports.SourceMapGenerator = SourceMapGenerator; }); },{"./array-set":6,"./base64-vlq":7,"./util":13,"amdefine":14}],12:[function(require,module,exports){ /* -*- Mode: js; js-indent-level: 2; -*- */ /* * Copyright 2011 Mozilla Foundation and contributors * Licensed under the New BSD license. See LICENSE or: * http://opensource.org/licenses/BSD-3-Clause */ if (typeof define !== 'function') { var define = require('amdefine')(module, require); } define(function (require, exports, module) { var SourceMapGenerator = require('./source-map-generator').SourceMapGenerator; var util = require('./util'); /** * SourceNodes provide a way to abstract over interpolating/concatenating * snippets of generated JavaScript source code while maintaining the line and * column information associated with the original source code. * * @param aLine The original line number. * @param aColumn The original column number. * @param aSource The original source's filename. * @param aChunks Optional. An array of strings which are snippets of * generated JS, or other SourceNodes. * @param aName The original identifier. */ function SourceNode(aLine, aColumn, aSource, aChunks, aName) { this.children = []; this.sourceContents = {}; this.line = aLine === undefined ? null : aLine; this.column = aColumn === undefined ? null : aColumn; this.source = aSource === undefined ? null : aSource; this.name = aName === undefined ? null : aName; if (aChunks != null) this.add(aChunks); } /** * Creates a SourceNode from generated code and a SourceMapConsumer. * * @param aGeneratedCode The generated code * @param aSourceMapConsumer The SourceMap for the generated code */ SourceNode.fromStringWithSourceMap = function SourceNode_fromStringWithSourceMap(aGeneratedCode, aSourceMapConsumer) { // The SourceNode we want to fill with the generated code // and the SourceMap var node = new SourceNode(); // The generated code // Processed fragments are removed from this array. var remainingLines = aGeneratedCode.split('\n'); // We need to remember the position of "remainingLines" var lastGeneratedLine = 1, lastGeneratedColumn = 0; // The generate SourceNodes we need a code range. // To extract it current and last mapping is used. // Here we store the last mapping. var lastMapping = null; aSourceMapConsumer.eachMapping(function (mapping) { if (lastMapping === null) { // We add the generated code until the first mapping // to the SourceNode without any mapping. // Each line is added as separate string. while (lastGeneratedLine < mapping.generatedLine) { node.add(remainingLines.shift() + "\n"); lastGeneratedLine++; } if (lastGeneratedColumn < mapping.generatedColumn) { var nextLine = remainingLines[0]; node.add(nextLine.substr(0, mapping.generatedColumn)); remainingLines[0] = nextLine.substr(mapping.generatedColumn); lastGeneratedColumn = mapping.generatedColumn; } } else { // We add the code from "lastMapping" to "mapping": // First check if there is a new line in between. if (lastGeneratedLine < mapping.generatedLine) { var code = ""; // Associate full lines with "lastMapping" do { code += remainingLines.shift() + "\n"; lastGeneratedLine++; lastGeneratedColumn = 0; } while (lastGeneratedLine < mapping.generatedLine); // When we reached the correct line, we add code until we // reach the correct column too. if (lastGeneratedColumn < mapping.generatedColumn) { var nextLine = remainingLines[0]; code += nextLine.substr(0, mapping.generatedColumn); remainingLines[0] = nextLine.substr(mapping.generatedColumn); lastGeneratedColumn = mapping.generatedColumn; } // Create the SourceNode. addMappingWithCode(lastMapping, code); } else { // There is no new line in between. // Associate the code between "lastGeneratedColumn" and // "mapping.generatedColumn" with "lastMapping" var nextLine = remainingLines[0]; var code = nextLine.substr(0, mapping.generatedColumn - lastGeneratedColumn); remainingLines[0] = nextLine.substr(mapping.generatedColumn - lastGeneratedColumn); lastGeneratedColumn = mapping.generatedColumn; addMappingWithCode(lastMapping, code); } } lastMapping = mapping; }, this); // We have processed all mappings. // Associate the remaining code in the current line with "lastMapping" // and add the remaining lines without any mapping addMappingWithCode(lastMapping, remainingLines.join("\n")); // Copy sourcesContent into SourceNode aSourceMapConsumer.sources.forEach(function (sourceFile) { var content = aSourceMapConsumer.sourceContentFor(sourceFile); if (content) { node.setSourceContent(sourceFile, content); } }); return node; function addMappingWithCode(mapping, code) { if (mapping === null || mapping.source === undefined) { node.add(code); } else { node.add(new SourceNode(mapping.originalLine, mapping.originalColumn, mapping.source, code, mapping.name)); } } }; /** * Add a chunk of generated JS to this source node. * * @param aChunk A string snippet of generated JS code, another instance of * SourceNode, or an array where each member is one of those things. */ SourceNode.prototype.add = function SourceNode_add(aChunk) { if (Array.isArray(aChunk)) { aChunk.forEach(function (chunk) { this.add(chunk); }, this); } else if (aChunk instanceof SourceNode || typeof aChunk === "string") { if (aChunk) { this.children.push(aChunk); } } else { throw new TypeError( "Expected a SourceNode, string, or an array of SourceNodes and strings. Got " + aChunk ); } return this; }; /** * Add a chunk of generated JS to the beginning of this source node. * * @param aChunk A string snippet of generated JS code, another instance of * SourceNode, or an array where each member is one of those things. */ SourceNode.prototype.prepend = function SourceNode_prepend(aChunk) { if (Array.isArray(aChunk)) { for (var i = aChunk.length-1; i >= 0; i--) { this.prepend(aChunk[i]); } } else if (aChunk instanceof SourceNode || typeof aChunk === "string") { this.children.unshift(aChunk); } else { throw new TypeError( "Expected a SourceNode, string, or an array of SourceNodes and strings. Got " + aChunk ); } return this; }; /** * Walk over the tree of JS snippets in this node and its children. The * walking function is called once for each snippet of JS and is passed that * snippet and the its original associated source's line/column location. * * @param aFn The traversal function. */ SourceNode.prototype.walk = function SourceNode_walk(aFn) { var chunk; for (var i = 0, len = this.children.length; i < len; i++) { chunk = this.children[i]; if (chunk instanceof SourceNode) { chunk.walk(aFn); } else { if (chunk !== '') { aFn(chunk, { source: this.source, line: this.line, column: this.column, name: this.name }); } } } }; /** * Like `String.prototype.join` except for SourceNodes. Inserts `aStr` between * each of `this.children`. * * @param aSep The separator. */ SourceNode.prototype.join = function SourceNode_join(aSep) { var newChildren; var i; var len = this.children.length; if (len > 0) { newChildren = []; for (i = 0; i < len-1; i++) { newChildren.push(this.children[i]); newChildren.push(aSep); } newChildren.push(this.children[i]); this.children = newChildren; } return this; }; /** * Call String.prototype.replace on the very right-most source snippet. Useful * for trimming whitespace from the end of a source node, etc. * * @param aPattern The pattern to replace. * @param aReplacement The thing to replace the pattern with. */ SourceNode.prototype.replaceRight = function SourceNode_replaceRight(aPattern, aReplacement) { var lastChild = this.children[this.children.length - 1]; if (lastChild instanceof SourceNode) { lastChild.replaceRight(aPattern, aReplacement); } else if (typeof lastChild === 'string') { this.children[this.children.length - 1] = lastChild.replace(aPattern, aReplacement); } else { this.children.push(''.replace(aPattern, aReplacement)); } return this; }; /** * Set the source content for a source file. This will be added to the SourceMapGenerator * in the sourcesContent field. * * @param aSourceFile The filename of the source file * @param aSourceContent The content of the source file */ SourceNode.prototype.setSourceContent = function SourceNode_setSourceContent(aSourceFile, aSourceContent) { this.sourceContents[util.toSetString(aSourceFile)] = aSourceContent; }; /** * Walk over the tree of SourceNodes. The walking function is called for each * source file content and is passed the filename and source content. * * @param aFn The traversal function. */ SourceNode.prototype.walkSourceContents = function SourceNode_walkSourceContents(aFn) { for (var i = 0, len = this.children.length; i < len; i++) { if (this.children[i] instanceof SourceNode) { this.children[i].walkSourceContents(aFn); } } var sources = Object.keys(this.sourceContents); for (var i = 0, len = sources.length; i < len; i++) { aFn(util.fromSetString(sources[i]), this.sourceContents[sources[i]]); } }; /** * Return the string representation of this source node. Walks over the tree * and concatenates all the various snippets together to one string. */ SourceNode.prototype.toString = function SourceNode_toString() { var str = ""; this.walk(function (chunk) { str += chunk; }); return str; }; /** * Returns the string representation of this source node along with a source * map. */ SourceNode.prototype.toStringWithSourceMap = function SourceNode_toStringWithSourceMap(aArgs) { var generated = { code: "", line: 1, column: 0 }; var map = new SourceMapGenerator(aArgs); var sourceMappingActive = false; var lastOriginalSource = null; var lastOriginalLine = null; var lastOriginalColumn = null; var lastOriginalName = null; this.walk(function (chunk, original) { generated.code += chunk; if (original.source !== null && original.line !== null && original.column !== null) { if(lastOriginalSource !== original.source || lastOriginalLine !== original.line || lastOriginalColumn !== original.column || lastOriginalName !== original.name) { map.addMapping({ source: original.source, original: { line: original.line, column: original.column }, generated: { line: generated.line, column: generated.column }, name: original.name }); } lastOriginalSource = original.source; lastOriginalLine = original.line; lastOriginalColumn = original.column; lastOriginalName = original.name; sourceMappingActive = true; } else if (sourceMappingActive) { map.addMapping({ generated: { line: generated.line, column: generated.column } }); lastOriginalSource = null; sourceMappingActive = false; } chunk.split('').forEach(function (ch) { if (ch === '\n') { generated.line++; generated.column = 0; } else { generated.column++; } }); }); this.walkSourceContents(function (sourceFile, sourceContent) { map.setSourceContent(sourceFile, sourceContent); }); return { code: generated.code, map: map }; }; exports.SourceNode = SourceNode; }); },{"./source-map-generator":11,"./util":13,"amdefine":14}],13:[function(require,module,exports){ /* -*- Mode: js; js-indent-level: 2; -*- */ /* * Copyright 2011 Mozilla Foundation and contributors * Licensed under the New BSD license. See LICENSE or: * http://opensource.org/licenses/BSD-3-Clause */ if (typeof define !== 'function') { var define = require('amdefine')(module, require); } define(function (require, exports, module) { /** * This is a helper function for getting values from parameter/options * objects. * * @param args The object we are extracting values from * @param name The name of the property we are getting. * @param defaultValue An optional value to return if the property is missing * from the object. If this is not specified and the property is missing, an * error will be thrown. */ function getArg(aArgs, aName, aDefaultValue) { if (aName in aArgs) { return aArgs[aName]; } else if (arguments.length === 3) { return aDefaultValue; } else { throw new Error('"' + aName + '" is a required argument.'); } } exports.getArg = getArg; var urlRegexp = /([\w+\-.]+):\/\/((\w+:\w+)@)?([\w.]+)?(:(\d+))?(\S+)?/; var dataUrlRegexp = /^data:.+\,.+/; function urlParse(aUrl) { var match = aUrl.match(urlRegexp); if (!match) { return null; } return { scheme: match[1], auth: match[3], host: match[4], port: match[6], path: match[7] }; } exports.urlParse = urlParse; function urlGenerate(aParsedUrl) { var url = aParsedUrl.scheme + "://"; if (aParsedUrl.auth) { url += aParsedUrl.auth + "@" } if (aParsedUrl.host) { url += aParsedUrl.host; } if (aParsedUrl.port) { url += ":" + aParsedUrl.port } if (aParsedUrl.path) { url += aParsedUrl.path; } return url; } exports.urlGenerate = urlGenerate; function join(aRoot, aPath) { var url; if (aPath.match(urlRegexp) || aPath.match(dataUrlRegexp)) { return aPath; } if (aPath.charAt(0) === '/' && (url = urlParse(aRoot))) { url.path = aPath; return urlGenerate(url); } return aRoot.replace(/\/$/, '') + '/' + aPath; } exports.join = join; /** * Because behavior goes wacky when you set `__proto__` on objects, we * have to prefix all the strings in our set with an arbitrary character. * * See https://github.com/mozilla/source-map/pull/31 and * https://github.com/mozilla/source-map/issues/30 * * @param String aStr */ function toSetString(aStr) { return '$' + aStr; } exports.toSetString = toSetString; function fromSetString(aStr) { return aStr.substr(1); } exports.fromSetString = fromSetString; function relative(aRoot, aPath) { aRoot = aRoot.replace(/\/$/, ''); var url = urlParse(aRoot); if (aPath.charAt(0) == "/" && url && url.path == "/") { return aPath.slice(1); } return aPath.indexOf(aRoot + '/') === 0 ? aPath.substr(aRoot.length + 1) : aPath; } exports.relative = relative; function strcmp(aStr1, aStr2) { var s1 = aStr1 || ""; var s2 = aStr2 || ""; return (s1 > s2) - (s1 < s2); } /** * Comparator between two mappings where the original positions are compared. * * Optionally pass in `true` as `onlyCompareGenerated` to consider two * mappings with the same original source/line/column, but different generated * line and column the same. Useful when searching for a mapping with a * stubbed out mapping. */ function compareByOriginalPositions(mappingA, mappingB, onlyCompareOriginal) { var cmp; cmp = strcmp(mappingA.source, mappingB.source); if (cmp) { return cmp; } cmp = mappingA.originalLine - mappingB.originalLine; if (cmp) { return cmp; } cmp = mappingA.originalColumn - mappingB.originalColumn; if (cmp || onlyCompareOriginal) { return cmp; } cmp = strcmp(mappingA.name, mappingB.name); if (cmp) { return cmp; } cmp = mappingA.generatedLine - mappingB.generatedLine; if (cmp) { return cmp; } return mappingA.generatedColumn - mappingB.generatedColumn; }; exports.compareByOriginalPositions = compareByOriginalPositions; /** * Comparator between two mappings where the generated positions are * compared. * * Optionally pass in `true` as `onlyCompareGenerated` to consider two * mappings with the same generated line and column, but different * source/name/original line and column the same. Useful when searching for a * mapping with a stubbed out mapping. */ function compareByGeneratedPositions(mappingA, mappingB, onlyCompareGenerated) { var cmp; cmp = mappingA.generatedLine - mappingB.generatedLine; if (cmp) { return cmp; } cmp = mappingA.generatedColumn - mappingB.generatedColumn; if (cmp || onlyCompareGenerated) { return cmp; } cmp = strcmp(mappingA.source, mappingB.source); if (cmp) { return cmp; } cmp = mappingA.originalLine - mappingB.originalLine; if (cmp) { return cmp; } cmp = mappingA.originalColumn - mappingB.originalColumn; if (cmp) { return cmp; } return strcmp(mappingA.name, mappingB.name); }; exports.compareByGeneratedPositions = compareByGeneratedPositions; }); },{"amdefine":14}],14:[function(require,module,exports){ var process=require("__browserify_process"),__filename="/../node_modules/source-map/node_modules/amdefine/amdefine.js";/** vim: et:ts=4:sw=4:sts=4 * @license amdefine 0.1.0 Copyright (c) 2011, The Dojo Foundation All Rights Reserved. * Available via the MIT or new BSD license. * see: http://github.com/jrburke/amdefine for details */ /*jslint node: true */ /*global module, process */ 'use strict'; /** * Creates a define for node. * @param {Object} module the "module" object that is defined by Node for the * current module. * @param {Function} [requireFn]. Node's require function for the current module. * It only needs to be passed in Node versions before 0.5, when module.require * did not exist. * @returns {Function} a define function that is usable for the current node * module. */ function amdefine(module, requireFn) { 'use strict'; var defineCache = {}, loaderCache = {}, alreadyCalled = false, path = require('path'), makeRequire, stringRequire; /** * Trims the . and .. from an array of path segments. * It will keep a leading path segment if a .. will become * the first path segment, to help with module name lookups, * which act like paths, but can be remapped. But the end result, * all paths that use this function should look normalized. * NOTE: this method MODIFIES the input array. * @param {Array} ary the array of path segments. */ function trimDots(ary) { var i, part; for (i = 0; ary[i]; i+= 1) { part = ary[i]; if (part === '.') { ary.splice(i, 1); i -= 1; } else if (part === '..') { if (i === 1 && (ary[2] === '..' || ary[0] === '..')) { //End of the line. Keep at least one non-dot //path segment at the front so it can be mapped //correctly to disk. Otherwise, there is likely //no path mapping for a path starting with '..'. //This can still fail, but catches the most reasonable //uses of .. break; } else if (i > 0) { ary.splice(i - 1, 2); i -= 2; } } } } function normalize(name, baseName) { var baseParts; //Adjust any relative paths. if (name && name.charAt(0) === '.') { //If have a base name, try to normalize against it, //otherwise, assume it is a top-level require that will //be relative to baseUrl in the end. if (baseName) { baseParts = baseName.split('/'); baseParts = baseParts.slice(0, baseParts.length - 1); baseParts = baseParts.concat(name.split('/')); trimDots(baseParts); name = baseParts.join('/'); } } return name; } /** * Create the normalize() function passed to a loader plugin's * normalize method. */ function makeNormalize(relName) { return function (name) { return normalize(name, relName); }; } function makeLoad(id) { function load(value) { loaderCache[id] = value; } load.fromText = function (id, text) { //This one is difficult because the text can/probably uses //define, and any relative paths and requires should be relative //to that id was it would be found on disk. But this would require //bootstrapping a module/require fairly deeply from node core. //Not sure how best to go about that yet. throw new Error('amdefine does not implement load.fromText'); }; return load; } makeRequire = function (systemRequire, exports, module, relId) { function amdRequire(deps, callback) { if (typeof deps === 'string') { //Synchronous, single module require('') return stringRequire(systemRequire, exports, module, deps, relId); } else { //Array of dependencies with a callback. //Convert the dependencies to modules. deps = deps.map(function (depName) { return stringRequire(systemRequire, exports, module, depName, relId); }); //Wait for next tick to call back the require call. process.nextTick(function () { callback.apply(null, deps); }); } } amdRequire.toUrl = function (filePath) { if (filePath.indexOf('.') === 0) { return normalize(filePath, path.dirname(module.filename)); } else { return filePath; } }; return amdRequire; }; //Favor explicit value, passed in if the module wants to support Node 0.4. requireFn = requireFn || function req() { return module.require.apply(module, arguments); }; function runFactory(id, deps, factory) { var r, e, m, result; if (id) { e = loaderCache[id] = {}; m = { id: id, uri: __filename, exports: e }; r = makeRequire(requireFn, e, m, id); } else { //Only support one define call per file if (alreadyCalled) { throw new Error('amdefine with no module ID cannot be called more than once per file.'); } alreadyCalled = true; //Use the real variables from node //Use module.exports for exports, since //the exports in here is amdefine exports. e = module.exports; m = module; r = makeRequire(requireFn, e, m, module.id); } //If there are dependencies, they are strings, so need //to convert them to dependency values. if (deps) { deps = deps.map(function (depName) { return r(depName); }); } //Call the factory with the right dependencies. if (typeof factory === 'function') { result = factory.apply(m.exports, deps); } else { result = factory; } if (result !== undefined) { m.exports = result; if (id) { loaderCache[id] = m.exports; } } } stringRequire = function (systemRequire, exports, module, id, relId) { //Split the ID by a ! so that var index = id.indexOf('!'), originalId = id, prefix, plugin; if (index === -1) { id = normalize(id, relId); //Straight module lookup. If it is one of the special dependencies, //deal with it, otherwise, delegate to node. if (id === 'require') { return makeRequire(systemRequire, exports, module, relId); } else if (id === 'exports') { return exports; } else if (id === 'module') { return module; } else if (loaderCache.hasOwnProperty(id)) { return loaderCache[id]; } else if (defineCache[id]) { runFactory.apply(null, defineCache[id]); return loaderCache[id]; } else { if(systemRequire) { return systemRequire(originalId); } else { throw new Error('No module with ID: ' + id); } } } else { //There is a plugin in play. prefix = id.substring(0, index); id = id.substring(index + 1, id.length); plugin = stringRequire(systemRequire, exports, module, prefix, relId); if (plugin.normalize) { id = plugin.normalize(id, makeNormalize(relId)); } else { //Normalize the ID normally. id = normalize(id, relId); } if (loaderCache[id]) { return loaderCache[id]; } else { plugin.load(id, makeRequire(systemRequire, exports, module, relId), makeLoad(id), {}); return loaderCache[id]; } } }; //Create a define function specific to the module asking for amdefine. function define(id, deps, factory) { if (Array.isArray(id)) { factory = deps; deps = id; id = undefined; } else if (typeof id !== 'string') { factory = id; id = deps = undefined; } if (deps && !Array.isArray(deps)) { factory = deps; deps = undefined; } if (!deps) { deps = ['require', 'exports', 'module']; } //Set up properties for this module. If an ID, then use //internal cache. If no ID, then use the external variables //for this node module. if (id) { //Put the module in deep freeze until there is a //require call for it. defineCache[id] = [id, deps, factory]; } else { runFactory(id, deps, factory); } } //define.require, which has access to all the values in the //cache. Useful for AMD modules that all have IDs in the file, //but need to finally export a value to node based on one of those //IDs. define.require = function (id) { if (loaderCache[id]) { return loaderCache[id]; } if (defineCache[id]) { runFactory.apply(null, defineCache[id]); return loaderCache[id]; } }; define.amd = {}; return define; } module.exports = amdefine; },{"__browserify_process":3,"path":2}],15:[function(require,module,exports){ /** * Copyright 2013 Facebook, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* jshint browser: true */ /* jslint evil: true */ 'use strict'; var runScripts; var headEl; var transform = require('./fbtransform/lib/transform').transform; var visitors = require('./fbtransform/visitors').transformVisitors; var transform = transform.bind(null, visitors.react); var docblock = require('./fbtransform/lib/docblock'); exports.transform = transform; exports.exec = function(code) { return eval(transform(code)); }; if (typeof window === "undefined" || window === null) { return; } headEl = document.getElementsByTagName('head')[0]; var run = exports.run = function(code) { var jsx = docblock.parseAsObject(docblock.extract(code)).jsx; var functionBody = jsx ? transform(code).code : code; var scriptEl = document.createElement('script'); scriptEl.innerHTML = functionBody; headEl.appendChild(scriptEl); }; var load = exports.load = function(url, callback) { var xhr; xhr = window.ActiveXObject ? new window.ActiveXObject('Microsoft.XMLHTTP') : new XMLHttpRequest(); // Disable async since we need to execute scripts in the order they are in the // DOM to mirror normal script loading. xhr.open('GET', url, false); if ('overrideMimeType' in xhr) { xhr.overrideMimeType('text/plain'); } xhr.onreadystatechange = function() { if (xhr.readyState === 4) { if (xhr.status === 0 || xhr.status === 200) { run(xhr.responseText); } else { throw new Error("Could not load " + url); } if (callback) { return callback(); } } }; return xhr.send(null); }; runScripts = function() { var scripts = document.getElementsByTagName('script'); scripts = Array.prototype.slice.call(scripts); var jsxScripts = scripts.filter(function(script) { return script.type === 'text/jsx'; }); jsxScripts.forEach(function(script) { if (script.src) { load(script.src); } else { run(script.innerHTML); } }); }; if (window.addEventListener) { window.addEventListener('DOMContentLoaded', runScripts, false); } else { window.attachEvent('onload', runScripts); } },{"./fbtransform/lib/docblock":16,"./fbtransform/lib/transform":17,"./fbtransform/visitors":23}],16:[function(require,module,exports){ /** * Copyright 2013 Facebook, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ var docblockRe = /^\s*(\/\*\*(.|\n)*?\*\/)/; var ltrimRe = /^\s*/; /** * @param {String} contents * @return {String} */ function extract(contents) { var match = contents.match(docblockRe); if (match) { return match[0].replace(ltrimRe, '') || ''; } return ''; } var commentStartRe = /^\/\*\*?/; var commentEndRe = /\*\/$/; var wsRe = /[\t ]+/g; var stringStartRe = /(\n|^) *\*/g; var multilineRe = /(?:^|\n) *(@[^\n]*?) *\n *([^@\n\s][^@\n]+?) *\n/g; var propertyRe = /(?:^|\n) *@(\S+) *([^\n]*)/g; /** * @param {String} contents * @return {Array} */ function parse(docblock) { docblock = docblock .replace(commentStartRe, '') .replace(commentEndRe, '') .replace(wsRe, ' ') .replace(stringStartRe, '$1'); // Normalize multi-line directives var prev = ''; while (prev != docblock) { prev = docblock; docblock = docblock.replace(multilineRe, "\n$1 $2\n"); } docblock = docblock.trim(); var result = []; var match; while (match = propertyRe.exec(docblock)) { result.push([match[1], match[2]]); } return result; } /** * Same as parse but returns an object of prop: value instead of array of paris * If a property appers more than once the last one will be returned * * @param {String} contents * @return {Object} */ function parseAsObject(docblock) { var pairs = parse(docblock); var result = {}; for (var i = 0; i < pairs.length; i++) { result[pairs[i][0]] = pairs[i][1]; } return result; } exports.extract = extract; exports.parse = parse; exports.parseAsObject = parseAsObject; },{}],17:[function(require,module,exports){ /** * Copyright 2013 Facebook, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /*global exports:true*/ /*jslint node: true*/ "use strict"; /** * Syntax transfomer for javascript. Takes the source in, spits the source * out. Tries to maintain readability and preserve whitespace and line numbers * where posssible. * * Support * - ES6 class transformation + private property munging, see ./classes.js * - React XHP style syntax transformations, see ./react.js * - Bolt XHP style syntax transformations, see ./bolt.js * * The general flow is the following: * - Parse the source with our customized esprima-parser * https://github.com/voloko/esprima. We have to customize the parser to * support non-standard XHP-style syntax. We parse the source range: true * option that forces esprima to return positions in the source within * resulting parse tree. * * - Traverse resulting syntax tree, trying to apply a set of visitors to each * node. Each visitor should provide a .test() function that tests if the * visitor can process a given node. * * - Visitor is responsible for code generation for a given syntax node. * Generated code is stored in state.g.buffer that is passed to every * visitor. It's up to the visitor to process the code the way it sees fit. * All of the current visitors however use both the node and the original * source to generate transformed code. They use nodes to generate new * code and they copy the original source, preserving whitespace and comments, * for the parts they don't care about. */ var esprima = require('esprima'); var createState = require('./utils').createState; var catchup = require('./utils').catchup; /** * @param {object} object * @param {function} visitor * @param {array} path * @param {object} state */ function traverse(object, path, state) { var key, child; if (walker(traverse, object, path, state) === false) { return; } path.unshift(object); for (key in object) { // skip obviously wrong attributes if (key === 'range' || key === 'loc') { continue; } if (object.hasOwnProperty(key)) { child = object[key]; if (typeof child === 'object' && child !== null) { child.range && catchup(child.range[0], state); traverse(child, path, state); child.range && catchup(child.range[1], state); } } } path.shift(); } function walker(traverse, object, path, state) { var visitors = state.g.visitors; for (var i = 0; i < visitors.length; i++) { if (visitors[i].test(object, path, state)) { return visitors[i](traverse, object, path, state); } } } function runPass(source, visitors, options) { var ast; try { ast = esprima.parse(source, { comment: true, loc: true, range: true }); } catch (e) { e.message = 'Parse Error: ' + e.message; throw e; } var state = createState(source, options); state.g.originalProgramAST = ast; state.g.visitors = visitors; if (options.sourceMap) { var SourceMapGenerator = require('source-map').SourceMapGenerator; state.g.sourceMap = new SourceMapGenerator({ file: 'transformed.js' }); } traverse(ast, [], state); catchup(source.length, state); return state; } /** * Applies all available transformations to the source * @param {array} visitors * @param {string} source * @param {?object} options * @return {object} */ function transform(visitors, source, options) { options = options || {}; var state = runPass(source, visitors, options); var sourceMap = state.g.sourceMap; if (sourceMap) { return { sourceMap: sourceMap, sourceMapFilename: options.filename || 'source.js', code: state.g.buffer }; } else { return { code: state.g.buffer }; } } exports.transform = transform; },{"./utils":18,"esprima":4,"source-map":5}],18:[function(require,module,exports){ /** * Copyright 2013 Facebook, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /*global exports:true*/ /** * State represents the given parser state. It has a local and global parts. * Global contains parser position, source, etc. Local contains scope based * properties, like current class name. State should contain all the info * required for transformation. It's the only mandatory object that is being * passed to every function in transform chain. * * @param {String} source * @param {Object} transformOptions * @return {Object} */ function createState(source, transformOptions) { return { /** * Name of the super class variable * @type {String} */ superVar: '', /** * Name of the enclosing class scope * @type {String} */ scopeName: '', /** * Global state (not affected by updateState) * @type {Object} */ g: { /** * A set of general options that transformations can consider while doing * a transformation: * * - minify * Specifies that transformation steps should do their best to minify * the output source when possible. This is useful for places where * minification optimizations are possible with higher-level context * info than what jsxmin can provide. * * For example, the ES6 class transform will minify munged private * variables if this flag is set. */ opts: transformOptions, /** * Current position in the source code * @type {Number} */ position: 0, /** * Buffer containing the result * @type {String} */ buffer: '', /** * Indentation offset (only negative offset is supported now) * @type {Number} */ indentBy: 0, /** * Source that is being transformed * @type {String} */ source: source, /** * Cached parsed docblock (see getDocblock) * @type {object} */ docblock: null, /** * Whether the thing was used * @type {Boolean} */ tagNamespaceUsed: false, /** * If using bolt xjs transformation * @type {Boolean} */ isBolt: undefined, /** * Whether to record source map (expensive) or not * @type {SourceMapGenerator|null} */ sourceMap: null, /** * Filename of the file being processed. Will be returned as a source * attribute in the source map */ sourceMapFilename: 'source.js', /** * Only when source map is used: last line in the source for which * source map was generated * @type {Number} */ sourceLine: 1, /** * Only when source map is used: last line in the buffer for which * source map was generated * @type {Number} */ bufferLine: 1, /** * The top-level Program AST for the original file. */ originalProgramAST: null, sourceColumn: 0, bufferColumn: 0 } }; } /** * Updates a copy of a given state with "update" and returns an updated state. * * @param {Object} state * @param {Object} update * @return {Object} */ function updateState(state, update) { return { g: state.g, superVar: update.superVar || state.superVar, scopeName: update.scopeName || state.scopeName }; } /** * Given a state fill the resulting buffer from the original source up to * the end * @param {Number} end * @param {Object} state * @param {Function?} contentTransformer Optional callback to transform newly * added content. */ function catchup(end, state, contentTransformer) { if (end < state.g.position) { // cannot move backwards return; } var source = state.g.source.substring(state.g.position, end); var transformed = updateIndent(source, state); if (state.g.sourceMap && transformed) { // record where we are state.g.sourceMap.addMapping({ generated: { line: state.g.bufferLine, column: state.g.bufferColumn }, original: { line: state.g.sourceLine, column: state.g.sourceColumn }, source: state.g.sourceMapFilename }); // record line breaks in transformed source var sourceLines = source.split('\n'); var transformedLines = transformed.split('\n'); // Add line break mappings between last known mapping and the end of the // added piece. So for the code piece // (foo, bar); // > var x = 2; // > var b = 3; // var c = // only add lines marked with ">": 2, 3. for (var i = 1; i < sourceLines.length - 1; i++) { state.g.sourceMap.addMapping({ generated: { line: state.g.bufferLine, column: 0 }, original: { line: state.g.sourceLine, column: 0 }, source: state.g.sourceMapFilename }); state.g.sourceLine++; state.g.bufferLine++; } // offset for the last piece if (sourceLines.length > 1) { state.g.sourceLine++; state.g.bufferLine++; state.g.sourceColumn = 0; state.g.bufferColumn = 0; } state.g.sourceColumn += sourceLines[sourceLines.length - 1].length; state.g.bufferColumn += transformedLines[transformedLines.length - 1].length; } state.g.buffer += contentTransformer ? contentTransformer(transformed) : transformed; state.g.position = end; } /** * Applies `catchup` but passing in a function that removes any non-whitespace * characters. */ var re = /(\S)/g; function stripNonWhite(value) { return value.replace(re, function() { return ''; }); } /** * Catches up as `catchup` but turns each non-white character into a space. */ function catchupWhiteSpace(end, state) { catchup(end, state, stripNonWhite); } /** * Same as catchup but does not touch the buffer * @param {Number} end * @param {Object} state */ function move(end, state) { // move the internal cursors if (state.g.sourceMap) { if (end < state.g.position) { state.g.position = 0; state.g.sourceLine = 1; state.g.sourceColumn = 0; } var source = state.g.source.substring(state.g.position, end); var sourceLines = source.split('\n'); if (sourceLines.length > 1) { state.g.sourceLine += sourceLines.length - 1; state.g.sourceColumn = 0; } state.g.sourceColumn += sourceLines[sourceLines.length - 1].length; } state.g.position = end; } /** * Appends a string of text to the buffer * @param {String} string * @param {Object} state */ function append(string, state) { if (state.g.sourceMap && string) { state.g.sourceMap.addMapping({ generated: { line: state.g.bufferLine, column: state.g.bufferColumn }, original: { line: state.g.sourceLine, column: state.g.sourceColumn }, source: state.g.sourceMapFilename }); var transformedLines = string.split('\n'); if (transformedLines.length > 1) { state.g.bufferLine += transformedLines.length - 1; state.g.bufferColumn = 0; } state.g.bufferColumn += transformedLines[transformedLines.length - 1].length; } state.g.buffer += string; } /** * Update indent using state.indentBy property. Indent is measured in * double spaces. Updates a single line only. * * @param {String} str * @param {Object} state * @return {String} */ function updateIndent(str, state) { for (var i = 0; i < -state.g.indentBy; i++) { str = str.replace(/(^|\n)( {2}|\t)/g, '$1'); } return str; } /** * Calculates indent from the beginning of the line until "start" or the first * character before start. * @example * " foo.bar()" * ^ * start * indent will be 2 * * @param {Number} start * @param {Object} state * @return {Number} */ function indentBefore(start, state) { var end = start; start = start - 1; while (start > 0 && state.g.source[start] != '\n') { if (!state.g.source[start].match(/[ \t]/)) { end = start; } start--; } return state.g.source.substring(start + 1, end); } function getDocblock(state) { if (!state.g.docblock) { var docblock = require('./docblock'); state.g.docblock = docblock.parseAsObject(docblock.extract(state.g.source)); } return state.g.docblock; } exports.catchup = catchup; exports.catchupWhiteSpace = catchupWhiteSpace; exports.append = append; exports.move = move; exports.updateIndent = updateIndent; exports.indentBefore = indentBefore; exports.updateState = updateState; exports.createState = createState; exports.getDocblock = getDocblock; },{"./docblock":16}],19:[function(require,module,exports){ /** * Copyright 2013 Facebook, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /*global exports:true*/ "use strict"; /** * Desugarizer for ES6 minimal class proposal. See * http://wiki.ecmascript.org/doku.php?id=harmony:proposals * * Does not require any runtime. Preserves whitespace and comments. * Supports a class declaration with methods, super calls and inheritance. * Currently does not support for getters and setters, since there's a very * low probability we're going to use them anytime soon. * * Additional features: * - Any member with private name (the name with prefix _, such _name) inside * the class's scope will be munged. This would will to eliminate the case * of sub-class accidentally overriding the super-class's provate properties * also discouage people from accessing private members that they should not * access. However, quoted property names don't get munged. * * class SkinnedMesh extends require('THREE').Mesh { * * update(camera) { * camera.code = 'iphone' * super.update(camera); * } * * / * * @constructor * / * constructor(geometry, materials) { * super(geometry, materials); * * super.update(1); * * this.identityMatrix = new THREE.Matrix4(); * this.bones = []; * this.boneMatrices = []; * this._name = 'foo'; * } * * / * * some other code * / * readMore() { * * } * * _doSomething() { * * } * } * * should be converted to * * var SkinnedMesh = (function() { * var __super = require('parent').Mesh; * * / * * @constructor * / * function SkinnedMesh(geometry, materials) { * __super.call(this, geometry, materials); * * __super.prototype.update.call(this, 1); * * this.identityMatrix = new THREE.Matrix4(); * this.bones = []; * this.boneMatrices = []; * this.$SkinnedMesh_name = 'foo'; * } * SkinnedMesh.prototype = Object.create(__super.prototype); * SkinnedMesh.prototype.constructor = SkinnedMesh; * * / * * @param camera * / * SkinnedMesh.prototype.update = function(camera) { * camera.code = 'iphone' * __super.prototype.update.call(this, camera); * }; * * SkinnedMesh.prototype.readMore = function() { * * }; * * SkinnedMesh.prototype.$SkinnedMesh_doSomething = function() { * * }; * * return SkinnedMesh; * })(); * */ var Syntax = require('esprima').Syntax; var base62 = require('base62'); var catchup = require('../lib/utils').catchup; var append = require('../lib/utils').append; var move = require('../lib/utils').move; var indentBefore = require('../lib/utils').indentBefore; var updateIndent = require('../lib/utils').updateIndent; var updateState = require('../lib/utils').updateState; function findConstructorIndex(object) { var classElements = object.body && object.body.body || []; for (var i = 0; i < classElements.length; i++) { if (classElements[i].type === Syntax.MethodDefinition && classElements[i].key.name === 'constructor') { return i; } } return -1; } var _mungedSymbolMaps = {}; function getMungedName(scopeName, name, minify) { if (minify) { if (!_mungedSymbolMaps[scopeName]) { _mungedSymbolMaps[scopeName] = { symbolMap: {}, identifierUUIDCounter: 0 }; } var symbolMap = _mungedSymbolMaps[scopeName].symbolMap; if (!symbolMap[name]) { symbolMap[name] = base62.encode(_mungedSymbolMaps[scopeName].identifierUUIDCounter); _mungedSymbolMaps[scopeName].identifierUUIDCounter++; } name = symbolMap[name]; } return '$' + scopeName + name; } function shouldMungeName(scopeName, name, state) { // only run when @preventMunge is not present in the docblock if (state.g.preventMunge === undefined) { var docblock = require('../lib/docblock'); state.g.preventMunge = docblock.parseAsObject( docblock.extract(state.g.source)).preventMunge !== undefined; } // Starts with only a single underscore (i.e. don't count double-underscores) return !state.g.preventMunge && scopeName ? /^_(?!_)/.test(name) : false; } function getProtoOfPrototypeVariableName(superVar) { return superVar + 'ProtoOfPrototype'; } function getSuperKeyName(superVar) { return superVar + 'Key'; } function getSuperProtoOfPrototypeVariable(superVariableName, indent) { var string = (indent + 'var $proto = $superName && $superName.prototype ? ' + '$superName.prototype : $superName;\n' ).replace(/\$proto/g, getProtoOfPrototypeVariableName(superVariableName)) .replace(/\$superName/g, superVariableName); return string; } function getInheritanceSetup(superClassToken, className, indent, superName) { var string = ''; if (superClassToken) { string += getStaticMethodsOnConstructorSetup(className, indent, superName); string += getPrototypeOnConstructorSetup(className, indent, superName); string += getConstructorPropertySetup(className, indent); } return string; } function getStaticMethodsOnConstructorSetup(className, indent, superName) { var string = ( indent + 'for (var $keyName in $superName) {\n' + indent + ' if ($superName.hasOwnProperty($keyName)) {\n' + indent + ' $className[$keyName] = $superName[$keyName];\n' + indent + ' }\n' + indent + '}\n') .replace(/\$className/g, className) .replace(/\$keyName/g, getSuperKeyName(superName)) .replace(/\$superName/g, superName); return string; } function getPrototypeOnConstructorSetup(className, indent, superName) { var string = ( indent + '$className.prototype = Object.create($protoPrototype);\n') .replace(/\$protoPrototype/g, getProtoOfPrototypeVariableName(superName)) .replace(/\$className/g, className); return string; } function getConstructorPropertySetup(className, indent) { var string = ( indent + '$className.prototype.constructor = $className;\n') .replace(/\$className/g, className); return string; } function getSuperConstructorSetup(superClassToken, indent, superName) { if (!superClassToken) return ''; var string = ( '\n' + indent + ' if ($superName && $superName.prototype) {\n' + indent + ' $superName.apply(this, arguments);\n' + indent + ' }\n' + indent) .replace(/\$superName/g, superName); return string; } function getMemberFunctionCall(superVar, propertyName, superArgs) { var string = ( '$superPrototype.$propertyName.call($superArguments)') .replace(/\$superPrototype/g, getProtoOfPrototypeVariableName(superVar)) .replace(/\$propertyName/g, propertyName) .replace(/\$superArguments/g, superArgs); return string; } function getCallParams(classElement, state) { var params = classElement.value.params; if (!params.length) { return ''; } return state.g.source.substring( params[0].range[0], params[params.length - 1].range[1]); } function getSuperArguments(callExpression, state) { var args = callExpression.arguments; if (!args.length) { return 'this'; } return 'this, ' + state.g.source.substring( args[0].range[0], args[args.length - 1].range[1]); } // The seed is used to generate the name for an anonymous class, // and this seed should be unique per browser's session. // The value of the seed looks like this: 1229588505.2969012. var classIDSeed = Date.now() % (60 * 60 * 1000) + Math.random(); /** * Generates a name for an anonymous class. The generated value looks like * this: "Classkc6pcn_mniza1yvi" * @param {String} scopeName * @return {string} the scope name for Anonymous Class */ function generateAnonymousClassName(scopeName) { classIDSeed++; return 'Class' + (classIDSeed).toString(36).replace('.', '_') + (scopeName || ''); } function renderMethods(traverse, object, name, path, state) { var classElements = object.body && object.body.body || []; move(object.body.range[0] + 1, state); for (var i = 0; i < classElements.length; i++) { if (classElements[i].key.name !== 'constructor') { catchup(classElements[i].range[0], state); var memberName = classElements[i].key.name; if (shouldMungeName(state.scopeName, memberName, state)) { memberName = getMungedName( state.scopeName, memberName, state.g.opts.minify ); } var prototypeOrStatic; if (classElements[i]['static']) { prototypeOrStatic = ''; } else { prototypeOrStatic = 'prototype.'; } append(name + '.' + prototypeOrStatic + memberName + ' = ', state); renderMethod(traverse, classElements[i], null, path, state); append(';', state); } move(classElements[i].range[1], state); } if (classElements.length) { append('\n', state); } move(object.range[1], state); } function renderMethod(traverse, method, name, path, state) { append(name ? 'function ' + name + '(' : 'function(', state); append(getCallParams(method, state) + ') {', state); move(method.value.body.range[0] + 1, state); traverse(method.value.body, path, state); catchup(method.value.body.range[1] - 1, state); append('}', state); } function renderSuperClass(traverse, superClass, path, state) { append('var ' + state.superVar + ' = ', state); move(superClass.range[0], state); traverse(superClass, path, state); catchup(superClass.range[1], state); append(';\n', state); } function renderConstructor(traverse, object, name, indent, path, state) { var classElements = object.body && object.body.body || []; var constructorIndex = findConstructorIndex(object); var constructor = constructorIndex === -1 ? null : classElements[constructorIndex]; if (constructor) { move(constructorIndex === 0 ? object.body.range[0] + 1 : classElements[constructorIndex - 1].range[1], state); catchup(constructor.range[0], state); renderMethod(traverse, constructor, name, path, state); append('\n', state); } else { if (object.superClass) { append('\n' + indent, state); } append('function ', state); if (object.id) { move(object.id.range[0], state); } append(name, state); if (object.id) { move(object.id.range[1], state); } append('(){ ', state); if (object.body) { move(object.body.range[0], state); } append(getSuperConstructorSetup( object.superClass, indent, state.superVar), state); append('}\n', state); } } var superId = 0; function renderClassBody(traverse, object, path, state) { var name = object.id ? object.id.name : 'constructor'; var superClass = object.superClass; var indent = updateIndent( indentBefore(object.range[0], state) + ' ', state); state = updateState( state, { scopeName: object.id ? object.id.name : generateAnonymousClassName(state.scopeName), superVar: superClass ? '__super' + superId++ : '' }); // super class if (superClass) { append(indent, state); renderSuperClass(traverse, superClass, path, state); append(getSuperProtoOfPrototypeVariable(state.superVar, indent), state); } renderConstructor(traverse, object, name, indent, path, state); append(getInheritanceSetup(superClass, name, indent, state.superVar), state); renderMethods(traverse, object, name, path, state); } /** * @public */ function visitClassExpression(traverse, object, path, state) { var indent = updateIndent( indentBefore(object.range[0], state) + ' ', state); var name = object.id ? object.id.name : 'constructor'; append('(function() {\n', state); renderClassBody(traverse, object, path, state); append(indent + 'return ' + name + ';\n', state); append(indent.substring(0, indent.length - 2) + '})()', state); return false } visitClassExpression.test = function(object, path, state) { return object.type === Syntax.ClassExpression; }; /** * @public */ function visitClassDeclaration(traverse, object, path, state) { state.g.indentBy--; renderClassBody(traverse, object, path, state); state.g.indentBy++; return false; } visitClassDeclaration.test = function(object, path, state) { return object.type === Syntax.ClassDeclaration; }; /** * @public */ function visitSuperCall(traverse, object, path, state) { if (path[0].type === Syntax.CallExpression) { append(state.superVar + '.call(' + getSuperArguments(path[0], state) + ')', state); move(path[0].range[1], state); } else if (path[0].type === Syntax.MemberExpression) { append(getMemberFunctionCall( state.superVar, path[0].property.name, getSuperArguments(path[1], state)), state); move(path[1].range[1], state); } return false; } visitSuperCall.test = function(object, path, state) { return state.superVar && object.type === Syntax.Identifier && object.name === 'super'; }; /** * @public */ function visitPrivateProperty(traverse, object, path, state) { var type = path[0] ? path[0].type : null; if (type !== Syntax.Property) { if (type === Syntax.MemberExpression) { type = path[0].object ? path[0].object.type : null; if (type === Syntax.Identifier && path[0].object.range[0] === object.range[0]) { // Identifier is a variable that appears "private". return; } } else { // Other syntax that are neither Property nor MemberExpression. return; } } var oldName = object.name; var newName = getMungedName( state.scopeName, oldName, state.g.opts.minify ); append(newName, state); move(object.range[1], state); } visitPrivateProperty.test = function(object, path, state) { return object.type === Syntax.Identifier && shouldMungeName(state.scopeName, object.name, state); }; exports.visitClassDeclaration = visitClassDeclaration; exports.visitClassExpression = visitClassExpression; exports.visitSuperCall = visitSuperCall; exports.visitPrivateProperty = visitPrivateProperty; },{"../lib/docblock":16,"../lib/utils":18,"base62":1,"esprima":4}],20:[function(require,module,exports){ /** * Copyright 2013 Facebook, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /*global exports:true*/ "use strict"; var Syntax = require('esprima').Syntax; var catchup = require('../lib/utils').catchup; var append = require('../lib/utils').append; var move = require('../lib/utils').move; var getDocblock = require('../lib/utils').getDocblock; var FALLBACK_TAGS = require('./xjs').knownTags; var renderXJSExpressionContainer = require('./xjs').renderXJSExpressionContainer; var renderXJSLiteral = require('./xjs').renderXJSLiteral; var quoteAttrName = require('./xjs').quoteAttrName; /** * Customized desugar processor. * * Currently: (Somewhat tailored to React) * <X> </X> => X(null, null) * <X prop="1" /> => X({prop: '1'}, null) * <X prop="2"><Y /></X> => X({prop:'2'}, Y(null, null)) * <X prop="2"><Y /><Z /></X> => X({prop:'2'}, [Y(null, null), Z(null, null)]) * * Exceptions to the simple rules above: * if a property is named "class" it will be changed to "className" in the * javascript since "class" is not a valid object key in javascript. */ var JSX_ATTRIBUTE_RENAMES = { 'class': 'className', cxName: 'className' }; var JSX_ATTRIBUTE_TRANSFORMS = { cxName: function(attr) { if (attr.value.type !== Syntax.Literal) { throw new Error("cx only accepts a string literal"); } else { var classNames = attr.value.value.split(/\s+/g); return 'cx(' + classNames.map(JSON.stringify).join(',') + ')'; } } }; function visitReactTag(traverse, object, path, state) { var jsxObjIdent = getDocblock(state).jsx; catchup(object.openingElement.range[0], state); if (object.name.namespace) { throw new Error( 'Namespace tags are not supported. ReactJSX is not XML.'); } var isFallbackTag = FALLBACK_TAGS[object.name.name]; append( (isFallbackTag ? jsxObjIdent + '.' : '') + (object.name.name) + '(', state ); move(object.name.range[1], state); var childrenToRender = object.children.filter(function(child) { return !(child.type === Syntax.Literal && !child.value.match(/\S/)); }); // if we don't have any attributes, pass in null if (object.attributes.length === 0) { append('null', state); } // write attributes object.attributes.forEach(function(attr, index) { catchup(attr.range[0], state); if (attr.name.namespace) { throw new Error( 'Namespace attributes are not supported. ReactJSX is not XML.'); } var name = JSX_ATTRIBUTE_RENAMES[attr.name.name] || attr.name.name; var isFirst = index === 0; var isLast = index === object.attributes.length - 1; if (isFirst) { append('{', state); } append(quoteAttrName(name), state); append(':', state); if (!attr.value) { state.g.buffer += 'true'; state.g.position = attr.name.range[1]; if (!isLast) { append(',', state); } } else if (JSX_ATTRIBUTE_TRANSFORMS[attr.name.name]) { move(attr.value.range[0], state); append(JSX_ATTRIBUTE_TRANSFORMS[attr.name.name](attr), state); move(attr.value.range[1], state); if (!isLast) { append(',', state); } } else if (attr.value.type === Syntax.Literal) { move(attr.value.range[0], state); renderXJSLiteral(attr.value, isLast, state); } else { move(attr.value.range[0], state); renderXJSExpressionContainer(traverse, attr.value, isLast, path, state); } if (isLast) { append('}', state); } catchup(attr.range[1], state); }); if (!object.selfClosing) { catchup(object.openingElement.range[1] - 1, state); move(object.openingElement.range[1], state); } // filter out whitespace if (childrenToRender.length > 0) { append(', ', state); object.children.forEach(function(child) { if (child.type === Syntax.Literal && !child.value.match(/\S/)) { return; } catchup(child.range[0], state); var isLast = child === childrenToRender[childrenToRender.length - 1]; if (child.type === Syntax.Literal) { renderXJSLiteral(child, isLast, state); } else if (child.type === Syntax.XJSExpressionContainer) { renderXJSExpressionContainer(traverse, child, isLast, path, state); } else { traverse(child, path, state); if (!isLast) { append(',', state); state.g.buffer = state.g.buffer.replace(/(\s*),$/, ',$1'); } } catchup(child.range[1], state); }); } if (object.selfClosing) { // everything up to /> catchup(object.openingElement.range[1] - 2, state); move(object.openingElement.range[1], state); } else { // everything up to </ sdflksjfd> catchup(object.closingElement.range[0], state); move(object.closingElement.range[1], state); } append(')', state); return false; } visitReactTag.test = function(object, path, state) { // only run react when react @jsx namespace is specified in docblock var jsx = getDocblock(state).jsx; return object.type === Syntax.XJSElement && jsx && jsx.length; }; exports.visitReactTag = visitReactTag; },{"../lib/utils":18,"./xjs":22,"esprima":4}],21:[function(require,module,exports){ /** * Copyright 2013 Facebook, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /*global exports:true*/ "use strict"; var Syntax = require('esprima').Syntax; var catchup = require('../lib/utils').catchup; var append = require('../lib/utils').append; var getDocblock = require('../lib/utils').getDocblock; /** * Transforms the following: * * var MyComponent = React.createClass({ * render: ... * }); * * into: * * var MyComponent = React.createClass({ * displayName: 'MyComponent', * render: ... * }); */ function visitReactDisplayName(traverse, object, path, state) { if (object.id.type === Syntax.Identifier && object.init && object.init.type === Syntax.CallExpression && object.init.callee.type === Syntax.MemberExpression && object.init.callee.object.type === Syntax.Identifier && object.init.callee.object.name === 'React' && object.init.callee.property.type === Syntax.Identifier && object.init.callee.property.name === 'createClass' && object.init['arguments'].length === 1 && object.init['arguments'][0].type === Syntax.ObjectExpression) { var displayName = object.id.name; catchup(object.init['arguments'][0].range[0] + 1, state); append("displayName: '" + displayName + "',", state); } } /** * Will only run on @jsx files for now. */ visitReactDisplayName.test = function(object, path, state) { return object.type === Syntax.VariableDeclarator && !!getDocblock(state).jsx; }; exports.visitReactDisplayName = visitReactDisplayName; },{"../lib/utils":18,"esprima":4}],22:[function(require,module,exports){ /** * Copyright 2013 Facebook, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /*global exports:true*/ "use strict"; var append = require('../lib/utils').append; var catchup = require('../lib/utils').catchup; var move = require('../lib/utils').move; var Syntax = require('esprima').Syntax; var knownTags = { a: true, abbr: true, address: true, applet: true, area: true, article: true, aside: true, audio: true, b: true, base: true, bdi: true, bdo: true, big: true, blockquote: true, body: true, br: true, button: true, canvas: true, caption: true, circle: true, cite: true, code: true, col: true, colgroup: true, command: true, data: true, datalist: true, dd: true, del: true, details: true, dfn: true, dialog: true, div: true, dl: true, dt: true, ellipse: true, em: true, embed: true, fieldset: true, figcaption: true, figure: true, footer: true, form: true, g: true, h1: true, h2: true, h3: true, h4: true, h5: true, h6: true, head: true, header: true, hgroup: true, hr: true, html: true, i: true, iframe: true, img: true, input: true, ins: true, kbd: true, keygen: true, label: true, legend: true, li: true, line: true, link: true, main: true, map: true, mark: true, marquee: true, menu: true, menuitem: true, meta: true, meter: true, nav: true, noscript: true, object: true, ol: true, optgroup: true, option: true, output: true, p: true, param: true, path: true, polyline: true, pre: true, progress: true, q: true, rect: true, rp: true, rt: true, ruby: true, s: true, samp: true, script: true, section: true, select: true, small: true, source: true, span: true, strong: true, style: true, sub: true, summary: true, sup: true, svg: true, table: true, tbody: true, td: true, text: true, textarea: true, tfoot: true, th: true, thead: true, time: true, title: true, tr: true, track: true, u: true, ul: true, 'var': true, video: true, wbr: true }; function safeTrim(string) { return string.replace(/^[ \t]+/, '').replace(/[ \t]+$/, ''); } // Replace all trailing whitespace characters with a single space character function trimWithSingleSpace(string) { return string.replace(/^[ \t\xA0]{2,}/, ' '). replace(/[ \t\xA0]{2,}$/, ' ').replace(/^\s+$/, ''); } /** * Special handling for multiline string literals * print lines: * * line * line * * as: * * "line "+ * "line" */ function renderXJSLiteral(object, isLast, state, start, end) { /** Added blank check filtering and triming*/ var trimmedChildValue = safeTrim(object.value); if (trimmedChildValue) { // head whitespace append(object.value.match(/^[\t ]*/)[0], state); if (start) { append(start, state); } var trimmedChildValueWithSpace = trimWithSingleSpace(object.value); /** */ var initialLines = trimmedChildValue.split(/\r\n|\n|\r/); var lines = initialLines.filter(function(line) { return safeTrim(line).length > 0; }); var hasInitialNewLine = initialLines[0] !== lines[0]; var hasFinalNewLine = initialLines[initialLines.length - 1] !== lines[lines.length - 1]; var numLines = lines.length; lines.forEach(function (line, ii) { var lastLine = ii === numLines - 1; var trimmedLine = safeTrim(line); if (trimmedLine === '' && !lastLine) { append(line, state); } else { var preString = ''; var postString = ''; var leading = ''; if (ii === 0) { if (hasInitialNewLine) { preString = ' '; leading = '\n'; } if (trimmedChildValueWithSpace.substring(0, 1) === ' ') { // If this is the first line, and the original content starts with // whitespace, place a single space at the beginning. preString = ' '; } } else { leading = line.match(/^[ \t]*/)[0]; } if (!lastLine || trimmedChildValueWithSpace.substr( trimmedChildValueWithSpace.length - 1, 1) === ' ' || hasFinalNewLine ) { // If either not on the last line, or the original content ends with // whitespace, place a single character at the end. postString = ' '; } append( leading + JSON.stringify( preString + trimmedLine + postString ) + (lastLine ? '' : '+') + line.match(/[ \t]*$/)[0], state); } if (!lastLine) { append('\n', state); } }); } else { if (start) { append(start, state); } append('""', state); } if (end) { append(end, state); } // add comma before trailing whitespace if (!isLast) { append(',', state); } // tail whitespace append(object.value.match(/[ \t]*$/)[0], state); move(object.range[1], state); } function renderXJSExpressionContainer(traverse, object, isLast, path, state) { // Plus 1 to skip `{`. move(object.range[0] + 1, state); traverse(object.expression, path, state); if (!isLast && object.expression.type !== Syntax.XJSEmptyExpression) { // If we need to append a comma, make sure to do so after the expression. catchup(object.expression.range[1], state); append(',', state); } // Minus 1 to skip `}`. catchup(object.range[1] - 1, state); move(object.range[1], state); return false; } function quoteAttrName(attr) { // Quote invalid JS identifiers. if (!/^[a-z_$][a-z\d_$]*$/i.test(attr)) { return "'" + attr + "'"; } return attr; } exports.knownTags = knownTags; exports.renderXJSExpressionContainer = renderXJSExpressionContainer; exports.renderXJSLiteral = renderXJSLiteral; exports.quoteAttrName = quoteAttrName; },{"../lib/utils":18,"esprima":4}],23:[function(require,module,exports){ /*global exports:true*/ var classes = require('./transforms/classes'); var react = require('./transforms/react'); var reactDisplayName = require('./transforms/reactDisplayName'); /** * Map from transformName => orderedListOfVisitors. */ var transformVisitors = { 'es6-classes': [ classes.visitClassExpression, classes.visitClassDeclaration, classes.visitSuperCall, classes.visitPrivateProperty ] }; transformVisitors.react = transformVisitors[ "es6-classes" ].concat([ react.visitReactTag, reactDisplayName.visitReactDisplayName ]); /** * Specifies the order in which each transform should run. */ var transformRunOrder = [ 'es6-classes', 'react' ]; /** * Given a list of transform names, return the ordered list of visitors to be * passed to the transform() function. * * @param {array?} excludes * @return {array} */ function getVisitorsList(excludes) { var ret = []; for (var i = 0, il = transformRunOrder.length; i < il; i++) { if (!excludes || excludes.indexOf(transformRunOrder[i]) === -1) { ret = ret.concat(transformVisitors[transformRunOrder[i]]); } } return ret; } exports.getVisitorsList = getVisitorsList; exports.transformVisitors = transformVisitors; },{"./transforms/classes":19,"./transforms/react":20,"./transforms/reactDisplayName":21}]},{},[15])(15) }); ;
assets/javascripts/kitten/components/layout/container/test.js
KissKissBankBank/kitten
import React from 'react' import renderer from 'react-test-renderer' import 'jest-styled-components' import { Container } from './index' describe('<Container />', () => { let component describe('compare with snapshot', () => { beforeEach(() => { component = renderer.create(<Container />).toJSON() }) it('matches with snapshot', () => { expect(component).toMatchSnapshot() }) }) describe('by default', () => { const container = mount(<Container />) it('is a <div />', () => { expect(container.find('div').length).toBe(1) }) }) describe('with other props', () => { const container = shallow(<Container aria-hidden />) it('has aria-hidden attribute', () => { expect(container.props()['aria-hidden']).toBeTruthy() }) }) describe('with children', () => { const container = shallow(<Container>Lorem ipsum…</Container>) it('has text', () => { expect(container.text()).toBe('Lorem ipsum…') }) }) describe('with fullWidthBelowScreenSize props', () => { it('has padding CSS rule', () => { const tree = renderer .create(<Container fullWidthBelowScreenSize="M" />) .toJSON() expect(tree).toHaveStyleRule('padding-right', '1.25rem') expect(tree).toHaveStyleRule('padding-right', '2.5rem', { media: '(min-width:640px)', }) expect(tree).toHaveStyleRule('padding-right', '0', { media: '(max-width:1079px)', }) expect(tree).toHaveStyleRule('padding-left', '1.25rem') expect(tree).toHaveStyleRule('padding-left', '2.5rem', { media: '(min-width:640px)', }) expect(tree).toHaveStyleRule('padding-left', '0', { media: '(max-width:1079px)', }) }) }) })
files/maxmertkit/1.0.1/js/maxmertkit.min.js
bdukes/jsdelivr
(function(){"use strict";var t,i,e,n,o,s,r;n=[],s=[],o={x:0,y:0,z:0},r="0.0.1",t=function(){function t(t){this.name=t}return t.prototype.callbacks=n,t.prototype.registerCallback=function(t){return this.callbacks.push(t)},t}(),e=function(){function i(){}return i.prototype.events=s,i.prototype.registerEvent=function(i){var e;return e=new t(i),null==this.events[i]?this.events[i]=e:void 0},i.prototype.dispatchEvent=function(t,i){var e,n,o,s,r;for(s=this.events[t].callbacks,r=[],n=0,o=s.length;o>n;n++)e=s[n],r.push(e(i));return r},i.prototype.addEventListener=function(t,i){return this.events[t].registerCallback(i)},i}(),i=function(){function t(t,i){this.$btn=t,this.options=i,this._pushInstance(),null!=this._afterConstruct&&this._afterConstruct()}return t.prototype._id=0,t.prototype._instances=new Array,t.prototype.destroy=function(){return this.$el.off("."+this._name),this._popInstance()},t.prototype._extend=function(t,i){var e,n;for(e in i)n=i[e],t[e]=n;return t},t.prototype._merge=function(t,i){return this._extend(this._extend({},t),i)},t.prototype._setOptions=function(){return console.warning("Maxmertkit Helpers. There is no standart setOptions function.")},t.prototype._pushInstance=function(){return this._id++,this._instances.push(this)},t.prototype._popInstance=function(){var t,i,e,n,o,s;for(o=this._instances,s=[],t=e=0,n=o.length;n>e;t=++e)i=o[t],i._id===this._id&&this._instances.splice(t,1),s.push(delete this);return s},t.prototype._selfish=function(){var t,i,e,n,o,s;for(o=this._instances,s=[],t=e=0,n=o.length;n>e;t=++e)i=o[t],s.push(this._id!==i._id?i.close():void 0);return s},t.prototype._getVersion=function(){return r},t.prototype.reactor=new e,t.prototype._setTransform=function(t,i){return t.webkitTransform=i,t.MozTransform=i,t.transform=i},t.prototype._equalNodes=function(t,i){return t.get(0)===i.get(0)},t.prototype._deviceMobile=function(){return/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent)},t.prototype._refreshSizes=function(){return this._windowHeight=$(window).height(),this._windowWidth=$(window).width(),this._height=this.$el.height(),this._width=this.$el.width(),this._offset=null!=this.scroll?("BODY"===this.scroll[0].nodeName,this.$el.offset()):this.$el.offset()},t.prototype._getContainer=function(t){var i,e;for(i=t[0]||t;null!=i&&(i=i.parentNode);){try{e=getComputedStyle(i)}catch(n){}if(null==e)return $(i);if(/(relative|fixed)/.test(e.position)||null!=i&&null!=i.style&&/(relative|fixed)/.test(i.style.position))return $(i)}return $(document)},t.prototype._getScrollParent=function(t){var i,e;for(i=t[0]||t;i=i.parentNode;){try{e=getComputedStyle(i)}catch(n){}if(null==e)return $(i);if(/(auto|scroll)/.test(e.overflow+e["overflow-y"]+e["overflow-x"])&&"BODY"!==$(i)[0].nodeName)return $(i)}return $(document)},t.prototype._isVisible=function(){return this._offset.top-this._windowHeight<=this.scroll.scrollTop()&&this.scroll.scrollTop()<=this._offset.top+this._height},t.prototype._getVisiblePercent=function(){var t,i,e;return e=this._offset.top,t=this.scroll.scrollTop(),i=this._offset.top+this._height,(t-e)/(i-e)},t.prototype._scrollVisible=function(){var t,i,e,n;return null!=this.scroll?(e=this._offset.top-this._windowHeight,i=this._offset.top+this._height+this._windowHeight,t=this.scroll.scrollTop()+this._windowHeight,n=1-t/i,1>n&&n>0):!0},t.prototype._setGlobalRotation=function(t,i,e){return o={x:t,y:i,z:e}},t.prototype._getGlobalRotation=function(){return o},t}(),function(){var t,i,e;t=jQuery.event.special,i="D"+ +new Date,e="D"+(+new Date+1),t.scrollstart={setup:function(){var e,n;n=void 0,e=function(i){var e;e=arguments,n?clearTimeout(n):(i.type="scrollstart",jQuery.event.trigger.apply(this,e)),n=setTimeout(function(){n=null},t.scrollstop.latency)},jQuery(this).bind("scroll",e).data(i,e)},teardown:function(){jQuery(this).unbind("scroll",jQuery(this).data(i))}},t.scrollstop={latency:300,setup:function(){var i,n;n=void 0,i=function(i){var e;e=arguments,n&&clearTimeout(n),n=setTimeout(function(){n=null,i.type="scrollstop",jQuery.event.trigger.apply(this,e)},t.scrollstop.latency)},jQuery(this).bind("scroll",i).data(e,i)},teardown:function(){jQuery(this).unbind("scroll",jQuery(this).data(e))}}}(),window.MaxmertkitHelpers=i}).call(this),function(){var t,i,e,n,o,s,r,a,h,c={}.hasOwnProperty,l=function(t,i){function e(){this.constructor=t}for(var n in i)c.call(i,n)&&(t[n]=i[n]);return e.prototype=i.prototype,t.prototype=new e,t.__super__=i.prototype,t};s="modal",o=[],t=function(t){function n(t,i){var e;this.btn=t,this.options=i,this.$btn=$(this.btn),e={target:this.$btn.data("target"),toggle:this.$btn.data("toggle")||"modal",event:"click."+this._name,eventClose:"click."+this._name,backdrop:this.$btn.data("backdrop")||!1,push:this.$btn.data("push")||!1,beforeactive:function(){},onactive:function(){},beforeunactive:function(){},onunactive:function(){}},this.options=this._merge(e,this.options),this.$el=$(document).find(this.options.target),this.$btn.on(this.options.event,function(t){return function(i){return i.preventDefault(),t.open()}}(this)),this._setOptions(this.options),this.$el.find("*[data-dismiss='modal']").on(this.options.event,function(t){return function(){return t.close()}}(this)),n.__super__.constructor.call(this,this.$btn,this.options),this.reactor.registerEvent("close.modal")}return l(n,t),n.prototype._name=s,n.prototype._instances=o,n.prototype._setOptions=function(t){var i,e,n;for(i in t){if(n=t[i],null==this.options[i])return i!=="kit-"+s?console.error("Maxmertkit Modal. You're trying to set unpropriate option – "+i):null;switch(i){case"backdrop":n&&this.$el.on("click."+this._name,function(t){return function(i){return $(i.target).hasClass("-modal _active_")||$(i.target).hasClass("-carousel")?t.close():void 0}}(this));break;case"push":n&&(e=$(document).find(n),e.length&&(this.$push=$(document).find(n)))}this.options[i]=n,"function"==typeof n&&(this[i]=this.options[i])}},n.prototype.destroy=function(){return this.$btn.off("."+this._name),n.__super__.destroy.apply(this,arguments)},n.prototype.open=function(){return e.call(this)},n.prototype.close=function(){return i.call(this)},n}(MaxmertkitHelpers),a=function(){return null!=this.$push?(this.$push.addClass("-start--"),this.$push.removeClass("-stop--")):void 0},h=function(){return null!=this.$push&&(this.$push.addClass("-stop--"),this.$push.removeClass("-start--"),null!=this.$push[0]&&null!=this.$push[0].style&&null!=this.$push[0].style["-webkit-overflow-scrolling"])?this.$push[0].style["-webkit-overflow-scrolling"]="auto":void 0},e=function(){var t;if(null==this.beforeopen)return r.call(this);try{return t=this.beforeopen.call(this.$btn),t.done(function(t){return function(){return r.call(t)}}(this)).fail(function(t){return function(){return t.$el.trigger("fail."+t._name)}}(this))}catch(i){return r.call(this)}},r=function(){if(null!=this.$push&&$("body").addClass("_perspective_"),this.$el.css({display:"table"}),setTimeout(function(t){return function(){return t.$el.addClass("_visible_ -start--"),t.$el.find(".-dialog").addClass("_visible_ -start--"),a.call(t)}}(this),1),$("body").addClass("_no-scroll_"),this.$el.trigger("opened."+this._name),null!=this.onopen)try{return this.onopen.call(this.$btn)}catch(t){}},i=function(){var t;if(null==this.beforeclose)return n.call(this);try{return t=this.beforeclose.call(this.$btn),t.done(function(t){return function(){return n.call(t)}}(this)).fail(function(t){return function(){return t.$el.trigger("fail."+t._name)}}(this))}catch(i){return n.call(this)}},n=function(){if(this.$el.addClass("-stop--"),this.$el.find(".-dialog").addClass("-stop--"),h.call(this),setTimeout(function(t){return function(){return t.$el.removeClass("_visible_ -start-- -stop--"),t.$el.find(".-dialog").removeClass("_visible_ -start-- -stop--"),$("body").removeClass("_no-scroll_"),null!=t.$push&&$("body").removeClass("_perspective_"),t.$el.hide()}}(this),1e3),this.$el.trigger("closed."+this._name),this.reactor.dispatchEvent("close.modal"),null!=this.onclose)try{return this.onclose.call(this.$btn)}catch(t){}},$.fn[s]=function(i){return this.each(function(){$.data(this,"kit-"+s)?"object"==typeof i?$.data(this,"kit-"+s)._setOptions(i):"string"==typeof i&&"_"!==i.charAt(0)?$.data(this,"kit-"+s)[i]:console.error("Maxmertkit error. You passed into the "+s+" something wrong."):$.data(this,"kit-"+s,new t(this,i))})},$(window).on("load",function(){return $('[data-toggle="modal"]').each(function(){var t;return t=$(this),t.modal(t.data())})})}.call(this),function(){var t,i,e,n,o,s,r,a,h,c,l={}.hasOwnProperty,u=function(t,i){function e(){this.constructor=t}for(var n in i)l.call(i,n)&&(t[n]=i[n]);return e.prototype=i.prototype,t.prototype=new e,t.__super__=i.prototype,t};s="affix",o=[],n=0,t=function(t){function r(t,i){var e;this.el=t,this.options=i,this.$el=$(this.el),this.$el.parent().append("&nbsp;"),this._id=n++,e={spy:this.$el.data("spy")||"affix",offset:5,beforeactive:function(){},onactive:function(){},beforeunactive:function(){},onunactive:function(){}},this.options=this._merge(e,this.options),this.beforeactive=this.options.beforeactive,this.onactive=this.options.onactive,this.beforeunactive=this.options.beforeunactive,this.onunactive=this.options.onunactive,this.start(),r.__super__.constructor.call(this,this.$btn,this.options)}return u(r,t),r.prototype._name=s,r.prototype._instances=o,r.prototype._setOptions=function(t){var i,e;for(i in t){if(e=t[i],null==this.options[i])return i!=="kit-"+s?console.error("Maxmertkit Affix. You're trying to set unpropriate option – "+i):null;this.options[i]=e}},r.prototype.destroy=function(){return r.__super__.destroy.apply(this,arguments)},r.prototype.start=function(){return i.call(this)},r.prototype.stop=function(){return e.call(this)},r}(MaxmertkitHelpers),a=function(){var t,i;return t=this._getContainer(this.$el),i="HTML"===t[0].firstElementChild.nodeName?0:t.offset().top,null!=this.$el.parent()&&this.$el.parent().offset()&&!this._deviceMobile()&&this._windowWidth>992?this.$el.parent().offset().top-this.options.offset<=$(document).scrollTop()?this.$el.css(this.$el.parent().offset().top+t.outerHeight()-this.options.offset-this.$el.outerHeight()>=$(document).scrollTop()?{width:this.$el.width(),position:"fixed",top:""+this.options.offset+"px",bottom:"auto"}:{position:"absolute",top:"auto",bottom:"-"+this.options.offset+"px",width:this.$el.width()}):(this.$el.css("position","relative"),this.$el.css("top","inherit")):void 0},r=function(){return $(document).on("scroll."+this._name+"."+this._id,function(t){return function(){return a.call(t)}}(this)),$(window).on("resize."+this._name+"."+this._id,function(t){return function(){return t._refreshSizes(),t._windowWidth<992?(t.$el.css("position","relative"),t.$el.css("top","inherit")):a.call(t)}}(this))},i=function(){var t;if(null==this.beforeactive)return h.call(this);try{return t=this.beforeactive.call(this.$el),t.done(function(t){return function(){return h.call(t)}}(this)).fail(function(t){return function(){return t.$el.trigger("fail."+t._name)}}(this))}catch(i){return h.call(this)}},h=function(){if(this._refreshSizes(),r.call(this),this.$el.addClass("_active_"),this.$el.trigger("started."+this._name),null!=this.onactive)try{return this.onactive.call(this.$el)}catch(t){}},e=function(){var t;if(null==this.beforeunactive)return c.call(this);try{return t=this.beforeunactive.call(this.$el),t.done(function(t){return function(){return c.call(t)}}(this)).fail(function(t){return function(){return t.$el.trigger("fail."+t._name)}}(this))}catch(i){return c.call(this)}},c=function(){if(this.$el.removeClass("_active_"),$(document).off("scroll."+this._name+"."+this._id),this.$el.trigger("stopped."+this._name),null!=this.onunactive)try{return this.onunactive.call(this.$el)}catch(t){}},$.fn[s]=function(i){return this.each(function(){$.data(this,"kit-"+s)?"object"==typeof i?$.data(this,"kit-"+s)._setOptions(i):"string"==typeof i&&"_"!==i.charAt(0)&&$.data(this,"kit-"+s)[i]:$.data(this,"kit-"+s,new t(this,i))})}}.call(this),function(){var t,i,e,n,o,s,r,a,h={}.hasOwnProperty,c=function(t,i){function e(){this.constructor=t}for(var n in i)h.call(i,n)&&(t[n]=i[n]);return e.prototype=i.prototype,t.prototype=new e,t.__super__=i.prototype,t};a="button",r=[],s=0,t=function(t){function i(t,e){var n;this.btn=t,this.options=e,this.$btn=$(this.btn),this._id=s++,n={toggle:this.$btn.data("toggle")||"button",group:this.$btn.data("group")||null,type:this.$btn.data("type")||"button",event:"click",beforeactive:function(){},onactive:function(){},beforeunactive:function(){},onunactive:function(){}},this.options=this._merge(n,this.options),this.beforeactive=this.options.beforeactive,this.onactive=this.options.onactive,this.beforeunactive=this.options.beforeunactive,this.onunactive=this.options.onunactive,this.$btn.on(this.options.event,function(t){return function(){return t.$btn.hasClass("_active_")?t.deactivate():t.activate()}}(this)),this.$btn.on(this.options.eventClose,function(t){return function(){return t.options.event!==t.options.eventClose?t.deactivate():void 0}}(this)),this.$btn.removeClass("_active_ _disabled_ _loading_"),i.__super__.constructor.call(this,this.$btn,this.options)}return c(i,t),i.prototype._name=a,i.prototype._instances=r,i.prototype._setOptions=function(t){var i,e;for(i in t){if(e=t[i],null==this.options[i])return i!=="kit-"+a?console.error("Maxmertkit Button. You're trying to set unpropriate option – "+i):null;switch(i){case"event":this.$btn.off(""+this.options.event+"."+this._name),this.options.event=e,this.$btn.on(""+this.options.event+"."+this._name,function(t){return function(){return t.$btn.hasClass("_active_")?t.deactivate():t.activate()}}(this));break;default:this.options[i]=e,"function"==typeof e&&(this[i]=this.options[i])}}},i.prototype.destroy=function(){return this.$btn.off("."+this._name),i.__super__.destroy.apply(this,arguments)},i.prototype.activate=function(){return e.call(this)},i.prototype.deactivate=function(){return this.$btn.hasClass("_active_")?n.call(this):void 0},i.prototype.disable=function(){return this.$btn.toggleClass("_disabled_")},i}(MaxmertkitHelpers),e=function(){var t;if(this.options.selfish&&this._selfish(),null==this.beforeactive)return i.call(this);try{return t=this.beforeactive.call(this.$btn),t.done(function(t){return function(){return i.call(t)}}(this)).fail(function(t){return function(){return t.$btn.trigger("fail."+t._name)}}(this))}catch(e){return i.call(this)}},i=function(){var t,i,e,n;if("radio"===this.options.type)for(n=this._instances,i=0,e=n.length;e>i;i++)t=n[i],this._id!==t._id&&"radio"===t.options.type&&t.options.group===this.options.group&&t.deactivate();if(this.$btn.addClass("_active_"),this.$btn.trigger("activated."+this._name),null!=this.onactive)try{return this.onactive.call(this.$btn)}catch(o){}},n=function(){var t;if(null==this.beforeunactive)return o.call(this);try{return t=this.beforeunactive.call(this.$btn),t.done(function(t){return function(){return o.call(t)}}(this)).fail(function(t){return function(){return t.$btn.trigger("fail."+t._name)}}(this))}catch(i){return o.call(this)}},o=function(){if(this.$btn.removeClass("_active_"),this.$btn.trigger("deactivated."+this._name),null!=this.onunactive)try{return this.onunactive.call(this.$btn)}catch(t){}},$.fn[a]=function(i){return this.each(function(){$.data(this,"kit-"+a)?"object"==typeof i?$.data(this,"kit-"+a)._setOptions(i):"string"==typeof i&&"_"!==i.charAt(0)?$.data(this,"kit-"+a)[i]:console.error("Maxmertkit Button. You passed into the "+a+" something wrong.\n"+i):$.data(this,"kit-"+a,new t(this,i))})},$(window).on("load",function(){return $('[data-toggle="button"]').each(function(){var t;return t=$(this),t.button(t.data())})})}.call(this),function(){var t,i,e,n,o,s,r,a,h,c,l,u,p,f={}.hasOwnProperty,_=function(t,i){function e(){this.constructor=t}for(var n in i)f.call(i,n)&&(t[n]=i[n]);return e.prototype=i.prototype,t.prototype=new e,t.__super__=i.prototype,t};h="scrollspy",a=[],r=0,t=function(t){function i(t,e){var n;this.el=t,this.options=e,this.$el=$(this.el),this._id=r++,n={spy:this.$el.data("spy")||"scroll",target:this.$el.data("target")||"body",offset:0,elements:"li a",elementsAttr:"href",noMobile:this.$el.data("no-mobile")||!0,beforeactive:function(){},onactive:function(){},beforeunactive:function(){},onunactive:function(){}},this.options=this._merge(n,this.options),this.beforeactive=this.options.beforeactive,this.onactive=this.options.onactive,this.beforeunactive=this.options.beforeunactive,this.onunactive=this.options.onunactive,this.start(),i.__super__.constructor.call(this,this.$btn,this.options)}return _(i,t),i.prototype._name=h,i.prototype._instances=a,i.prototype._setOptions=function(t){var i,e;for(i in t){if(e=t[i],null==this.options[i])return i!=="kit-"+h?console.error("Maxmertkit Scrollspy. You're trying to set unpropriate option."):null;this.options[i]=e}},i.prototype.destroy=function(){return i.__super__.destroy.apply(this,arguments)},i.prototype.refresh=function(){return c.call(this)},i.prototype.start=function(){return n.call(this)},i.prototype.stop=function(){return o.call(this)},i}(MaxmertkitHelpers),e=function(t){var i,e,n,o;for(o=this.elements,e=0,n=o.length;n>e;e++)i=o[e],i.menu.removeClass("_active_");return this.elements[t].menu.addClass("_active_").parents("li").addClass("_active_")},s=function(t){return this.elements[t].menu.removeClass("_active_")},c=function(){return this.elements=[],this.$el.find(this.options.elements).each(function(t){return function(i,e){var n,o;return o=$(e).attr(t.options.elementsAttr),null!=o&&(n=$(t.options.target).find(o),n.length)?t.elements.push({menu:$(e).parent(),item:n.parent(),itemHeight:n.parent().height(),offsetTop:n.position().top}):void 0}}(this))},l=function(t){var i,n,o;for(i=0,o=[];i<this.elements.length;)this.elements[i].offsetTop<=(n=(t.currentTarget.scrollTop||t.currentTarget.scrollY)+this.options.offset)&&n<=this.elements[i].offsetTop+this.elements[i].itemHeight?this.elements[i].menu.hasClass("_active_")||e.call(this,i):this.elements[i].menu.hasClass("_active_")&&(t.currentTarget.scrollTop||t.currentTarget.scrollY)+this.options.offset<this.elements[i].offsetTop+this.elements[i].itemHeight&&s.call(this,i),o.push(i++);return o},i=function(){var t;return t="body"===this.options.target?window:this.options.target,$(t).on("scroll."+this._name+"."+this._id,function(t){return function(i){return l.call(t,i)}}(this))},n=function(){var t;if(this.refresh(),null==this.beforeactive)return u.call(this);try{return t=this.beforeactive.call(this.$el),t.done(function(t){return function(){return u.call(t)}}(this)).fail(function(t){return function(){return t.$el.trigger("fail."+t._name)}}(this))}catch(i){return u.call(this)}},u=function(){if(i.call(this),this.$el.addClass("_active_"),this.$el.trigger("started."+this._name),null!=this.onactive)try{return this.onactive.call(this.$el)}catch(t){}},o=function(){var t;if(null==this.beforeunactive)return p.call(this);try{return t=this.beforeunactive.call(this.$el),t.done(function(t){return function(){return p.call(t)}}(this)).fail(function(t){return function(){return t.$el.trigger("fail."+t._name)}}(this))}catch(i){return p.call(this)}},p=function(){var t;if(t="body"===this.options.target?window:this.options.target,$(t).off("scroll."+this._name+"."+this._id),this.$el.trigger("stopped."+this._name),null!=this.onunactive)try{return this.onunactive.call(this.$el)}catch(i){}},$.fn[h]=function(i){return this.each(function(){$.data(this,"kit-"+h)?"object"==typeof i?$.data(this,"kit-"+h)._setOptions(i):"string"==typeof i&&"_"!==i.charAt(0)?$.data(this,"kit-"+h)[i]:console.error("Maxmertkit Affix. You passed into the "+h+" something wrong."):$.data(this,"kit-"+h,new t(this,i))})}}.call(this),function(){var t,i,e,n,o,s,r,a,h={}.hasOwnProperty,c=function(t,i){function e(){this.constructor=t}for(var n in i)h.call(i,n)&&(t[n]=i[n]);return e.prototype=i.prototype,t.prototype=new e,t.__super__=i.prototype,t};a="tabs",r=[],s=0,t=function(t){function i(t,e){var n;this.tab=t,this.options=e,this.$tab=$(this.tab),this._id=s++,n={toggle:this.$tab.data("toggle")||"tabs",group:this.$tab.data("group")||null,target:this.$tab.data("target")||null,event:"click",active:0,beforeactive:function(){},onactive:function(){},beforeunactive:function(){},onunactive:function(){}},this.options=this._merge(n,this.options),this.beforeactive=this.options.beforeactive,this.onactive=this.options.onactive,this.beforeunactive=this.options.beforeunactive,this.onunactive=this.options.onunactive,this.$tab.on(this.options.event,function(t){return function(){return t.$tab.hasClass("_active_")?void 0:t.activate()}}(this)),this.$content=$(document).find(this.options.target),this.$content.hide(),i.__super__.constructor.call(this,this.$tab,this.options)}return c(i,t),i.prototype._name=a,i.prototype._instances=r,i.prototype._setOptions=function(t){var i,e;for(i in t){if(e=t[i],null==this.options[i])return i!=="kit-"+a?console.error("Maxmertkit Tabs. You're trying to set unpropriate option."):null;switch(i){case"event":this.$tab.off(""+this.options.event+"."+this._name),this.options.event=e,this.$tab.on(""+this.options.event+"."+this._name,function(t){return function(){return t.$tab.hasClass("_active_")?t.deactivate():t.activate()}}(this));break;case"target":this.options.target=e,this.$content=$(document).find(this.options.target);break;default:this.options[i]=e,"function"==typeof e&&(this[i]=this.options[i])}}},i.prototype._afterConstruct=function(){var t;for(t=0;t<this._instances&&this._instances[t].group!==this.options.group;)t++;return this._instances[t].activate()},i.prototype.destroy=function(){return this.$tab.off("."+this._name),i.__super__.destroy.apply(this,arguments)},i.prototype.activate=function(){return e.call(this)},i.prototype.deactivate=function(){return this.$tab.hasClass("_active_")?n.call(this):void 0},i.prototype.disable=function(){return this.$tab.toggleClass("_disabled_")},i}(MaxmertkitHelpers),e=function(){var t;if(this.options.selfish&&this._selfish(),null==this.beforeactive)return i.call(this);try{return t=this.beforeactive.call(this.$tab),t.done(function(t){return function(){return i.call(t)}}(this)).fail(function(t){return function(){return t.$tab.trigger("fail."+t._name)}}(this))}catch(e){return i.call(this)}},i=function(){var t,i,e,n;for(n=this._instances,i=0,e=n.length;e>i;i++)t=n[i],this._id!==t._id&&t.options.group===this.options.group&&t.deactivate();if(this.$tab.addClass("_active_"),this.$tab.trigger("activated."+this._name),this.$content.show(),null!=this.onactive)try{return this.onactive.call(this.$tab)}catch(o){}},n=function(){var t;if(null==this.beforeunactive)return o.call(this);try{return t=this.beforeunactive.call(this.$tab),t.done(function(t){return function(){return o.call(t)}}(this)).fail(function(t){return function(){return t.$tab.trigger("fail."+t._name)}}(this))}catch(i){return o.call(this)}},o=function(){if(this.$tab.removeClass("_active_"),this.$tab.trigger("deactivated."+this._name),this.$content.hide(),null!=this.onunactive)try{return this.onunactive.call(this.$tab)}catch(t){}},$.fn[a]=function(i){return this.each(function(){$.data(this,"kit-"+a)?"object"==typeof i?$.data(this,"kit-"+a)._setOptions(i):"string"==typeof i&&"_"!==i.charAt(0)?$.data(this,"kit-"+a)[i]:console.error("Maxmertkit Tabs. You passed into the "+a+" something wrong."):$.data(this,"kit-"+a,new t(this,i))})}}.call(this),function(){"use strict";var t,i,e,n,o,s,r,a,h,c={}.hasOwnProperty,l=function(t,i){function e(){this.constructor=t}for(var n in i)c.call(i,n)&&(t[n]=i[n]);return e.prototype=i.prototype,t.prototype=new e,t.__super__=i.prototype,t};r="popup",s=[],o=0,t=function(t){function n(t,i){var e;this.btn=t,this.options=i,this.$btn=$(this.btn),this._id=o++,e={target:this.$btn.data("target"),toggle:this.$btn.data("toggle")||"popup",event:"click",eventClose:"click",positionVertical:"top",positionHorizontal:"center",offset:{horizontal:5,vertical:5},closeUnfocus:!1,closeResize:!0,selfish:!0},this.options=this._merge(e,this.options),this.beforeopen=this.options.beforeopen,this.onopen=this.options.onopen,this.beforeclose=this.options.beforeclose,this.onclose=this.options.onclose,this.$el=$(document).find(this.options.target),this.$btn.on(this.options.event,function(t){return function(){return t.$el.is(":visible")?t.close():t.open()}}(this)),this.$btn.on(this.options.eventClose,function(t){return function(){return t.options.event!==t.options.eventClose?t.close():void 0}}(this)),this.$el.find("*[data-dismiss='popup']").on(this.options.event,function(t){return function(){return t.close()}}(this)),this.options.closeUnfocus&&$(document).on("click."+r,function(t){return function(i){var e;return e="."+t.$el[0].className.split(" ").join("."),$(i.target).closest(e).length||!t.$el.is(":visible")||t.$el.is(":animated")||$(i.target)[0]===t.$btn[0]?void 0:t.close()}}(this)),this.options.closeResize&&$(window).on("resize."+r,function(t){return function(){return t.close()}}(this)),this.$el.removeClass("_top_ _bottom_ _left_ _right_"),this.$el.addClass("_"+this.options.positionVertical+"_ _"+this.options.positionHorizontal+"_"),n.__super__.constructor.call(this,this.$btn,this.options),setTimeout(function(t){return function(){return t.reactor.addEventListener("close.modal",function(){return t.close()})}}(this),1)}return l(n,t),n.prototype._name=r,n.prototype._instances=s,n.prototype._setOptions=function(t){var i,e;for(i in t){if(e=t[i],null==this.options[i])return i!=="kit-"+r?console.error("Maxmertkit Popup. You're trying to set unpropriate option – "+i):null;switch(i){case"target":this.$el=$(document).find(this.options.target),this.$el.find("*[data-dismiss='popup']").on(this.options.event,function(t){return function(){return t.close()}}(this));break;case"event":this.$btn.off(""+this.options.event+"."+this._name),this.options.event=e,this.$btn.on(""+this.options.event+"."+this._name,function(t){return function(){return t.$el.is(":visible")?t.close():t.open()}}(this));break;case"eventClose":this.$btn.off(""+this.options.eventClose+"."+this._name),this.options.eventClose=e,this.$btn.on(""+this.options.eventClose+"."+this._name,function(t){return function(){return t.options.event!==t.options.eventClose?t.close():void 0}}(this));break;case"closeUnfocus":this.options.closeUnfocus=e,$(document).off("click."+this._name),this.options.closeUnfocus&&$(document).on("click."+this._name,function(t){return function(i){var e;return e="."+t.$el[0].className.split(" ").join("."),$(i.target).closest(e).length||!t.$el.is(":visible")||t.$el.is(":animated")||$(i.target)[0]===t.$btn[0]?void 0:t.close()}}(this));break;case"positionVertical":this.$el.removeClass("_top_ _middle_ _bottom_"),this.options.positionVertical=e,this.$el.addClass("_"+this.options.positionVertical+"_");break;case"positionHorizontal":this.$el.removeClass("_left_ _center_ _right_"),this.options.positionHorizontal=e,this.$el.addClass("_"+this.options.positionHorizontal+"_");break;default:this.options[i]=e}}},n.prototype.destroy=function(){return this.$btn.off("."+this._name),n.__super__.destroy.apply(this,arguments)},n.prototype.open=function(){return e.call(this)},n.prototype.close=function(){return i.call(this)},n}(MaxmertkitHelpers),h=function(){var t,i,e,n,o,s,r,a,h;switch(s=this._getContainer(this.$el),r=this._getContainer(this.$btn),o=this.$btn.offset(),n=this.$el.offset(),null!=s&&(null==s[0]||null!=s[0].activeElement&&"BODY"!==s[0].activeElement.nodeName||null!=s[0].nodeName&&"BODY"!==s[0].nodeName)&&(e=$(s).offset(),null!=e&&(o.top=o.top-e.top,o.left=o.left-e.left)),h={width:this.$btn.outerWidth(),height:this.$btn.outerHeight()},a={width:this.$el.outerWidth(),height:this.$el.outerHeight()},i=t=0,this.options.positionVertical){case"top":i=o.top-a.height-this.options.offset.vertical;break;case"bottom":i=o.top+h.height+this.options.offset.vertical;break;case"middle":i=o.top+h.height/2-a.height/2}switch(this.options.positionHorizontal){case"center":t=o.left+h.width/2-a.width/2;break;case"left":t=o.left-a.width-this.options.offset.horizontal;break;case"right":t=o.left+h.width+this.options.offset.horizontal}return this.$el.css({left:t,top:i})},e=function(){var t;if(this.options.selfish&&this._selfish(),null==this.beforeopen)return a.call(this);try{return t=this.beforeopen.call(this.$btn),t.done(function(t){return function(){return a.call(t)}}(this)).fail(function(t){return function(){return t.$el.trigger("fail."+t._name)}}(this))}catch(i){return a.call(this)}},a=function(){if(h.call(this),this.$el.addClass("_active_"),this.$el.trigger("opened."+this._name),null!=this.onopen)try{return this.onopen.call(this.$btn)}catch(t){}},i=function(){var t;if(null==this.beforeclose)return n.call(this);try{return t=this.beforeclose.call(this.$btn),t.done(function(t){return function(){return n.call(t)}}(this)).fail(function(t){return function(){return t.$el.trigger("fail."+t._name)}}(this))}catch(i){return n.call(this)}},n=function(){if(this.$el.removeClass("_active_"),this.$el.trigger("closed."+this._name),null!=this.onclose)try{return this.onclose.call(this.$btn)}catch(t){}},$.fn[r]=function(i){return this.each(function(){$.data(this,"kit-"+r)?"object"==typeof i?$.data(this,"kit-"+r)._setOptions(i):"string"==typeof i&&"_"!==i.charAt(0)?$.data(this,"kit-"+r)[i]:console.error("Maxmertkit Popup. You passed into the "+r+" something wrong."):$.data(this,"kit-"+r,new t(this,i))})}}.call(this);
src/svg-icons/navigation/chevron-left.js
kittyjumbalaya/material-components-web
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let NavigationChevronLeft = (props) => ( <SvgIcon {...props}> <path d="M15.41 7.41L14 6l-6 6 6 6 1.41-1.41L10.83 12z"/> </SvgIcon> ); NavigationChevronLeft = pure(NavigationChevronLeft); NavigationChevronLeft.displayName = 'NavigationChevronLeft'; NavigationChevronLeft.muiName = 'SvgIcon'; export default NavigationChevronLeft;
src/index.js
IbrahimCode/ReactReduxRouterStarter
import React from 'react' import ReactDOM from 'react-dom' import { Provider } from 'react-redux' import { ConnectedRouter } from 'react-router-redux' import createHistory from 'history/createBrowserHistory' import App from './containers/App' import registerServiceWorker from './registerServiceWorker' // Style import './index.css' // import * as BooksActionCreators from './containers/Books/actions' import configureStore from './store' const history = createHistory() const store = configureStore(window.INITIAL_STATE, history) ReactDOM.render( <Provider store={store}> <ConnectedRouter history={history}> <App /> </ConnectedRouter> </Provider>, document.getElementById('root') ) registerServiceWorker()
public/vendor/jquery-1.9.1.min.js
lvivdev/RubySchool_Less_23
/*! jQuery v1.9.1 | (c) 2005, 2012 jQuery Foundation, Inc. | jquery.org/license //@ sourceMappingURL=jquery.min.map */(function(e,t){var n,r,i=typeof t,o=e.document,a=e.location,s=e.jQuery,u=e.$,l={},c=[],p="1.9.1",f=c.concat,d=c.push,h=c.slice,g=c.indexOf,m=l.toString,y=l.hasOwnProperty,v=p.trim,b=function(e,t){return new b.fn.init(e,t,r)},x=/[+-]?(?:\d*\.|)\d+(?:[eE][+-]?\d+|)/.source,w=/\S+/g,T=/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,N=/^(?:(<[\w\W]+>)[^>]*|#([\w-]*))$/,C=/^<(\w+)\s*\/?>(?:<\/\1>|)$/,k=/^[\],:{}\s]*$/,E=/(?:^|:|,)(?:\s*\[)+/g,S=/\\(?:["\\\/bfnrt]|u[\da-fA-F]{4})/g,A=/"[^"\\\r\n]*"|true|false|null|-?(?:\d+\.|)\d+(?:[eE][+-]?\d+|)/g,j=/^-ms-/,D=/-([\da-z])/gi,L=function(e,t){return t.toUpperCase()},H=function(e){(o.addEventListener||"load"===e.type||"complete"===o.readyState)&&(q(),b.ready())},q=function(){o.addEventListener?(o.removeEventListener("DOMContentLoaded",H,!1),e.removeEventListener("load",H,!1)):(o.detachEvent("onreadystatechange",H),e.detachEvent("onload",H))};b.fn=b.prototype={jquery:p,constructor:b,init:function(e,n,r){var i,a;if(!e)return this;if("string"==typeof e){if(i="<"===e.charAt(0)&&">"===e.charAt(e.length-1)&&e.length>=3?[null,e,null]:N.exec(e),!i||!i[1]&&n)return!n||n.jquery?(n||r).find(e):this.constructor(n).find(e);if(i[1]){if(n=n instanceof b?n[0]:n,b.merge(this,b.parseHTML(i[1],n&&n.nodeType?n.ownerDocument||n:o,!0)),C.test(i[1])&&b.isPlainObject(n))for(i in n)b.isFunction(this[i])?this[i](n[i]):this.attr(i,n[i]);return this}if(a=o.getElementById(i[2]),a&&a.parentNode){if(a.id!==i[2])return r.find(e);this.length=1,this[0]=a}return this.context=o,this.selector=e,this}return e.nodeType?(this.context=this[0]=e,this.length=1,this):b.isFunction(e)?r.ready(e):(e.selector!==t&&(this.selector=e.selector,this.context=e.context),b.makeArray(e,this))},selector:"",length:0,size:function(){return this.length},toArray:function(){return h.call(this)},get:function(e){return null==e?this.toArray():0>e?this[this.length+e]:this[e]},pushStack:function(e){var t=b.merge(this.constructor(),e);return t.prevObject=this,t.context=this.context,t},each:function(e,t){return b.each(this,e,t)},ready:function(e){return b.ready.promise().done(e),this},slice:function(){return this.pushStack(h.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]]:[])},map:function(e){return this.pushStack(b.map(this,function(t,n){return e.call(t,n,t)}))},end:function(){return this.prevObject||this.constructor(null)},push:d,sort:[].sort,splice:[].splice},b.fn.init.prototype=b.fn,b.extend=b.fn.extend=function(){var e,n,r,i,o,a,s=arguments[0]||{},u=1,l=arguments.length,c=!1;for("boolean"==typeof s&&(c=s,s=arguments[1]||{},u=2),"object"==typeof s||b.isFunction(s)||(s={}),l===u&&(s=this,--u);l>u;u++)if(null!=(o=arguments[u]))for(i in o)e=s[i],r=o[i],s!==r&&(c&&r&&(b.isPlainObject(r)||(n=b.isArray(r)))?(n?(n=!1,a=e&&b.isArray(e)?e:[]):a=e&&b.isPlainObject(e)?e:{},s[i]=b.extend(c,a,r)):r!==t&&(s[i]=r));return s},b.extend({noConflict:function(t){return e.$===b&&(e.$=u),t&&e.jQuery===b&&(e.jQuery=s),b},isReady:!1,readyWait:1,holdReady:function(e){e?b.readyWait++:b.ready(!0)},ready:function(e){if(e===!0?!--b.readyWait:!b.isReady){if(!o.body)return setTimeout(b.ready);b.isReady=!0,e!==!0&&--b.readyWait>0||(n.resolveWith(o,[b]),b.fn.trigger&&b(o).trigger("ready").off("ready"))}},isFunction:function(e){return"function"===b.type(e)},isArray:Array.isArray||function(e){return"array"===b.type(e)},isWindow:function(e){return null!=e&&e==e.window},isNumeric:function(e){return!isNaN(parseFloat(e))&&isFinite(e)},type:function(e){return null==e?e+"":"object"==typeof e||"function"==typeof e?l[m.call(e)]||"object":typeof e},isPlainObject:function(e){if(!e||"object"!==b.type(e)||e.nodeType||b.isWindow(e))return!1;try{if(e.constructor&&!y.call(e,"constructor")&&!y.call(e.constructor.prototype,"isPrototypeOf"))return!1}catch(n){return!1}var r;for(r in e);return r===t||y.call(e,r)},isEmptyObject:function(e){var t;for(t in e)return!1;return!0},error:function(e){throw Error(e)},parseHTML:function(e,t,n){if(!e||"string"!=typeof e)return null;"boolean"==typeof t&&(n=t,t=!1),t=t||o;var r=C.exec(e),i=!n&&[];return r?[t.createElement(r[1])]:(r=b.buildFragment([e],t,i),i&&b(i).remove(),b.merge([],r.childNodes))},parseJSON:function(n){return e.JSON&&e.JSON.parse?e.JSON.parse(n):null===n?n:"string"==typeof n&&(n=b.trim(n),n&&k.test(n.replace(S,"@").replace(A,"]").replace(E,"")))?Function("return "+n)():(b.error("Invalid JSON: "+n),t)},parseXML:function(n){var r,i;if(!n||"string"!=typeof n)return null;try{e.DOMParser?(i=new DOMParser,r=i.parseFromString(n,"text/xml")):(r=new ActiveXObject("Microsoft.XMLDOM"),r.async="false",r.loadXML(n))}catch(o){r=t}return r&&r.documentElement&&!r.getElementsByTagName("parsererror").length||b.error("Invalid XML: "+n),r},noop:function(){},globalEval:function(t){t&&b.trim(t)&&(e.execScript||function(t){e.eval.call(e,t)})(t)},camelCase:function(e){return e.replace(j,"ms-").replace(D,L)},nodeName:function(e,t){return e.nodeName&&e.nodeName.toLowerCase()===t.toLowerCase()},each:function(e,t,n){var r,i=0,o=e.length,a=M(e);if(n){if(a){for(;o>i;i++)if(r=t.apply(e[i],n),r===!1)break}else for(i in e)if(r=t.apply(e[i],n),r===!1)break}else if(a){for(;o>i;i++)if(r=t.call(e[i],i,e[i]),r===!1)break}else for(i in e)if(r=t.call(e[i],i,e[i]),r===!1)break;return e},trim:v&&!v.call("\ufeff\u00a0")?function(e){return null==e?"":v.call(e)}:function(e){return null==e?"":(e+"").replace(T,"")},makeArray:function(e,t){var n=t||[];return null!=e&&(M(Object(e))?b.merge(n,"string"==typeof e?[e]:e):d.call(n,e)),n},inArray:function(e,t,n){var r;if(t){if(g)return g.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,n){var r=n.length,i=e.length,o=0;if("number"==typeof r)for(;r>o;o++)e[i++]=n[o];else while(n[o]!==t)e[i++]=n[o++];return e.length=i,e},grep:function(e,t,n){var r,i=[],o=0,a=e.length;for(n=!!n;a>o;o++)r=!!t(e[o],o),n!==r&&i.push(e[o]);return i},map:function(e,t,n){var r,i=0,o=e.length,a=M(e),s=[];if(a)for(;o>i;i++)r=t(e[i],i,n),null!=r&&(s[s.length]=r);else for(i in e)r=t(e[i],i,n),null!=r&&(s[s.length]=r);return f.apply([],s)},guid:1,proxy:function(e,n){var r,i,o;return"string"==typeof n&&(o=e[n],n=e,e=o),b.isFunction(e)?(r=h.call(arguments,2),i=function(){return e.apply(n||this,r.concat(h.call(arguments)))},i.guid=e.guid=e.guid||b.guid++,i):t},access:function(e,n,r,i,o,a,s){var u=0,l=e.length,c=null==r;if("object"===b.type(r)){o=!0;for(u in r)b.access(e,n,u,r[u],!0,a,s)}else if(i!==t&&(o=!0,b.isFunction(i)||(s=!0),c&&(s?(n.call(e,i),n=null):(c=n,n=function(e,t,n){return c.call(b(e),n)})),n))for(;l>u;u++)n(e[u],r,s?i:i.call(e[u],u,n(e[u],r)));return o?e:c?n.call(e):l?n(e[0],r):a},now:function(){return(new Date).getTime()}}),b.ready.promise=function(t){if(!n)if(n=b.Deferred(),"complete"===o.readyState)setTimeout(b.ready);else if(o.addEventListener)o.addEventListener("DOMContentLoaded",H,!1),e.addEventListener("load",H,!1);else{o.attachEvent("onreadystatechange",H),e.attachEvent("onload",H);var r=!1;try{r=null==e.frameElement&&o.documentElement}catch(i){}r&&r.doScroll&&function a(){if(!b.isReady){try{r.doScroll("left")}catch(e){return setTimeout(a,50)}q(),b.ready()}}()}return n.promise(t)},b.each("Boolean Number String Function Array Date RegExp Object Error".split(" "),function(e,t){l["[object "+t+"]"]=t.toLowerCase()});function M(e){var t=e.length,n=b.type(e);return b.isWindow(e)?!1:1===e.nodeType&&t?!0:"array"===n||"function"!==n&&(0===t||"number"==typeof t&&t>0&&t-1 in e)}r=b(o);var _={};function F(e){var t=_[e]={};return b.each(e.match(w)||[],function(e,n){t[n]=!0}),t}b.Callbacks=function(e){e="string"==typeof e?_[e]||F(e):b.extend({},e);var n,r,i,o,a,s,u=[],l=!e.once&&[],c=function(t){for(r=e.memory&&t,i=!0,a=s||0,s=0,o=u.length,n=!0;u&&o>a;a++)if(u[a].apply(t[0],t[1])===!1&&e.stopOnFalse){r=!1;break}n=!1,u&&(l?l.length&&c(l.shift()):r?u=[]:p.disable())},p={add:function(){if(u){var t=u.length;(function i(t){b.each(t,function(t,n){var r=b.type(n);"function"===r?e.unique&&p.has(n)||u.push(n):n&&n.length&&"string"!==r&&i(n)})})(arguments),n?o=u.length:r&&(s=t,c(r))}return this},remove:function(){return u&&b.each(arguments,function(e,t){var r;while((r=b.inArray(t,u,r))>-1)u.splice(r,1),n&&(o>=r&&o--,a>=r&&a--)}),this},has:function(e){return e?b.inArray(e,u)>-1:!(!u||!u.length)},empty:function(){return u=[],this},disable:function(){return u=l=r=t,this},disabled:function(){return!u},lock:function(){return l=t,r||p.disable(),this},locked:function(){return!l},fireWith:function(e,t){return t=t||[],t=[e,t.slice?t.slice():t],!u||i&&!l||(n?l.push(t):c(t)),this},fire:function(){return p.fireWith(this,arguments),this},fired:function(){return!!i}};return p},b.extend({Deferred:function(e){var t=[["resolve","done",b.Callbacks("once memory"),"resolved"],["reject","fail",b.Callbacks("once memory"),"rejected"],["notify","progress",b.Callbacks("memory")]],n="pending",r={state:function(){return n},always:function(){return i.done(arguments).fail(arguments),this},then:function(){var e=arguments;return b.Deferred(function(n){b.each(t,function(t,o){var a=o[0],s=b.isFunction(e[t])&&e[t];i[o[1]](function(){var e=s&&s.apply(this,arguments);e&&b.isFunction(e.promise)?e.promise().done(n.resolve).fail(n.reject).progress(n.notify):n[a+"With"](this===r?n.promise():this,s?[e]:arguments)})}),e=null}).promise()},promise:function(e){return null!=e?b.extend(e,r):r}},i={};return r.pipe=r.then,b.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=0,n=h.call(arguments),r=n.length,i=1!==r||e&&b.isFunction(e.promise)?r:0,o=1===i?e:b.Deferred(),a=function(e,t,n){return function(r){t[e]=this,n[e]=arguments.length>1?h.call(arguments):r,n===s?o.notifyWith(t,n):--i||o.resolveWith(t,n)}},s,u,l;if(r>1)for(s=Array(r),u=Array(r),l=Array(r);r>t;t++)n[t]&&b.isFunction(n[t].promise)?n[t].promise().done(a(t,l,n)).fail(o.reject).progress(a(t,u,s)):--i;return i||o.resolveWith(l,n),o.promise()}}),b.support=function(){var t,n,r,a,s,u,l,c,p,f,d=o.createElement("div");if(d.setAttribute("className","t"),d.innerHTML=" <link/><table></table><a href='/a'>a</a><input type='checkbox'/>",n=d.getElementsByTagName("*"),r=d.getElementsByTagName("a")[0],!n||!r||!n.length)return{};s=o.createElement("select"),l=s.appendChild(o.createElement("option")),a=d.getElementsByTagName("input")[0],r.style.cssText="top:1px;float:left;opacity:.5",t={getSetAttribute:"t"!==d.className,leadingWhitespace:3===d.firstChild.nodeType,tbody:!d.getElementsByTagName("tbody").length,htmlSerialize:!!d.getElementsByTagName("link").length,style:/top/.test(r.getAttribute("style")),hrefNormalized:"/a"===r.getAttribute("href"),opacity:/^0.5/.test(r.style.opacity),cssFloat:!!r.style.cssFloat,checkOn:!!a.value,optSelected:l.selected,enctype:!!o.createElement("form").enctype,html5Clone:"<:nav></:nav>"!==o.createElement("nav").cloneNode(!0).outerHTML,boxModel:"CSS1Compat"===o.compatMode,deleteExpando:!0,noCloneEvent:!0,inlineBlockNeedsLayout:!1,shrinkWrapBlocks:!1,reliableMarginRight:!0,boxSizingReliable:!0,pixelPosition:!1},a.checked=!0,t.noCloneChecked=a.cloneNode(!0).checked,s.disabled=!0,t.optDisabled=!l.disabled;try{delete d.test}catch(h){t.deleteExpando=!1}a=o.createElement("input"),a.setAttribute("value",""),t.input=""===a.getAttribute("value"),a.value="t",a.setAttribute("type","radio"),t.radioValue="t"===a.value,a.setAttribute("checked","t"),a.setAttribute("name","t"),u=o.createDocumentFragment(),u.appendChild(a),t.appendChecked=a.checked,t.checkClone=u.cloneNode(!0).cloneNode(!0).lastChild.checked,d.attachEvent&&(d.attachEvent("onclick",function(){t.noCloneEvent=!1}),d.cloneNode(!0).click());for(f in{submit:!0,change:!0,focusin:!0})d.setAttribute(c="on"+f,"t"),t[f+"Bubbles"]=c in e||d.attributes[c].expando===!1;return d.style.backgroundClip="content-box",d.cloneNode(!0).style.backgroundClip="",t.clearCloneStyle="content-box"===d.style.backgroundClip,b(function(){var n,r,a,s="padding:0;margin:0;border:0;display:block;box-sizing:content-box;-moz-box-sizing:content-box;-webkit-box-sizing:content-box;",u=o.getElementsByTagName("body")[0];u&&(n=o.createElement("div"),n.style.cssText="border:0;width:0;height:0;position:absolute;top:0;left:-9999px;margin-top:1px",u.appendChild(n).appendChild(d),d.innerHTML="<table><tr><td></td><td>t</td></tr></table>",a=d.getElementsByTagName("td"),a[0].style.cssText="padding:0;margin:0;border:0;display:none",p=0===a[0].offsetHeight,a[0].style.display="",a[1].style.display="none",t.reliableHiddenOffsets=p&&0===a[0].offsetHeight,d.innerHTML="",d.style.cssText="box-sizing:border-box;-moz-box-sizing:border-box;-webkit-box-sizing:border-box;padding:1px;border:1px;display:block;width:4px;margin-top:1%;position:absolute;top:1%;",t.boxSizing=4===d.offsetWidth,t.doesNotIncludeMarginInBodyOffset=1!==u.offsetTop,e.getComputedStyle&&(t.pixelPosition="1%"!==(e.getComputedStyle(d,null)||{}).top,t.boxSizingReliable="4px"===(e.getComputedStyle(d,null)||{width:"4px"}).width,r=d.appendChild(o.createElement("div")),r.style.cssText=d.style.cssText=s,r.style.marginRight=r.style.width="0",d.style.width="1px",t.reliableMarginRight=!parseFloat((e.getComputedStyle(r,null)||{}).marginRight)),typeof d.style.zoom!==i&&(d.innerHTML="",d.style.cssText=s+"width:1px;padding:1px;display:inline;zoom:1",t.inlineBlockNeedsLayout=3===d.offsetWidth,d.style.display="block",d.innerHTML="<div></div>",d.firstChild.style.width="5px",t.shrinkWrapBlocks=3!==d.offsetWidth,t.inlineBlockNeedsLayout&&(u.style.zoom=1)),u.removeChild(n),n=d=a=r=null)}),n=s=u=l=r=a=null,t}();var O=/(?:\{[\s\S]*\}|\[[\s\S]*\])$/,B=/([A-Z])/g;function P(e,n,r,i){if(b.acceptData(e)){var o,a,s=b.expando,u="string"==typeof n,l=e.nodeType,p=l?b.cache:e,f=l?e[s]:e[s]&&s;if(f&&p[f]&&(i||p[f].data)||!u||r!==t)return f||(l?e[s]=f=c.pop()||b.guid++:f=s),p[f]||(p[f]={},l||(p[f].toJSON=b.noop)),("object"==typeof n||"function"==typeof n)&&(i?p[f]=b.extend(p[f],n):p[f].data=b.extend(p[f].data,n)),o=p[f],i||(o.data||(o.data={}),o=o.data),r!==t&&(o[b.camelCase(n)]=r),u?(a=o[n],null==a&&(a=o[b.camelCase(n)])):a=o,a}}function R(e,t,n){if(b.acceptData(e)){var r,i,o,a=e.nodeType,s=a?b.cache:e,u=a?e[b.expando]:b.expando;if(s[u]){if(t&&(o=n?s[u]:s[u].data)){b.isArray(t)?t=t.concat(b.map(t,b.camelCase)):t in o?t=[t]:(t=b.camelCase(t),t=t in o?[t]:t.split(" "));for(r=0,i=t.length;i>r;r++)delete o[t[r]];if(!(n?$:b.isEmptyObject)(o))return}(n||(delete s[u].data,$(s[u])))&&(a?b.cleanData([e],!0):b.support.deleteExpando||s!=s.window?delete s[u]:s[u]=null)}}}b.extend({cache:{},expando:"jQuery"+(p+Math.random()).replace(/\D/g,""),noData:{embed:!0,object:"clsid:D27CDB6E-AE6D-11cf-96B8-444553540000",applet:!0},hasData:function(e){return e=e.nodeType?b.cache[e[b.expando]]:e[b.expando],!!e&&!$(e)},data:function(e,t,n){return P(e,t,n)},removeData:function(e,t){return R(e,t)},_data:function(e,t,n){return P(e,t,n,!0)},_removeData:function(e,t){return R(e,t,!0)},acceptData:function(e){if(e.nodeType&&1!==e.nodeType&&9!==e.nodeType)return!1;var t=e.nodeName&&b.noData[e.nodeName.toLowerCase()];return!t||t!==!0&&e.getAttribute("classid")===t}}),b.fn.extend({data:function(e,n){var r,i,o=this[0],a=0,s=null;if(e===t){if(this.length&&(s=b.data(o),1===o.nodeType&&!b._data(o,"parsedAttrs"))){for(r=o.attributes;r.length>a;a++)i=r[a].name,i.indexOf("data-")||(i=b.camelCase(i.slice(5)),W(o,i,s[i]));b._data(o,"parsedAttrs",!0)}return s}return"object"==typeof e?this.each(function(){b.data(this,e)}):b.access(this,function(n){return n===t?o?W(o,e,b.data(o,e)):null:(this.each(function(){b.data(this,e,n)}),t)},null,n,arguments.length>1,null,!0)},removeData:function(e){return this.each(function(){b.removeData(this,e)})}});function W(e,n,r){if(r===t&&1===e.nodeType){var i="data-"+n.replace(B,"-$1").toLowerCase();if(r=e.getAttribute(i),"string"==typeof r){try{r="true"===r?!0:"false"===r?!1:"null"===r?null:+r+""===r?+r:O.test(r)?b.parseJSON(r):r}catch(o){}b.data(e,n,r)}else r=t}return r}function $(e){var t;for(t in e)if(("data"!==t||!b.isEmptyObject(e[t]))&&"toJSON"!==t)return!1;return!0}b.extend({queue:function(e,n,r){var i;return e?(n=(n||"fx")+"queue",i=b._data(e,n),r&&(!i||b.isArray(r)?i=b._data(e,n,b.makeArray(r)):i.push(r)),i||[]):t},dequeue:function(e,t){t=t||"fx";var n=b.queue(e,t),r=n.length,i=n.shift(),o=b._queueHooks(e,t),a=function(){b.dequeue(e,t)};"inprogress"===i&&(i=n.shift(),r--),o.cur=i,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 b._data(e,n)||b._data(e,n,{empty:b.Callbacks("once memory").add(function(){b._removeData(e,t+"queue"),b._removeData(e,n)})})}}),b.fn.extend({queue:function(e,n){var r=2;return"string"!=typeof e&&(n=e,e="fx",r--),r>arguments.length?b.queue(this[0],e):n===t?this:this.each(function(){var t=b.queue(this,e,n);b._queueHooks(this,e),"fx"===e&&"inprogress"!==t[0]&&b.dequeue(this,e)})},dequeue:function(e){return this.each(function(){b.dequeue(this,e)})},delay:function(e,t){return e=b.fx?b.fx.speeds[e]||e:e,t=t||"fx",this.queue(t,function(t,n){var r=setTimeout(t,e);n.stop=function(){clearTimeout(r)}})},clearQueue:function(e){return this.queue(e||"fx",[])},promise:function(e,n){var r,i=1,o=b.Deferred(),a=this,s=this.length,u=function(){--i||o.resolveWith(a,[a])};"string"!=typeof e&&(n=e,e=t),e=e||"fx";while(s--)r=b._data(a[s],e+"queueHooks"),r&&r.empty&&(i++,r.empty.add(u));return u(),o.promise(n)}});var I,z,X=/[\t\r\n]/g,U=/\r/g,V=/^(?:input|select|textarea|button|object)$/i,Y=/^(?:a|area)$/i,J=/^(?:checked|selected|autofocus|autoplay|async|controls|defer|disabled|hidden|loop|multiple|open|readonly|required|scoped)$/i,G=/^(?:checked|selected)$/i,Q=b.support.getSetAttribute,K=b.support.input;b.fn.extend({attr:function(e,t){return b.access(this,b.attr,e,t,arguments.length>1)},removeAttr:function(e){return this.each(function(){b.removeAttr(this,e)})},prop:function(e,t){return b.access(this,b.prop,e,t,arguments.length>1)},removeProp:function(e){return e=b.propFix[e]||e,this.each(function(){try{this[e]=t,delete this[e]}catch(n){}})},addClass:function(e){var t,n,r,i,o,a=0,s=this.length,u="string"==typeof e&&e;if(b.isFunction(e))return this.each(function(t){b(this).addClass(e.call(this,t,this.className))});if(u)for(t=(e||"").match(w)||[];s>a;a++)if(n=this[a],r=1===n.nodeType&&(n.className?(" "+n.className+" ").replace(X," "):" ")){o=0;while(i=t[o++])0>r.indexOf(" "+i+" ")&&(r+=i+" ");n.className=b.trim(r)}return this},removeClass:function(e){var t,n,r,i,o,a=0,s=this.length,u=0===arguments.length||"string"==typeof e&&e;if(b.isFunction(e))return this.each(function(t){b(this).removeClass(e.call(this,t,this.className))});if(u)for(t=(e||"").match(w)||[];s>a;a++)if(n=this[a],r=1===n.nodeType&&(n.className?(" "+n.className+" ").replace(X," "):"")){o=0;while(i=t[o++])while(r.indexOf(" "+i+" ")>=0)r=r.replace(" "+i+" "," ");n.className=e?b.trim(r):""}return this},toggleClass:function(e,t){var n=typeof e,r="boolean"==typeof t;return b.isFunction(e)?this.each(function(n){b(this).toggleClass(e.call(this,n,this.className,t),t)}):this.each(function(){if("string"===n){var o,a=0,s=b(this),u=t,l=e.match(w)||[];while(o=l[a++])u=r?u:!s.hasClass(o),s[u?"addClass":"removeClass"](o)}else(n===i||"boolean"===n)&&(this.className&&b._data(this,"__className__",this.className),this.className=this.className||e===!1?"":b._data(this,"__className__")||"")})},hasClass:function(e){var t=" "+e+" ",n=0,r=this.length;for(;r>n;n++)if(1===this[n].nodeType&&(" "+this[n].className+" ").replace(X," ").indexOf(t)>=0)return!0;return!1},val:function(e){var n,r,i,o=this[0];{if(arguments.length)return i=b.isFunction(e),this.each(function(n){var o,a=b(this);1===this.nodeType&&(o=i?e.call(this,n,a.val()):e,null==o?o="":"number"==typeof o?o+="":b.isArray(o)&&(o=b.map(o,function(e){return null==e?"":e+""})),r=b.valHooks[this.type]||b.valHooks[this.nodeName.toLowerCase()],r&&"set"in r&&r.set(this,o,"value")!==t||(this.value=o))});if(o)return r=b.valHooks[o.type]||b.valHooks[o.nodeName.toLowerCase()],r&&"get"in r&&(n=r.get(o,"value"))!==t?n:(n=o.value,"string"==typeof n?n.replace(U,""):null==n?"":n)}}}),b.extend({valHooks:{option:{get:function(e){var t=e.attributes.value;return!t||t.specified?e.value:e.text}},select:{get:function(e){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,u=0>i?s:o?i:0;for(;s>u;u++)if(n=r[u],!(!n.selected&&u!==i||(b.support.optDisabled?n.disabled:null!==n.getAttribute("disabled"))||n.parentNode.disabled&&b.nodeName(n.parentNode,"optgroup"))){if(t=b(n).val(),o)return t;a.push(t)}return a},set:function(e,t){var n=b.makeArray(t);return b(e).find("option").each(function(){this.selected=b.inArray(b(this).val(),n)>=0}),n.length||(e.selectedIndex=-1),n}}},attr:function(e,n,r){var o,a,s,u=e.nodeType;if(e&&3!==u&&8!==u&&2!==u)return typeof e.getAttribute===i?b.prop(e,n,r):(a=1!==u||!b.isXMLDoc(e),a&&(n=n.toLowerCase(),o=b.attrHooks[n]||(J.test(n)?z:I)),r===t?o&&a&&"get"in o&&null!==(s=o.get(e,n))?s:(typeof e.getAttribute!==i&&(s=e.getAttribute(n)),null==s?t:s):null!==r?o&&a&&"set"in o&&(s=o.set(e,r,n))!==t?s:(e.setAttribute(n,r+""),r):(b.removeAttr(e,n),t))},removeAttr:function(e,t){var n,r,i=0,o=t&&t.match(w);if(o&&1===e.nodeType)while(n=o[i++])r=b.propFix[n]||n,J.test(n)?!Q&&G.test(n)?e[b.camelCase("default-"+n)]=e[r]=!1:e[r]=!1:b.attr(e,n,""),e.removeAttribute(Q?n:r)},attrHooks:{type:{set:function(e,t){if(!b.support.radioValue&&"radio"===t&&b.nodeName(e,"input")){var n=e.value;return e.setAttribute("type",t),n&&(e.value=n),t}}}},propFix:{tabindex:"tabIndex",readonly:"readOnly","for":"htmlFor","class":"className",maxlength:"maxLength",cellspacing:"cellSpacing",cellpadding:"cellPadding",rowspan:"rowSpan",colspan:"colSpan",usemap:"useMap",frameborder:"frameBorder",contenteditable:"contentEditable"},prop:function(e,n,r){var i,o,a,s=e.nodeType;if(e&&3!==s&&8!==s&&2!==s)return a=1!==s||!b.isXMLDoc(e),a&&(n=b.propFix[n]||n,o=b.propHooks[n]),r!==t?o&&"set"in o&&(i=o.set(e,r,n))!==t?i:e[n]=r:o&&"get"in o&&null!==(i=o.get(e,n))?i:e[n]},propHooks:{tabIndex:{get:function(e){var n=e.getAttributeNode("tabindex");return n&&n.specified?parseInt(n.value,10):V.test(e.nodeName)||Y.test(e.nodeName)&&e.href?0:t}}}}),z={get:function(e,n){var r=b.prop(e,n),i="boolean"==typeof r&&e.getAttribute(n),o="boolean"==typeof r?K&&Q?null!=i:G.test(n)?e[b.camelCase("default-"+n)]:!!i:e.getAttributeNode(n);return o&&o.value!==!1?n.toLowerCase():t},set:function(e,t,n){return t===!1?b.removeAttr(e,n):K&&Q||!G.test(n)?e.setAttribute(!Q&&b.propFix[n]||n,n):e[b.camelCase("default-"+n)]=e[n]=!0,n}},K&&Q||(b.attrHooks.value={get:function(e,n){var r=e.getAttributeNode(n);return b.nodeName(e,"input")?e.defaultValue:r&&r.specified?r.value:t},set:function(e,n,r){return b.nodeName(e,"input")?(e.defaultValue=n,t):I&&I.set(e,n,r)}}),Q||(I=b.valHooks.button={get:function(e,n){var r=e.getAttributeNode(n);return r&&("id"===n||"name"===n||"coords"===n?""!==r.value:r.specified)?r.value:t},set:function(e,n,r){var i=e.getAttributeNode(r);return i||e.setAttributeNode(i=e.ownerDocument.createAttribute(r)),i.value=n+="","value"===r||n===e.getAttribute(r)?n:t}},b.attrHooks.contenteditable={get:I.get,set:function(e,t,n){I.set(e,""===t?!1:t,n)}},b.each(["width","height"],function(e,n){b.attrHooks[n]=b.extend(b.attrHooks[n],{set:function(e,r){return""===r?(e.setAttribute(n,"auto"),r):t}})})),b.support.hrefNormalized||(b.each(["href","src","width","height"],function(e,n){b.attrHooks[n]=b.extend(b.attrHooks[n],{get:function(e){var r=e.getAttribute(n,2);return null==r?t:r}})}),b.each(["href","src"],function(e,t){b.propHooks[t]={get:function(e){return e.getAttribute(t,4)}}})),b.support.style||(b.attrHooks.style={get:function(e){return e.style.cssText||t},set:function(e,t){return e.style.cssText=t+""}}),b.support.optSelected||(b.propHooks.selected=b.extend(b.propHooks.selected,{get:function(e){var t=e.parentNode;return t&&(t.selectedIndex,t.parentNode&&t.parentNode.selectedIndex),null}})),b.support.enctype||(b.propFix.enctype="encoding"),b.support.checkOn||b.each(["radio","checkbox"],function(){b.valHooks[this]={get:function(e){return null===e.getAttribute("value")?"on":e.value}}}),b.each(["radio","checkbox"],function(){b.valHooks[this]=b.extend(b.valHooks[this],{set:function(e,n){return b.isArray(n)?e.checked=b.inArray(b(e).val(),n)>=0:t}})});var Z=/^(?:input|select|textarea)$/i,et=/^key/,tt=/^(?:mouse|contextmenu)|click/,nt=/^(?:focusinfocus|focusoutblur)$/,rt=/^([^.]*)(?:\.(.+)|)$/;function it(){return!0}function ot(){return!1}b.event={global:{},add:function(e,n,r,o,a){var s,u,l,c,p,f,d,h,g,m,y,v=b._data(e);if(v){r.handler&&(c=r,r=c.handler,a=c.selector),r.guid||(r.guid=b.guid++),(u=v.events)||(u=v.events={}),(f=v.handle)||(f=v.handle=function(e){return typeof b===i||e&&b.event.triggered===e.type?t:b.event.dispatch.apply(f.elem,arguments)},f.elem=e),n=(n||"").match(w)||[""],l=n.length;while(l--)s=rt.exec(n[l])||[],g=y=s[1],m=(s[2]||"").split(".").sort(),p=b.event.special[g]||{},g=(a?p.delegateType:p.bindType)||g,p=b.event.special[g]||{},d=b.extend({type:g,origType:y,data:o,handler:r,guid:r.guid,selector:a,needsContext:a&&b.expr.match.needsContext.test(a),namespace:m.join(".")},c),(h=u[g])||(h=u[g]=[],h.delegateCount=0,p.setup&&p.setup.call(e,o,m,f)!==!1||(e.addEventListener?e.addEventListener(g,f,!1):e.attachEvent&&e.attachEvent("on"+g,f))),p.add&&(p.add.call(e,d),d.handler.guid||(d.handler.guid=r.guid)),a?h.splice(h.delegateCount++,0,d):h.push(d),b.event.global[g]=!0;e=null}},remove:function(e,t,n,r,i){var o,a,s,u,l,c,p,f,d,h,g,m=b.hasData(e)&&b._data(e);if(m&&(c=m.events)){t=(t||"").match(w)||[""],l=t.length;while(l--)if(s=rt.exec(t[l])||[],d=g=s[1],h=(s[2]||"").split(".").sort(),d){p=b.event.special[d]||{},d=(r?p.delegateType:p.bindType)||d,f=c[d]||[],s=s[2]&&RegExp("(^|\\.)"+h.join("\\.(?:.*\\.|)")+"(\\.|$)"),u=o=f.length;while(o--)a=f[o],!i&&g!==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--,p.remove&&p.remove.call(e,a));u&&!f.length&&(p.teardown&&p.teardown.call(e,h,m.handle)!==!1||b.removeEvent(e,d,m.handle),delete c[d])}else for(d in c)b.event.remove(e,d+t[l],n,r,!0);b.isEmptyObject(c)&&(delete m.handle,b._removeData(e,"events"))}},trigger:function(n,r,i,a){var s,u,l,c,p,f,d,h=[i||o],g=y.call(n,"type")?n.type:n,m=y.call(n,"namespace")?n.namespace.split("."):[];if(l=f=i=i||o,3!==i.nodeType&&8!==i.nodeType&&!nt.test(g+b.event.triggered)&&(g.indexOf(".")>=0&&(m=g.split("."),g=m.shift(),m.sort()),u=0>g.indexOf(":")&&"on"+g,n=n[b.expando]?n:new b.Event(g,"object"==typeof n&&n),n.isTrigger=!0,n.namespace=m.join("."),n.namespace_re=n.namespace?RegExp("(^|\\.)"+m.join("\\.(?:.*\\.|)")+"(\\.|$)"):null,n.result=t,n.target||(n.target=i),r=null==r?[n]:b.makeArray(r,[n]),p=b.event.special[g]||{},a||!p.trigger||p.trigger.apply(i,r)!==!1)){if(!a&&!p.noBubble&&!b.isWindow(i)){for(c=p.delegateType||g,nt.test(c+g)||(l=l.parentNode);l;l=l.parentNode)h.push(l),f=l;f===(i.ownerDocument||o)&&h.push(f.defaultView||f.parentWindow||e)}d=0;while((l=h[d++])&&!n.isPropagationStopped())n.type=d>1?c:p.bindType||g,s=(b._data(l,"events")||{})[n.type]&&b._data(l,"handle"),s&&s.apply(l,r),s=u&&l[u],s&&b.acceptData(l)&&s.apply&&s.apply(l,r)===!1&&n.preventDefault();if(n.type=g,!(a||n.isDefaultPrevented()||p._default&&p._default.apply(i.ownerDocument,r)!==!1||"click"===g&&b.nodeName(i,"a")||!b.acceptData(i)||!u||!i[g]||b.isWindow(i))){f=i[u],f&&(i[u]=null),b.event.triggered=g;try{i[g]()}catch(v){}b.event.triggered=t,f&&(i[u]=f)}return n.result}},dispatch:function(e){e=b.event.fix(e);var n,r,i,o,a,s=[],u=h.call(arguments),l=(b._data(this,"events")||{})[e.type]||[],c=b.event.special[e.type]||{};if(u[0]=e,e.delegateTarget=this,!c.preDispatch||c.preDispatch.call(this,e)!==!1){s=b.event.handlers.call(this,e,l),n=0;while((o=s[n++])&&!e.isPropagationStopped()){e.currentTarget=o.elem,a=0;while((i=o.handlers[a++])&&!e.isImmediatePropagationStopped())(!e.namespace_re||e.namespace_re.test(i.namespace))&&(e.handleObj=i,e.data=i.data,r=((b.event.special[i.origType]||{}).handle||i.handler).apply(o.elem,u),r!==t&&(e.result=r)===!1&&(e.preventDefault(),e.stopPropagation()))}return c.postDispatch&&c.postDispatch.call(this,e),e.result}},handlers:function(e,n){var r,i,o,a,s=[],u=n.delegateCount,l=e.target;if(u&&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(o=[],a=0;u>a;a++)i=n[a],r=i.selector+" ",o[r]===t&&(o[r]=i.needsContext?b(r,this).index(l)>=0:b.find(r,this,null,[l]).length),o[r]&&o.push(i);o.length&&s.push({elem:l,handlers:o})}return n.length>u&&s.push({elem:this,handlers:n.slice(u)}),s},fix:function(e){if(e[b.expando])return e;var t,n,r,i=e.type,a=e,s=this.fixHooks[i];s||(this.fixHooks[i]=s=tt.test(i)?this.mouseHooks:et.test(i)?this.keyHooks:{}),r=s.props?this.props.concat(s.props):this.props,e=new b.Event(a),t=r.length;while(t--)n=r[t],e[n]=a[n];return e.target||(e.target=a.srcElement||o),3===e.target.nodeType&&(e.target=e.target.parentNode),e.metaKey=!!e.metaKey,s.filter?s.filter(e,a):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,n){var r,i,a,s=n.button,u=n.fromElement;return null==e.pageX&&null!=n.clientX&&(i=e.target.ownerDocument||o,a=i.documentElement,r=i.body,e.pageX=n.clientX+(a&&a.scrollLeft||r&&r.scrollLeft||0)-(a&&a.clientLeft||r&&r.clientLeft||0),e.pageY=n.clientY+(a&&a.scrollTop||r&&r.scrollTop||0)-(a&&a.clientTop||r&&r.clientTop||0)),!e.relatedTarget&&u&&(e.relatedTarget=u===e.target?n.toElement:u),e.which||s===t||(e.which=1&s?1:2&s?3:4&s?2:0),e}},special:{load:{noBubble:!0},click:{trigger:function(){return b.nodeName(this,"input")&&"checkbox"===this.type&&this.click?(this.click(),!1):t}},focus:{trigger:function(){if(this!==o.activeElement&&this.focus)try{return this.focus(),!1}catch(e){}},delegateType:"focusin"},blur:{trigger:function(){return this===o.activeElement&&this.blur?(this.blur(),!1):t},delegateType:"focusout"},beforeunload:{postDispatch:function(e){e.result!==t&&(e.originalEvent.returnValue=e.result)}}},simulate:function(e,t,n,r){var i=b.extend(new b.Event,n,{type:e,isSimulated:!0,originalEvent:{}});r?b.event.trigger(i,null,t):b.event.dispatch.call(t,i),i.isDefaultPrevented()&&n.preventDefault()}},b.removeEvent=o.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]===i&&(e[r]=null),e.detachEvent(r,n))},b.Event=function(e,n){return this instanceof b.Event?(e&&e.type?(this.originalEvent=e,this.type=e.type,this.isDefaultPrevented=e.defaultPrevented||e.returnValue===!1||e.getPreventDefault&&e.getPreventDefault()?it:ot):this.type=e,n&&b.extend(this,n),this.timeStamp=e&&e.timeStamp||b.now(),this[b.expando]=!0,t):new b.Event(e,n)},b.Event.prototype={isDefaultPrevented:ot,isPropagationStopped:ot,isImmediatePropagationStopped:ot,preventDefault:function(){var e=this.originalEvent;this.isDefaultPrevented=it,e&&(e.preventDefault?e.preventDefault():e.returnValue=!1)},stopPropagation:function(){var e=this.originalEvent;this.isPropagationStopped=it,e&&(e.stopPropagation&&e.stopPropagation(),e.cancelBubble=!0)},stopImmediatePropagation:function(){this.isImmediatePropagationStopped=it,this.stopPropagation()}},b.each({mouseenter:"mouseover",mouseleave:"mouseout"},function(e,t){b.event.special[e]={delegateType:t,bindType:t,handle:function(e){var n,r=this,i=e.relatedTarget,o=e.handleObj; return(!i||i!==r&&!b.contains(r,i))&&(e.type=o.origType,n=o.handler.apply(this,arguments),e.type=t),n}}}),b.support.submitBubbles||(b.event.special.submit={setup:function(){return b.nodeName(this,"form")?!1:(b.event.add(this,"click._submit keypress._submit",function(e){var n=e.target,r=b.nodeName(n,"input")||b.nodeName(n,"button")?n.form:t;r&&!b._data(r,"submitBubbles")&&(b.event.add(r,"submit._submit",function(e){e._submit_bubble=!0}),b._data(r,"submitBubbles",!0))}),t)},postDispatch:function(e){e._submit_bubble&&(delete e._submit_bubble,this.parentNode&&!e.isTrigger&&b.event.simulate("submit",this.parentNode,e,!0))},teardown:function(){return b.nodeName(this,"form")?!1:(b.event.remove(this,"._submit"),t)}}),b.support.changeBubbles||(b.event.special.change={setup:function(){return Z.test(this.nodeName)?(("checkbox"===this.type||"radio"===this.type)&&(b.event.add(this,"propertychange._change",function(e){"checked"===e.originalEvent.propertyName&&(this._just_changed=!0)}),b.event.add(this,"click._change",function(e){this._just_changed&&!e.isTrigger&&(this._just_changed=!1),b.event.simulate("change",this,e,!0)})),!1):(b.event.add(this,"beforeactivate._change",function(e){var t=e.target;Z.test(t.nodeName)&&!b._data(t,"changeBubbles")&&(b.event.add(t,"change._change",function(e){!this.parentNode||e.isSimulated||e.isTrigger||b.event.simulate("change",this.parentNode,e,!0)}),b._data(t,"changeBubbles",!0))}),t)},handle:function(e){var n=e.target;return this!==n||e.isSimulated||e.isTrigger||"radio"!==n.type&&"checkbox"!==n.type?e.handleObj.handler.apply(this,arguments):t},teardown:function(){return b.event.remove(this,"._change"),!Z.test(this.nodeName)}}),b.support.focusinBubbles||b.each({focus:"focusin",blur:"focusout"},function(e,t){var n=0,r=function(e){b.event.simulate(t,e.target,b.event.fix(e),!0)};b.event.special[t]={setup:function(){0===n++&&o.addEventListener(e,r,!0)},teardown:function(){0===--n&&o.removeEventListener(e,r,!0)}}}),b.fn.extend({on:function(e,n,r,i,o){var a,s;if("object"==typeof e){"string"!=typeof n&&(r=r||n,n=t);for(a in e)this.on(a,n,r,e[a],o);return this}if(null==r&&null==i?(i=n,r=n=t):null==i&&("string"==typeof n?(i=r,r=t):(i=r,r=n,n=t)),i===!1)i=ot;else if(!i)return this;return 1===o&&(s=i,i=function(e){return b().off(e),s.apply(this,arguments)},i.guid=s.guid||(s.guid=b.guid++)),this.each(function(){b.event.add(this,e,i,r,n)})},one:function(e,t,n,r){return this.on(e,t,n,r,1)},off:function(e,n,r){var i,o;if(e&&e.preventDefault&&e.handleObj)return i=e.handleObj,b(e.delegateTarget).off(i.namespace?i.origType+"."+i.namespace:i.origType,i.selector,i.handler),this;if("object"==typeof e){for(o in e)this.off(o,n,e[o]);return this}return(n===!1||"function"==typeof n)&&(r=n,n=t),r===!1&&(r=ot),this.each(function(){b.event.remove(this,e,r,n)})},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)},trigger:function(e,t){return this.each(function(){b.event.trigger(e,t,this)})},triggerHandler:function(e,n){var r=this[0];return r?b.event.trigger(e,n,r,!0):t}}),function(e,t){var n,r,i,o,a,s,u,l,c,p,f,d,h,g,m,y,v,x="sizzle"+-new Date,w=e.document,T={},N=0,C=0,k=it(),E=it(),S=it(),A=typeof t,j=1<<31,D=[],L=D.pop,H=D.push,q=D.slice,M=D.indexOf||function(e){var t=0,n=this.length;for(;n>t;t++)if(this[t]===e)return t;return-1},_="[\\x20\\t\\r\\n\\f]",F="(?:\\\\.|[\\w-]|[^\\x00-\\xa0])+",O=F.replace("w","w#"),B="([*^$|!~]?=)",P="\\["+_+"*("+F+")"+_+"*(?:"+B+_+"*(?:(['\"])((?:\\\\.|[^\\\\])*?)\\3|("+O+")|)|)"+_+"*\\]",R=":("+F+")(?:\\(((['\"])((?:\\\\.|[^\\\\])*?)\\3|((?:\\\\.|[^\\\\()[\\]]|"+P.replace(3,8)+")*)|.*)\\)|)",W=RegExp("^"+_+"+|((?:^|[^\\\\])(?:\\\\.)*)"+_+"+$","g"),$=RegExp("^"+_+"*,"+_+"*"),I=RegExp("^"+_+"*([\\x20\\t\\r\\n\\f>+~])"+_+"*"),z=RegExp(R),X=RegExp("^"+O+"$"),U={ID:RegExp("^#("+F+")"),CLASS:RegExp("^\\.("+F+")"),NAME:RegExp("^\\[name=['\"]?("+F+")['\"]?\\]"),TAG:RegExp("^("+F.replace("w","w*")+")"),ATTR:RegExp("^"+P),PSEUDO:RegExp("^"+R),CHILD:RegExp("^:(only|first|last|nth|nth-last)-(child|of-type)(?:\\("+_+"*(even|odd|(([+-]|)(\\d*)n|)"+_+"*(?:([+-]|)"+_+"*(\\d+)|))"+_+"*\\)|)","i"),needsContext:RegExp("^"+_+"*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\\("+_+"*((?:-\\d)?\\d*)"+_+"*\\)|)(?=[^-]|$)","i")},V=/[\x20\t\r\n\f]*[+~]/,Y=/^[^{]+\{\s*\[native code/,J=/^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/,G=/^(?:input|select|textarea|button)$/i,Q=/^h\d$/i,K=/'|\\/g,Z=/\=[\x20\t\r\n\f]*([^'"\]]*)[\x20\t\r\n\f]*\]/g,et=/\\([\da-fA-F]{1,6}[\x20\t\r\n\f]?|.)/g,tt=function(e,t){var n="0x"+t-65536;return n!==n?t:0>n?String.fromCharCode(n+65536):String.fromCharCode(55296|n>>10,56320|1023&n)};try{q.call(w.documentElement.childNodes,0)[0].nodeType}catch(nt){q=function(e){var t,n=[];while(t=this[e++])n.push(t);return n}}function rt(e){return Y.test(e+"")}function it(){var e,t=[];return e=function(n,r){return t.push(n+=" ")>i.cacheLength&&delete e[t.shift()],e[n]=r}}function ot(e){return e[x]=!0,e}function at(e){var t=p.createElement("div");try{return e(t)}catch(n){return!1}finally{t=null}}function st(e,t,n,r){var i,o,a,s,u,l,f,g,m,v;if((t?t.ownerDocument||t:w)!==p&&c(t),t=t||p,n=n||[],!e||"string"!=typeof e)return n;if(1!==(s=t.nodeType)&&9!==s)return[];if(!d&&!r){if(i=J.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))&&y(t,o)&&o.id===a)return n.push(o),n}else{if(i[2])return H.apply(n,q.call(t.getElementsByTagName(e),0)),n;if((a=i[3])&&T.getByClassName&&t.getElementsByClassName)return H.apply(n,q.call(t.getElementsByClassName(a),0)),n}if(T.qsa&&!h.test(e)){if(f=!0,g=x,m=t,v=9===s&&e,1===s&&"object"!==t.nodeName.toLowerCase()){l=ft(e),(f=t.getAttribute("id"))?g=f.replace(K,"\\$&"):t.setAttribute("id",g),g="[id='"+g+"'] ",u=l.length;while(u--)l[u]=g+dt(l[u]);m=V.test(e)&&t.parentNode||t,v=l.join(",")}if(v)try{return H.apply(n,q.call(m.querySelectorAll(v),0)),n}catch(b){}finally{f||t.removeAttribute("id")}}}return wt(e.replace(W,"$1"),t,n,r)}a=st.isXML=function(e){var t=e&&(e.ownerDocument||e).documentElement;return t?"HTML"!==t.nodeName:!1},c=st.setDocument=function(e){var n=e?e.ownerDocument||e:w;return n!==p&&9===n.nodeType&&n.documentElement?(p=n,f=n.documentElement,d=a(n),T.tagNameNoComments=at(function(e){return e.appendChild(n.createComment("")),!e.getElementsByTagName("*").length}),T.attributes=at(function(e){e.innerHTML="<select></select>";var t=typeof e.lastChild.getAttribute("multiple");return"boolean"!==t&&"string"!==t}),T.getByClassName=at(function(e){return e.innerHTML="<div class='hidden e'></div><div class='hidden'></div>",e.getElementsByClassName&&e.getElementsByClassName("e").length?(e.lastChild.className="e",2===e.getElementsByClassName("e").length):!1}),T.getByName=at(function(e){e.id=x+0,e.innerHTML="<a name='"+x+"'></a><div name='"+x+"'></div>",f.insertBefore(e,f.firstChild);var t=n.getElementsByName&&n.getElementsByName(x).length===2+n.getElementsByName(x+0).length;return T.getIdNotName=!n.getElementById(x),f.removeChild(e),t}),i.attrHandle=at(function(e){return e.innerHTML="<a href='#'></a>",e.firstChild&&typeof e.firstChild.getAttribute!==A&&"#"===e.firstChild.getAttribute("href")})?{}:{href:function(e){return e.getAttribute("href",2)},type:function(e){return e.getAttribute("type")}},T.getIdNotName?(i.find.ID=function(e,t){if(typeof t.getElementById!==A&&!d){var n=t.getElementById(e);return n&&n.parentNode?[n]:[]}},i.filter.ID=function(e){var t=e.replace(et,tt);return function(e){return e.getAttribute("id")===t}}):(i.find.ID=function(e,n){if(typeof n.getElementById!==A&&!d){var r=n.getElementById(e);return r?r.id===e||typeof r.getAttributeNode!==A&&r.getAttributeNode("id").value===e?[r]:t:[]}},i.filter.ID=function(e){var t=e.replace(et,tt);return function(e){var n=typeof e.getAttributeNode!==A&&e.getAttributeNode("id");return n&&n.value===t}}),i.find.TAG=T.tagNameNoComments?function(e,n){return typeof n.getElementsByTagName!==A?n.getElementsByTagName(e):t}:function(e,t){var n,r=[],i=0,o=t.getElementsByTagName(e);if("*"===e){while(n=o[i++])1===n.nodeType&&r.push(n);return r}return o},i.find.NAME=T.getByName&&function(e,n){return typeof n.getElementsByName!==A?n.getElementsByName(name):t},i.find.CLASS=T.getByClassName&&function(e,n){return typeof n.getElementsByClassName===A||d?t:n.getElementsByClassName(e)},g=[],h=[":focus"],(T.qsa=rt(n.querySelectorAll))&&(at(function(e){e.innerHTML="<select><option selected=''></option></select>",e.querySelectorAll("[selected]").length||h.push("\\["+_+"*(?:checked|disabled|ismap|multiple|readonly|selected|value)"),e.querySelectorAll(":checked").length||h.push(":checked")}),at(function(e){e.innerHTML="<input type='hidden' i=''/>",e.querySelectorAll("[i^='']").length&&h.push("[*^$]="+_+"*(?:\"\"|'')"),e.querySelectorAll(":enabled").length||h.push(":enabled",":disabled"),e.querySelectorAll("*,:x"),h.push(",.*:")})),(T.matchesSelector=rt(m=f.matchesSelector||f.mozMatchesSelector||f.webkitMatchesSelector||f.oMatchesSelector||f.msMatchesSelector))&&at(function(e){T.disconnectedMatch=m.call(e,"div"),m.call(e,"[s!='']:x"),g.push("!=",R)}),h=RegExp(h.join("|")),g=RegExp(g.join("|")),y=rt(f.contains)||f.compareDocumentPosition?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)while(t=t.parentNode)if(t===e)return!0;return!1},v=f.compareDocumentPosition?function(e,t){var r;return e===t?(u=!0,0):(r=t.compareDocumentPosition&&e.compareDocumentPosition&&e.compareDocumentPosition(t))?1&r||e.parentNode&&11===e.parentNode.nodeType?e===n||y(w,e)?-1:t===n||y(w,t)?1:0:4&r?-1:1:e.compareDocumentPosition?-1:1}:function(e,t){var r,i=0,o=e.parentNode,a=t.parentNode,s=[e],l=[t];if(e===t)return u=!0,0;if(!o||!a)return e===n?-1:t===n?1:o?-1:a?1:0;if(o===a)return ut(e,t);r=e;while(r=r.parentNode)s.unshift(r);r=t;while(r=r.parentNode)l.unshift(r);while(s[i]===l[i])i++;return i?ut(s[i],l[i]):s[i]===w?-1:l[i]===w?1:0},u=!1,[0,0].sort(v),T.detectDuplicates=u,p):p},st.matches=function(e,t){return st(e,null,null,t)},st.matchesSelector=function(e,t){if((e.ownerDocument||e)!==p&&c(e),t=t.replace(Z,"='$1']"),!(!T.matchesSelector||d||g&&g.test(t)||h.test(t)))try{var n=m.call(e,t);if(n||T.disconnectedMatch||e.document&&11!==e.document.nodeType)return n}catch(r){}return st(t,p,null,[e]).length>0},st.contains=function(e,t){return(e.ownerDocument||e)!==p&&c(e),y(e,t)},st.attr=function(e,t){var n;return(e.ownerDocument||e)!==p&&c(e),d||(t=t.toLowerCase()),(n=i.attrHandle[t])?n(e):d||T.attributes?e.getAttribute(t):((n=e.getAttributeNode(t))||e.getAttribute(t))&&e[t]===!0?t:n&&n.specified?n.value:null},st.error=function(e){throw Error("Syntax error, unrecognized expression: "+e)},st.uniqueSort=function(e){var t,n=[],r=1,i=0;if(u=!T.detectDuplicates,e.sort(v),u){for(;t=e[r];r++)t===e[r-1]&&(i=n.push(r));while(i--)e.splice(n[i],1)}return e};function ut(e,t){var n=t&&e,r=n&&(~t.sourceIndex||j)-(~e.sourceIndex||j);if(r)return r;if(n)while(n=n.nextSibling)if(n===t)return-1;return e?1:-1}function lt(e){return function(t){var n=t.nodeName.toLowerCase();return"input"===n&&t.type===e}}function ct(e){return function(t){var n=t.nodeName.toLowerCase();return("input"===n||"button"===n)&&t.type===e}}function pt(e){return ot(function(t){return t=+t,ot(function(n,r){var i,o=e([],n.length,t),a=o.length;while(a--)n[i=o[a]]&&(n[i]=!(r[i]=n[i]))})})}o=st.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+=o(e)}else if(3===i||4===i)return e.nodeValue}else for(;t=e[r];r++)n+=o(t);return n},i=st.selectors={cacheLength:50,createPseudo:ot,match:U,find:{},relative:{">":{dir:"parentNode",first:!0}," ":{dir:"parentNode"},"+":{dir:"previousSibling",first:!0},"~":{dir:"previousSibling"}},preFilter:{ATTR:function(e){return e[1]=e[1].replace(et,tt),e[3]=(e[4]||e[5]||"").replace(et,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]||st.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]&&st.error(e[0]),e},PSEUDO:function(e){var t,n=!e[5]&&e[2];return U.CHILD.test(e[0])?null:(e[4]?e[2]=e[4]:n&&z.test(n)&&(t=ft(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){return"*"===e?function(){return!0}:(e=e.replace(et,tt).toLowerCase(),function(t){return t.nodeName&&t.nodeName.toLowerCase()===e})},CLASS:function(e){var t=k[e+" "];return t||(t=RegExp("(^|"+_+")"+e+"("+_+"|$)"))&&k(e,function(e){return t.test(e.className||typeof e.getAttribute!==A&&e.getAttribute("class")||"")})},ATTR:function(e,t,n){return function(r){var i=st.attr(r,e);return null==i?"!="===t:t?(i+="","="===t?i===n:"!="===t?i!==n:"^="===t?n&&0===i.indexOf(n):"*="===t?n&&i.indexOf(n)>-1:"$="===t?n&&i.slice(-n.length)===n:"~="===t?(" "+i+" ").indexOf(n)>-1:"|="===t?i===n||i.slice(0,n.length+1)===n+"-":!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,u){var l,c,p,f,d,h,g=o!==a?"nextSibling":"previousSibling",m=t.parentNode,y=s&&t.nodeName.toLowerCase(),v=!u&&!s;if(m){if(o){while(g){p=t;while(p=p[g])if(s?p.nodeName.toLowerCase()===y:1===p.nodeType)return!1;h=g="only"===e&&!h&&"nextSibling"}return!0}if(h=[a?m.firstChild:m.lastChild],a&&v){c=m[x]||(m[x]={}),l=c[e]||[],d=l[0]===N&&l[1],f=l[0]===N&&l[2],p=d&&m.childNodes[d];while(p=++d&&p&&p[g]||(f=d=0)||h.pop())if(1===p.nodeType&&++f&&p===t){c[e]=[N,d,f];break}}else if(v&&(l=(t[x]||(t[x]={}))[e])&&l[0]===N)f=l[1];else while(p=++d&&p&&p[g]||(f=d=0)||h.pop())if((s?p.nodeName.toLowerCase()===y:1===p.nodeType)&&++f&&(v&&((p[x]||(p[x]={}))[e]=[N,f]),p===t))break;return f-=i,f===r||0===f%r&&f/r>=0}}},PSEUDO:function(e,t){var n,r=i.pseudos[e]||i.setFilters[e.toLowerCase()]||st.error("unsupported pseudo: "+e);return r[x]?r(t):r.length>1?(n=[e,e,"",t],i.setFilters.hasOwnProperty(e.toLowerCase())?ot(function(e,n){var i,o=r(e,t),a=o.length;while(a--)i=M.call(e,o[a]),e[i]=!(n[i]=o[a])}):function(e){return r(e,0,n)}):r}},pseudos:{not:ot(function(e){var t=[],n=[],r=s(e.replace(W,"$1"));return r[x]?ot(function(e,t,n,i){var o,a=r(e,null,i,[]),s=e.length;while(s--)(o=a[s])&&(e[s]=!(t[s]=o))}):function(e,i,o){return t[0]=e,r(t,null,o,n),!n.pop()}}),has:ot(function(e){return function(t){return st(e,t).length>0}}),contains:ot(function(e){return function(t){return(t.textContent||t.innerText||o(t)).indexOf(e)>-1}}),lang:ot(function(e){return X.test(e||"")||st.error("unsupported lang: "+e),e=e.replace(et,tt).toLowerCase(),function(t){var n;do if(n=d?t.getAttribute("xml:lang")||t.getAttribute("lang"):t.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===f},focus:function(e){return e===p.activeElement&&(!p.hasFocus||p.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.nodeName>"@"||3===e.nodeType||4===e.nodeType)return!1;return!0},parent:function(e){return!i.pseudos.empty(e)},header:function(e){return Q.test(e.nodeName)},input:function(e){return G.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"))||t.toLowerCase()===e.type)},first:pt(function(){return[0]}),last:pt(function(e,t){return[t-1]}),eq:pt(function(e,t,n){return[0>n?n+t:n]}),even:pt(function(e,t){var n=0;for(;t>n;n+=2)e.push(n);return e}),odd:pt(function(e,t){var n=1;for(;t>n;n+=2)e.push(n);return e}),lt:pt(function(e,t,n){var r=0>n?n+t:n;for(;--r>=0;)e.push(r);return e}),gt:pt(function(e,t,n){var r=0>n?n+t:n;for(;t>++r;)e.push(r);return e})}};for(n in{radio:!0,checkbox:!0,file:!0,password:!0,image:!0})i.pseudos[n]=lt(n);for(n in{submit:!0,reset:!0})i.pseudos[n]=ct(n);function ft(e,t){var n,r,o,a,s,u,l,c=E[e+" "];if(c)return t?0:c.slice(0);s=e,u=[],l=i.preFilter;while(s){(!n||(r=$.exec(s)))&&(r&&(s=s.slice(r[0].length)||s),u.push(o=[])),n=!1,(r=I.exec(s))&&(n=r.shift(),o.push({value:n,type:r[0].replace(W," ")}),s=s.slice(n.length));for(a in i.filter)!(r=U[a].exec(s))||l[a]&&!(r=l[a](r))||(n=r.shift(),o.push({value:n,type:a,matches:r}),s=s.slice(n.length));if(!n)break}return t?s.length:s?st.error(e):E(e,u).slice(0)}function dt(e){var t=0,n=e.length,r="";for(;n>t;t++)r+=e[t].value;return r}function ht(e,t,n){var i=t.dir,o=n&&"parentNode"===i,a=C++;return t.first?function(t,n,r){while(t=t[i])if(1===t.nodeType||o)return e(t,n,r)}:function(t,n,s){var u,l,c,p=N+" "+a;if(s){while(t=t[i])if((1===t.nodeType||o)&&e(t,n,s))return!0}else while(t=t[i])if(1===t.nodeType||o)if(c=t[x]||(t[x]={}),(l=c[i])&&l[0]===p){if((u=l[1])===!0||u===r)return u===!0}else if(l=c[i]=[p],l[1]=e(t,n,s)||r,l[1]===!0)return!0}}function gt(e){return e.length>1?function(t,n,r){var i=e.length;while(i--)if(!e[i](t,n,r))return!1;return!0}:e[0]}function mt(e,t,n,r,i){var o,a=[],s=0,u=e.length,l=null!=t;for(;u>s;s++)(o=e[s])&&(!n||n(o,r,i))&&(a.push(o),l&&t.push(s));return a}function yt(e,t,n,r,i,o){return r&&!r[x]&&(r=yt(r)),i&&!i[x]&&(i=yt(i,o)),ot(function(o,a,s,u){var l,c,p,f=[],d=[],h=a.length,g=o||xt(t||"*",s.nodeType?[s]:s,[]),m=!e||!o&&t?g:mt(g,f,e,s,u),y=n?i||(o?e:h||r)?[]:a:m;if(n&&n(m,y,s,u),r){l=mt(y,d),r(l,[],s,u),c=l.length;while(c--)(p=l[c])&&(y[d[c]]=!(m[d[c]]=p))}if(o){if(i||e){if(i){l=[],c=y.length;while(c--)(p=y[c])&&l.push(m[c]=p);i(null,y=[],l,u)}c=y.length;while(c--)(p=y[c])&&(l=i?M.call(o,p):f[c])>-1&&(o[l]=!(a[l]=p))}}else y=mt(y===a?y.splice(h,y.length):y),i?i(null,a,y,u):H.apply(a,y)})}function vt(e){var t,n,r,o=e.length,a=i.relative[e[0].type],s=a||i.relative[" "],u=a?1:0,c=ht(function(e){return e===t},s,!0),p=ht(function(e){return M.call(t,e)>-1},s,!0),f=[function(e,n,r){return!a&&(r||n!==l)||((t=n).nodeType?c(e,n,r):p(e,n,r))}];for(;o>u;u++)if(n=i.relative[e[u].type])f=[ht(gt(f),n)];else{if(n=i.filter[e[u].type].apply(null,e[u].matches),n[x]){for(r=++u;o>r;r++)if(i.relative[e[r].type])break;return yt(u>1&&gt(f),u>1&&dt(e.slice(0,u-1)).replace(W,"$1"),n,r>u&&vt(e.slice(u,r)),o>r&&vt(e=e.slice(r)),o>r&&dt(e))}f.push(n)}return gt(f)}function bt(e,t){var n=0,o=t.length>0,a=e.length>0,s=function(s,u,c,f,d){var h,g,m,y=[],v=0,b="0",x=s&&[],w=null!=d,T=l,C=s||a&&i.find.TAG("*",d&&u.parentNode||u),k=N+=null==T?1:Math.random()||.1;for(w&&(l=u!==p&&u,r=n);null!=(h=C[b]);b++){if(a&&h){g=0;while(m=e[g++])if(m(h,u,c)){f.push(h);break}w&&(N=k,r=++n)}o&&((h=!m&&h)&&v--,s&&x.push(h))}if(v+=b,o&&b!==v){g=0;while(m=t[g++])m(x,y,u,c);if(s){if(v>0)while(b--)x[b]||y[b]||(y[b]=L.call(f));y=mt(y)}H.apply(f,y),w&&!s&&y.length>0&&v+t.length>1&&st.uniqueSort(f)}return w&&(N=k,l=T),x};return o?ot(s):s}s=st.compile=function(e,t){var n,r=[],i=[],o=S[e+" "];if(!o){t||(t=ft(e)),n=t.length;while(n--)o=vt(t[n]),o[x]?r.push(o):i.push(o);o=S(e,bt(i,r))}return o};function xt(e,t,n){var r=0,i=t.length;for(;i>r;r++)st(e,t[r],n);return n}function wt(e,t,n,r){var o,a,u,l,c,p=ft(e);if(!r&&1===p.length){if(a=p[0]=p[0].slice(0),a.length>2&&"ID"===(u=a[0]).type&&9===t.nodeType&&!d&&i.relative[a[1].type]){if(t=i.find.ID(u.matches[0].replace(et,tt),t)[0],!t)return n;e=e.slice(a.shift().value.length)}o=U.needsContext.test(e)?0:a.length;while(o--){if(u=a[o],i.relative[l=u.type])break;if((c=i.find[l])&&(r=c(u.matches[0].replace(et,tt),V.test(a[0].type)&&t.parentNode||t))){if(a.splice(o,1),e=r.length&&dt(a),!e)return H.apply(n,q.call(r,0)),n;break}}}return s(e,p)(r,t,d,n,V.test(e)),n}i.pseudos.nth=i.pseudos.eq;function Tt(){}i.filters=Tt.prototype=i.pseudos,i.setFilters=new Tt,c(),st.attr=b.attr,b.find=st,b.expr=st.selectors,b.expr[":"]=b.expr.pseudos,b.unique=st.uniqueSort,b.text=st.getText,b.isXMLDoc=st.isXML,b.contains=st.contains}(e);var at=/Until$/,st=/^(?:parents|prev(?:Until|All))/,ut=/^.[^:#\[\.,]*$/,lt=b.expr.match.needsContext,ct={children:!0,contents:!0,next:!0,prev:!0};b.fn.extend({find:function(e){var t,n,r,i=this.length;if("string"!=typeof e)return r=this,this.pushStack(b(e).filter(function(){for(t=0;i>t;t++)if(b.contains(r[t],this))return!0}));for(n=[],t=0;i>t;t++)b.find(e,this[t],n);return n=this.pushStack(i>1?b.unique(n):n),n.selector=(this.selector?this.selector+" ":"")+e,n},has:function(e){var t,n=b(e,this),r=n.length;return this.filter(function(){for(t=0;r>t;t++)if(b.contains(this,n[t]))return!0})},not:function(e){return this.pushStack(ft(this,e,!1))},filter:function(e){return this.pushStack(ft(this,e,!0))},is:function(e){return!!e&&("string"==typeof e?lt.test(e)?b(e,this.context).index(this[0])>=0:b.filter(e,this).length>0:this.filter(e).length>0)},closest:function(e,t){var n,r=0,i=this.length,o=[],a=lt.test(e)||"string"!=typeof e?b(e,t||this.context):0;for(;i>r;r++){n=this[r];while(n&&n.ownerDocument&&n!==t&&11!==n.nodeType){if(a?a.index(n)>-1:b.find.matchesSelector(n,e)){o.push(n);break}n=n.parentNode}}return this.pushStack(o.length>1?b.unique(o):o)},index:function(e){return e?"string"==typeof e?b.inArray(this[0],b(e)):b.inArray(e.jquery?e[0]:e,this):this[0]&&this[0].parentNode?this.first().prevAll().length:-1},add:function(e,t){var n="string"==typeof e?b(e,t):b.makeArray(e&&e.nodeType?[e]:e),r=b.merge(this.get(),n);return this.pushStack(b.unique(r))},addBack:function(e){return this.add(null==e?this.prevObject:this.prevObject.filter(e))}}),b.fn.andSelf=b.fn.addBack;function pt(e,t){do e=e[t];while(e&&1!==e.nodeType);return e}b.each({parent:function(e){var t=e.parentNode;return t&&11!==t.nodeType?t:null},parents:function(e){return b.dir(e,"parentNode")},parentsUntil:function(e,t,n){return b.dir(e,"parentNode",n)},next:function(e){return pt(e,"nextSibling")},prev:function(e){return pt(e,"previousSibling")},nextAll:function(e){return b.dir(e,"nextSibling")},prevAll:function(e){return b.dir(e,"previousSibling")},nextUntil:function(e,t,n){return b.dir(e,"nextSibling",n)},prevUntil:function(e,t,n){return b.dir(e,"previousSibling",n)},siblings:function(e){return b.sibling((e.parentNode||{}).firstChild,e)},children:function(e){return b.sibling(e.firstChild)},contents:function(e){return b.nodeName(e,"iframe")?e.contentDocument||e.contentWindow.document:b.merge([],e.childNodes)}},function(e,t){b.fn[e]=function(n,r){var i=b.map(this,t,n);return at.test(e)||(r=n),r&&"string"==typeof r&&(i=b.filter(r,i)),i=this.length>1&&!ct[e]?b.unique(i):i,this.length>1&&st.test(e)&&(i=i.reverse()),this.pushStack(i)}}),b.extend({filter:function(e,t,n){return n&&(e=":not("+e+")"),1===t.length?b.find.matchesSelector(t[0],e)?[t[0]]:[]:b.find.matches(e,t)},dir:function(e,n,r){var i=[],o=e[n];while(o&&9!==o.nodeType&&(r===t||1!==o.nodeType||!b(o).is(r)))1===o.nodeType&&i.push(o),o=o[n];return i},sibling:function(e,t){var n=[];for(;e;e=e.nextSibling)1===e.nodeType&&e!==t&&n.push(e);return n}});function ft(e,t,n){if(t=t||0,b.isFunction(t))return b.grep(e,function(e,r){var i=!!t.call(e,r,e);return i===n});if(t.nodeType)return b.grep(e,function(e){return e===t===n});if("string"==typeof t){var r=b.grep(e,function(e){return 1===e.nodeType});if(ut.test(t))return b.filter(t,r,!n);t=b.filter(t,r)}return b.grep(e,function(e){return b.inArray(e,t)>=0===n})}function dt(e){var t=ht.split("|"),n=e.createDocumentFragment();if(n.createElement)while(t.length)n.createElement(t.pop());return n}var ht="abbr|article|aside|audio|bdi|canvas|data|datalist|details|figcaption|figure|footer|header|hgroup|mark|meter|nav|output|progress|section|summary|time|video",gt=/ jQuery\d+="(?:null|\d+)"/g,mt=RegExp("<(?:"+ht+")[\\s/>]","i"),yt=/^\s+/,vt=/<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/gi,bt=/<([\w:]+)/,xt=/<tbody/i,wt=/<|&#?\w+;/,Tt=/<(?:script|style|link)/i,Nt=/^(?:checkbox|radio)$/i,Ct=/checked\s*(?:[^=]|=\s*.checked.)/i,kt=/^$|\/(?:java|ecma)script/i,Et=/^true\/(.*)/,St=/^\s*<!(?:\[CDATA\[|--)|(?:\]\]|--)>\s*$/g,At={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:b.support.htmlSerialize?[0,"",""]:[1,"X<div>","</div>"]},jt=dt(o),Dt=jt.appendChild(o.createElement("div"));At.optgroup=At.option,At.tbody=At.tfoot=At.colgroup=At.caption=At.thead,At.th=At.td,b.fn.extend({text:function(e){return b.access(this,function(e){return e===t?b.text(this):this.empty().append((this[0]&&this[0].ownerDocument||o).createTextNode(e))},null,e,arguments.length)},wrapAll:function(e){if(b.isFunction(e))return this.each(function(t){b(this).wrapAll(e.call(this,t))});if(this[0]){var t=b(e,this[0].ownerDocument).eq(0).clone(!0);this[0].parentNode&&t.insertBefore(this[0]),t.map(function(){var e=this;while(e.firstChild&&1===e.firstChild.nodeType)e=e.firstChild;return e}).append(this)}return this},wrapInner:function(e){return b.isFunction(e)?this.each(function(t){b(this).wrapInner(e.call(this,t))}):this.each(function(){var t=b(this),n=t.contents();n.length?n.wrapAll(e):t.append(e)})},wrap:function(e){var t=b.isFunction(e);return this.each(function(n){b(this).wrapAll(t?e.call(this,n):e)})},unwrap:function(){return this.parent().each(function(){b.nodeName(this,"body")||b(this).replaceWith(this.childNodes)}).end()},append:function(){return this.domManip(arguments,!0,function(e){(1===this.nodeType||11===this.nodeType||9===this.nodeType)&&this.appendChild(e)})},prepend:function(){return this.domManip(arguments,!0,function(e){(1===this.nodeType||11===this.nodeType||9===this.nodeType)&&this.insertBefore(e,this.firstChild)})},before:function(){return this.domManip(arguments,!1,function(e){this.parentNode&&this.parentNode.insertBefore(e,this)})},after:function(){return this.domManip(arguments,!1,function(e){this.parentNode&&this.parentNode.insertBefore(e,this.nextSibling)})},remove:function(e,t){var n,r=0;for(;null!=(n=this[r]);r++)(!e||b.filter(e,[n]).length>0)&&(t||1!==n.nodeType||b.cleanData(Ot(n)),n.parentNode&&(t&&b.contains(n.ownerDocument,n)&&Mt(Ot(n,"script")),n.parentNode.removeChild(n)));return this},empty:function(){var e,t=0;for(;null!=(e=this[t]);t++){1===e.nodeType&&b.cleanData(Ot(e,!1));while(e.firstChild)e.removeChild(e.firstChild);e.options&&b.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 b.clone(this,e,t)})},html:function(e){return b.access(this,function(e){var n=this[0]||{},r=0,i=this.length;if(e===t)return 1===n.nodeType?n.innerHTML.replace(gt,""):t;if(!("string"!=typeof e||Tt.test(e)||!b.support.htmlSerialize&&mt.test(e)||!b.support.leadingWhitespace&&yt.test(e)||At[(bt.exec(e)||["",""])[1].toLowerCase()])){e=e.replace(vt,"<$1></$2>");try{for(;i>r;r++)n=this[r]||{},1===n.nodeType&&(b.cleanData(Ot(n,!1)),n.innerHTML=e);n=0}catch(o){}}n&&this.empty().append(e)},null,e,arguments.length)},replaceWith:function(e){var t=b.isFunction(e);return t||"string"==typeof e||(e=b(e).not(this).detach()),this.domManip([e],!0,function(e){var t=this.nextSibling,n=this.parentNode;n&&(b(this).remove(),n.insertBefore(e,t))})},detach:function(e){return this.remove(e,!0)},domManip:function(e,n,r){e=f.apply([],e);var i,o,a,s,u,l,c=0,p=this.length,d=this,h=p-1,g=e[0],m=b.isFunction(g);if(m||!(1>=p||"string"!=typeof g||b.support.checkClone)&&Ct.test(g))return this.each(function(i){var o=d.eq(i);m&&(e[0]=g.call(this,i,n?o.html():t)),o.domManip(e,n,r)});if(p&&(l=b.buildFragment(e,this[0].ownerDocument,!1,this),i=l.firstChild,1===l.childNodes.length&&(l=i),i)){for(n=n&&b.nodeName(i,"tr"),s=b.map(Ot(l,"script"),Ht),a=s.length;p>c;c++)o=l,c!==h&&(o=b.clone(o,!0,!0),a&&b.merge(s,Ot(o,"script"))),r.call(n&&b.nodeName(this[c],"table")?Lt(this[c],"tbody"):this[c],o,c);if(a)for(u=s[s.length-1].ownerDocument,b.map(s,qt),c=0;a>c;c++)o=s[c],kt.test(o.type||"")&&!b._data(o,"globalEval")&&b.contains(u,o)&&(o.src?b.ajax({url:o.src,type:"GET",dataType:"script",async:!1,global:!1,"throws":!0}):b.globalEval((o.text||o.textContent||o.innerHTML||"").replace(St,"")));l=i=null}return this}});function Lt(e,t){return e.getElementsByTagName(t)[0]||e.appendChild(e.ownerDocument.createElement(t))}function Ht(e){var t=e.getAttributeNode("type");return e.type=(t&&t.specified)+"/"+e.type,e}function qt(e){var t=Et.exec(e.type);return t?e.type=t[1]:e.removeAttribute("type"),e}function Mt(e,t){var n,r=0;for(;null!=(n=e[r]);r++)b._data(n,"globalEval",!t||b._data(t[r],"globalEval"))}function _t(e,t){if(1===t.nodeType&&b.hasData(e)){var n,r,i,o=b._data(e),a=b._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++)b.event.add(t,n,s[n][r])}a.data&&(a.data=b.extend({},a.data))}}function Ft(e,t){var n,r,i;if(1===t.nodeType){if(n=t.nodeName.toLowerCase(),!b.support.noCloneEvent&&t[b.expando]){i=b._data(t);for(r in i.events)b.removeEvent(t,r,i.handle);t.removeAttribute(b.expando)}"script"===n&&t.text!==e.text?(Ht(t).text=e.text,qt(t)):"object"===n?(t.parentNode&&(t.outerHTML=e.outerHTML),b.support.html5Clone&&e.innerHTML&&!b.trim(t.innerHTML)&&(t.innerHTML=e.innerHTML)):"input"===n&&Nt.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)}}b.each({appendTo:"append",prependTo:"prepend",insertBefore:"before",insertAfter:"after",replaceAll:"replaceWith"},function(e,t){b.fn[e]=function(e){var n,r=0,i=[],o=b(e),a=o.length-1;for(;a>=r;r++)n=r===a?this:this.clone(!0),b(o[r])[t](n),d.apply(i,n.get());return this.pushStack(i)}});function Ot(e,n){var r,o,a=0,s=typeof e.getElementsByTagName!==i?e.getElementsByTagName(n||"*"):typeof e.querySelectorAll!==i?e.querySelectorAll(n||"*"):t;if(!s)for(s=[],r=e.childNodes||e;null!=(o=r[a]);a++)!n||b.nodeName(o,n)?s.push(o):b.merge(s,Ot(o,n));return n===t||n&&b.nodeName(e,n)?b.merge([e],s):s}function Bt(e){Nt.test(e.type)&&(e.defaultChecked=e.checked)}b.extend({clone:function(e,t,n){var r,i,o,a,s,u=b.contains(e.ownerDocument,e);if(b.support.html5Clone||b.isXMLDoc(e)||!mt.test("<"+e.nodeName+">")?o=e.cloneNode(!0):(Dt.innerHTML=e.outerHTML,Dt.removeChild(o=Dt.firstChild)),!(b.support.noCloneEvent&&b.support.noCloneChecked||1!==e.nodeType&&11!==e.nodeType||b.isXMLDoc(e)))for(r=Ot(o),s=Ot(e),a=0;null!=(i=s[a]);++a)r[a]&&Ft(i,r[a]);if(t)if(n)for(s=s||Ot(e),r=r||Ot(o),a=0;null!=(i=s[a]);a++)_t(i,r[a]);else _t(e,o);return r=Ot(o,"script"),r.length>0&&Mt(r,!u&&Ot(e,"script")),r=s=i=null,o},buildFragment:function(e,t,n,r){var i,o,a,s,u,l,c,p=e.length,f=dt(t),d=[],h=0;for(;p>h;h++)if(o=e[h],o||0===o)if("object"===b.type(o))b.merge(d,o.nodeType?[o]:o);else if(wt.test(o)){s=s||f.appendChild(t.createElement("div")),u=(bt.exec(o)||["",""])[1].toLowerCase(),c=At[u]||At._default,s.innerHTML=c[1]+o.replace(vt,"<$1></$2>")+c[2],i=c[0];while(i--)s=s.lastChild;if(!b.support.leadingWhitespace&&yt.test(o)&&d.push(t.createTextNode(yt.exec(o)[0])),!b.support.tbody){o="table"!==u||xt.test(o)?"<table>"!==c[1]||xt.test(o)?0:s:s.firstChild,i=o&&o.childNodes.length;while(i--)b.nodeName(l=o.childNodes[i],"tbody")&&!l.childNodes.length&&o.removeChild(l) }b.merge(d,s.childNodes),s.textContent="";while(s.firstChild)s.removeChild(s.firstChild);s=f.lastChild}else d.push(t.createTextNode(o));s&&f.removeChild(s),b.support.appendChecked||b.grep(Ot(d,"input"),Bt),h=0;while(o=d[h++])if((!r||-1===b.inArray(o,r))&&(a=b.contains(o.ownerDocument,o),s=Ot(f.appendChild(o),"script"),a&&Mt(s),n)){i=0;while(o=s[i++])kt.test(o.type||"")&&n.push(o)}return s=null,f},cleanData:function(e,t){var n,r,o,a,s=0,u=b.expando,l=b.cache,p=b.support.deleteExpando,f=b.event.special;for(;null!=(n=e[s]);s++)if((t||b.acceptData(n))&&(o=n[u],a=o&&l[o])){if(a.events)for(r in a.events)f[r]?b.event.remove(n,r):b.removeEvent(n,r,a.handle);l[o]&&(delete l[o],p?delete n[u]:typeof n.removeAttribute!==i?n.removeAttribute(u):n[u]=null,c.push(o))}}});var Pt,Rt,Wt,$t=/alpha\([^)]*\)/i,It=/opacity\s*=\s*([^)]*)/,zt=/^(top|right|bottom|left)$/,Xt=/^(none|table(?!-c[ea]).+)/,Ut=/^margin/,Vt=RegExp("^("+x+")(.*)$","i"),Yt=RegExp("^("+x+")(?!px)[a-z%]+$","i"),Jt=RegExp("^([+-])=("+x+")","i"),Gt={BODY:"block"},Qt={position:"absolute",visibility:"hidden",display:"block"},Kt={letterSpacing:0,fontWeight:400},Zt=["Top","Right","Bottom","Left"],en=["Webkit","O","Moz","ms"];function tn(e,t){if(t in e)return t;var n=t.charAt(0).toUpperCase()+t.slice(1),r=t,i=en.length;while(i--)if(t=en[i]+n,t in e)return t;return r}function nn(e,t){return e=t||e,"none"===b.css(e,"display")||!b.contains(e.ownerDocument,e)}function rn(e,t){var n,r,i,o=[],a=0,s=e.length;for(;s>a;a++)r=e[a],r.style&&(o[a]=b._data(r,"olddisplay"),n=r.style.display,t?(o[a]||"none"!==n||(r.style.display=""),""===r.style.display&&nn(r)&&(o[a]=b._data(r,"olddisplay",un(r.nodeName)))):o[a]||(i=nn(r),(n&&"none"!==n||!i)&&b._data(r,"olddisplay",i?n:b.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}b.fn.extend({css:function(e,n){return b.access(this,function(e,n,r){var i,o,a={},s=0;if(b.isArray(n)){for(o=Rt(e),i=n.length;i>s;s++)a[n[s]]=b.css(e,n[s],!1,o);return a}return r!==t?b.style(e,n,r):b.css(e,n)},e,n,arguments.length>1)},show:function(){return rn(this,!0)},hide:function(){return rn(this)},toggle:function(e){var t="boolean"==typeof e;return this.each(function(){(t?e:nn(this))?b(this).show():b(this).hide()})}}),b.extend({cssHooks:{opacity:{get:function(e,t){if(t){var n=Wt(e,"opacity");return""===n?"1":n}}}},cssNumber:{columnCount:!0,fillOpacity:!0,fontWeight:!0,lineHeight:!0,opacity:!0,orphans:!0,widows:!0,zIndex:!0,zoom:!0},cssProps:{"float":b.support.cssFloat?"cssFloat":"styleFloat"},style:function(e,n,r,i){if(e&&3!==e.nodeType&&8!==e.nodeType&&e.style){var o,a,s,u=b.camelCase(n),l=e.style;if(n=b.cssProps[u]||(b.cssProps[u]=tn(l,u)),s=b.cssHooks[n]||b.cssHooks[u],r===t)return s&&"get"in s&&(o=s.get(e,!1,i))!==t?o:l[n];if(a=typeof r,"string"===a&&(o=Jt.exec(r))&&(r=(o[1]+1)*o[2]+parseFloat(b.css(e,n)),a="number"),!(null==r||"number"===a&&isNaN(r)||("number"!==a||b.cssNumber[u]||(r+="px"),b.support.clearCloneStyle||""!==r||0!==n.indexOf("background")||(l[n]="inherit"),s&&"set"in s&&(r=s.set(e,r,i))===t)))try{l[n]=r}catch(c){}}},css:function(e,n,r,i){var o,a,s,u=b.camelCase(n);return n=b.cssProps[u]||(b.cssProps[u]=tn(e.style,u)),s=b.cssHooks[n]||b.cssHooks[u],s&&"get"in s&&(a=s.get(e,!0,r)),a===t&&(a=Wt(e,n,i)),"normal"===a&&n in Kt&&(a=Kt[n]),""===r||r?(o=parseFloat(a),r===!0||b.isNumeric(o)?o||0:a):a},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}}),e.getComputedStyle?(Rt=function(t){return e.getComputedStyle(t,null)},Wt=function(e,n,r){var i,o,a,s=r||Rt(e),u=s?s.getPropertyValue(n)||s[n]:t,l=e.style;return s&&(""!==u||b.contains(e.ownerDocument,e)||(u=b.style(e,n)),Yt.test(u)&&Ut.test(n)&&(i=l.width,o=l.minWidth,a=l.maxWidth,l.minWidth=l.maxWidth=l.width=u,u=s.width,l.width=i,l.minWidth=o,l.maxWidth=a)),u}):o.documentElement.currentStyle&&(Rt=function(e){return e.currentStyle},Wt=function(e,n,r){var i,o,a,s=r||Rt(e),u=s?s[n]:t,l=e.style;return null==u&&l&&l[n]&&(u=l[n]),Yt.test(u)&&!zt.test(n)&&(i=l.left,o=e.runtimeStyle,a=o&&o.left,a&&(o.left=e.currentStyle.left),l.left="fontSize"===n?"1em":u,u=l.pixelLeft+"px",l.left=i,a&&(o.left=a)),""===u?"auto":u});function on(e,t,n){var r=Vt.exec(t);return r?Math.max(0,r[1]-(n||0))+(r[2]||"px"):t}function an(e,t,n,r,i){var o=n===(r?"border":"content")?4:"width"===t?1:0,a=0;for(;4>o;o+=2)"margin"===n&&(a+=b.css(e,n+Zt[o],!0,i)),r?("content"===n&&(a-=b.css(e,"padding"+Zt[o],!0,i)),"margin"!==n&&(a-=b.css(e,"border"+Zt[o]+"Width",!0,i))):(a+=b.css(e,"padding"+Zt[o],!0,i),"padding"!==n&&(a+=b.css(e,"border"+Zt[o]+"Width",!0,i)));return a}function sn(e,t,n){var r=!0,i="width"===t?e.offsetWidth:e.offsetHeight,o=Rt(e),a=b.support.boxSizing&&"border-box"===b.css(e,"boxSizing",!1,o);if(0>=i||null==i){if(i=Wt(e,t,o),(0>i||null==i)&&(i=e.style[t]),Yt.test(i))return i;r=a&&(b.support.boxSizingReliable||i===e.style[t]),i=parseFloat(i)||0}return i+an(e,t,n||(a?"border":"content"),r,o)+"px"}function un(e){var t=o,n=Gt[e];return n||(n=ln(e,t),"none"!==n&&n||(Pt=(Pt||b("<iframe frameborder='0' width='0' height='0'/>").css("cssText","display:block !important")).appendTo(t.documentElement),t=(Pt[0].contentWindow||Pt[0].contentDocument).document,t.write("<!doctype html><html><body>"),t.close(),n=ln(e,t),Pt.detach()),Gt[e]=n),n}function ln(e,t){var n=b(t.createElement(e)).appendTo(t.body),r=b.css(n[0],"display");return n.remove(),r}b.each(["height","width"],function(e,n){b.cssHooks[n]={get:function(e,r,i){return r?0===e.offsetWidth&&Xt.test(b.css(e,"display"))?b.swap(e,Qt,function(){return sn(e,n,i)}):sn(e,n,i):t},set:function(e,t,r){var i=r&&Rt(e);return on(e,t,r?an(e,n,r,b.support.boxSizing&&"border-box"===b.css(e,"boxSizing",!1,i),i):0)}}}),b.support.opacity||(b.cssHooks.opacity={get:function(e,t){return It.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=b.isNumeric(t)?"alpha(opacity="+100*t+")":"",o=r&&r.filter||n.filter||"";n.zoom=1,(t>=1||""===t)&&""===b.trim(o.replace($t,""))&&n.removeAttribute&&(n.removeAttribute("filter"),""===t||r&&!r.filter)||(n.filter=$t.test(o)?o.replace($t,i):o+" "+i)}}),b(function(){b.support.reliableMarginRight||(b.cssHooks.marginRight={get:function(e,n){return n?b.swap(e,{display:"inline-block"},Wt,[e,"marginRight"]):t}}),!b.support.pixelPosition&&b.fn.position&&b.each(["top","left"],function(e,n){b.cssHooks[n]={get:function(e,r){return r?(r=Wt(e,n),Yt.test(r)?b(e).position()[n]+"px":r):t}}})}),b.expr&&b.expr.filters&&(b.expr.filters.hidden=function(e){return 0>=e.offsetWidth&&0>=e.offsetHeight||!b.support.reliableHiddenOffsets&&"none"===(e.style&&e.style.display||b.css(e,"display"))},b.expr.filters.visible=function(e){return!b.expr.filters.hidden(e)}),b.each({margin:"",padding:"",border:"Width"},function(e,t){b.cssHooks[e+t]={expand:function(n){var r=0,i={},o="string"==typeof n?n.split(" "):[n];for(;4>r;r++)i[e+Zt[r]+t]=o[r]||o[r-2]||o[0];return i}},Ut.test(e)||(b.cssHooks[e+t].set=on)});var cn=/%20/g,pn=/\[\]$/,fn=/\r?\n/g,dn=/^(?:submit|button|image|reset|file)$/i,hn=/^(?:input|select|textarea|keygen)/i;b.fn.extend({serialize:function(){return b.param(this.serializeArray())},serializeArray:function(){return this.map(function(){var e=b.prop(this,"elements");return e?b.makeArray(e):this}).filter(function(){var e=this.type;return this.name&&!b(this).is(":disabled")&&hn.test(this.nodeName)&&!dn.test(e)&&(this.checked||!Nt.test(e))}).map(function(e,t){var n=b(this).val();return null==n?null:b.isArray(n)?b.map(n,function(e){return{name:t.name,value:e.replace(fn,"\r\n")}}):{name:t.name,value:n.replace(fn,"\r\n")}}).get()}}),b.param=function(e,n){var r,i=[],o=function(e,t){t=b.isFunction(t)?t():null==t?"":t,i[i.length]=encodeURIComponent(e)+"="+encodeURIComponent(t)};if(n===t&&(n=b.ajaxSettings&&b.ajaxSettings.traditional),b.isArray(e)||e.jquery&&!b.isPlainObject(e))b.each(e,function(){o(this.name,this.value)});else for(r in e)gn(r,e[r],n,o);return i.join("&").replace(cn,"+")};function gn(e,t,n,r){var i;if(b.isArray(t))b.each(t,function(t,i){n||pn.test(e)?r(e,i):gn(e+"["+("object"==typeof i?t:"")+"]",i,n,r)});else if(n||"object"!==b.type(t))r(e,t);else for(i in t)gn(e+"["+i+"]",t[i],n,r)}b.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){b.fn[t]=function(e,n){return arguments.length>0?this.on(t,null,e,n):this.trigger(t)}}),b.fn.hover=function(e,t){return this.mouseenter(e).mouseleave(t||e)};var mn,yn,vn=b.now(),bn=/\?/,xn=/#.*$/,wn=/([?&])_=[^&]*/,Tn=/^(.*?):[ \t]*([^\r\n]*)\r?$/gm,Nn=/^(?:about|app|app-storage|.+-extension|file|res|widget):$/,Cn=/^(?:GET|HEAD)$/,kn=/^\/\//,En=/^([\w.+-]+:)(?:\/\/([^\/?#:]*)(?::(\d+)|)|)/,Sn=b.fn.load,An={},jn={},Dn="*/".concat("*");try{yn=a.href}catch(Ln){yn=o.createElement("a"),yn.href="",yn=yn.href}mn=En.exec(yn.toLowerCase())||[];function Hn(e){return function(t,n){"string"!=typeof t&&(n=t,t="*");var r,i=0,o=t.toLowerCase().match(w)||[];if(b.isFunction(n))while(r=o[i++])"+"===r[0]?(r=r.slice(1)||"*",(e[r]=e[r]||[]).unshift(n)):(e[r]=e[r]||[]).push(n)}}function qn(e,n,r,i){var o={},a=e===jn;function s(u){var l;return o[u]=!0,b.each(e[u]||[],function(e,u){var c=u(n,r,i);return"string"!=typeof c||a||o[c]?a?!(l=c):t:(n.dataTypes.unshift(c),s(c),!1)}),l}return s(n.dataTypes[0])||!o["*"]&&s("*")}function Mn(e,n){var r,i,o=b.ajaxSettings.flatOptions||{};for(i in n)n[i]!==t&&((o[i]?e:r||(r={}))[i]=n[i]);return r&&b.extend(!0,e,r),e}b.fn.load=function(e,n,r){if("string"!=typeof e&&Sn)return Sn.apply(this,arguments);var i,o,a,s=this,u=e.indexOf(" ");return u>=0&&(i=e.slice(u,e.length),e=e.slice(0,u)),b.isFunction(n)?(r=n,n=t):n&&"object"==typeof n&&(a="POST"),s.length>0&&b.ajax({url:e,type:a,dataType:"html",data:n}).done(function(e){o=arguments,s.html(i?b("<div>").append(b.parseHTML(e)).find(i):e)}).complete(r&&function(e,t){s.each(r,o||[e.responseText,t,e])}),this},b.each(["ajaxStart","ajaxStop","ajaxComplete","ajaxError","ajaxSuccess","ajaxSend"],function(e,t){b.fn[t]=function(e){return this.on(t,e)}}),b.each(["get","post"],function(e,n){b[n]=function(e,r,i,o){return b.isFunction(r)&&(o=o||i,i=r,r=t),b.ajax({url:e,type:n,dataType:o,data:r,success:i})}}),b.extend({active:0,lastModified:{},etag:{},ajaxSettings:{url:yn,type:"GET",isLocal:Nn.test(mn[1]),global:!0,processData:!0,async:!0,contentType:"application/x-www-form-urlencoded; charset=UTF-8",accepts:{"*":Dn,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"},converters:{"* text":e.String,"text html":!0,"text json":b.parseJSON,"text xml":b.parseXML},flatOptions:{url:!0,context:!0}},ajaxSetup:function(e,t){return t?Mn(Mn(e,b.ajaxSettings),t):Mn(b.ajaxSettings,e)},ajaxPrefilter:Hn(An),ajaxTransport:Hn(jn),ajax:function(e,n){"object"==typeof e&&(n=e,e=t),n=n||{};var r,i,o,a,s,u,l,c,p=b.ajaxSetup({},n),f=p.context||p,d=p.context&&(f.nodeType||f.jquery)?b(f):b.event,h=b.Deferred(),g=b.Callbacks("once memory"),m=p.statusCode||{},y={},v={},x=0,T="canceled",N={readyState:0,getResponseHeader:function(e){var t;if(2===x){if(!c){c={};while(t=Tn.exec(a))c[t[1].toLowerCase()]=t[2]}t=c[e.toLowerCase()]}return null==t?null:t},getAllResponseHeaders:function(){return 2===x?a:null},setRequestHeader:function(e,t){var n=e.toLowerCase();return x||(e=v[n]=v[n]||e,y[e]=t),this},overrideMimeType:function(e){return x||(p.mimeType=e),this},statusCode:function(e){var t;if(e)if(2>x)for(t in e)m[t]=[m[t],e[t]];else N.always(e[N.status]);return this},abort:function(e){var t=e||T;return l&&l.abort(t),k(0,t),this}};if(h.promise(N).complete=g.add,N.success=N.done,N.error=N.fail,p.url=((e||p.url||yn)+"").replace(xn,"").replace(kn,mn[1]+"//"),p.type=n.method||n.type||p.method||p.type,p.dataTypes=b.trim(p.dataType||"*").toLowerCase().match(w)||[""],null==p.crossDomain&&(r=En.exec(p.url.toLowerCase()),p.crossDomain=!(!r||r[1]===mn[1]&&r[2]===mn[2]&&(r[3]||("http:"===r[1]?80:443))==(mn[3]||("http:"===mn[1]?80:443)))),p.data&&p.processData&&"string"!=typeof p.data&&(p.data=b.param(p.data,p.traditional)),qn(An,p,n,N),2===x)return N;u=p.global,u&&0===b.active++&&b.event.trigger("ajaxStart"),p.type=p.type.toUpperCase(),p.hasContent=!Cn.test(p.type),o=p.url,p.hasContent||(p.data&&(o=p.url+=(bn.test(o)?"&":"?")+p.data,delete p.data),p.cache===!1&&(p.url=wn.test(o)?o.replace(wn,"$1_="+vn++):o+(bn.test(o)?"&":"?")+"_="+vn++)),p.ifModified&&(b.lastModified[o]&&N.setRequestHeader("If-Modified-Since",b.lastModified[o]),b.etag[o]&&N.setRequestHeader("If-None-Match",b.etag[o])),(p.data&&p.hasContent&&p.contentType!==!1||n.contentType)&&N.setRequestHeader("Content-Type",p.contentType),N.setRequestHeader("Accept",p.dataTypes[0]&&p.accepts[p.dataTypes[0]]?p.accepts[p.dataTypes[0]]+("*"!==p.dataTypes[0]?", "+Dn+"; q=0.01":""):p.accepts["*"]);for(i in p.headers)N.setRequestHeader(i,p.headers[i]);if(p.beforeSend&&(p.beforeSend.call(f,N,p)===!1||2===x))return N.abort();T="abort";for(i in{success:1,error:1,complete:1})N[i](p[i]);if(l=qn(jn,p,n,N)){N.readyState=1,u&&d.trigger("ajaxSend",[N,p]),p.async&&p.timeout>0&&(s=setTimeout(function(){N.abort("timeout")},p.timeout));try{x=1,l.send(y,k)}catch(C){if(!(2>x))throw C;k(-1,C)}}else k(-1,"No Transport");function k(e,n,r,i){var c,y,v,w,T,C=n;2!==x&&(x=2,s&&clearTimeout(s),l=t,a=i||"",N.readyState=e>0?4:0,r&&(w=_n(p,N,r)),e>=200&&300>e||304===e?(p.ifModified&&(T=N.getResponseHeader("Last-Modified"),T&&(b.lastModified[o]=T),T=N.getResponseHeader("etag"),T&&(b.etag[o]=T)),204===e?(c=!0,C="nocontent"):304===e?(c=!0,C="notmodified"):(c=Fn(p,w),C=c.state,y=c.data,v=c.error,c=!v)):(v=C,(e||!C)&&(C="error",0>e&&(e=0))),N.status=e,N.statusText=(n||C)+"",c?h.resolveWith(f,[y,C,N]):h.rejectWith(f,[N,C,v]),N.statusCode(m),m=t,u&&d.trigger(c?"ajaxSuccess":"ajaxError",[N,p,c?y:v]),g.fireWith(f,[N,C]),u&&(d.trigger("ajaxComplete",[N,p]),--b.active||b.event.trigger("ajaxStop")))}return N},getScript:function(e,n){return b.get(e,t,n,"script")},getJSON:function(e,t,n){return b.get(e,t,n,"json")}});function _n(e,n,r){var i,o,a,s,u=e.contents,l=e.dataTypes,c=e.responseFields;for(s in c)s in r&&(n[c[s]]=r[s]);while("*"===l[0])l.shift(),o===t&&(o=e.mimeType||n.getResponseHeader("Content-Type"));if(o)for(s in u)if(u[s]&&u[s].test(o)){l.unshift(s);break}if(l[0]in r)a=l[0];else{for(s in r){if(!l[0]||e.converters[s+" "+l[0]]){a=s;break}i||(i=s)}a=a||i}return a?(a!==l[0]&&l.unshift(a),r[a]):t}function Fn(e,t){var n,r,i,o,a={},s=0,u=e.dataTypes.slice(),l=u[0];if(e.dataFilter&&(t=e.dataFilter(t,e.dataType)),u[1])for(i in e.converters)a[i.toLowerCase()]=e.converters[i];for(;r=u[++s];)if("*"!==r){if("*"!==l&&l!==r){if(i=a[l+" "+r]||a["* "+r],!i)for(n in a)if(o=n.split(" "),o[1]===r&&(i=a[l+" "+o[0]]||a["* "+o[0]])){i===!0?i=a[n]:a[n]!==!0&&(r=o[0],u.splice(s--,0,r));break}if(i!==!0)if(i&&e["throws"])t=i(t);else try{t=i(t)}catch(c){return{state:"parsererror",error:i?c:"No conversion from "+l+" to "+r}}}l=r}return{state:"success",data:t}}b.ajaxSetup({accepts:{script:"text/javascript, application/javascript, application/ecmascript, application/x-ecmascript"},contents:{script:/(?:java|ecma)script/},converters:{"text script":function(e){return b.globalEval(e),e}}}),b.ajaxPrefilter("script",function(e){e.cache===t&&(e.cache=!1),e.crossDomain&&(e.type="GET",e.global=!1)}),b.ajaxTransport("script",function(e){if(e.crossDomain){var n,r=o.head||b("head")[0]||o.documentElement;return{send:function(t,i){n=o.createElement("script"),n.async=!0,e.scriptCharset&&(n.charset=e.scriptCharset),n.src=e.url,n.onload=n.onreadystatechange=function(e,t){(t||!n.readyState||/loaded|complete/.test(n.readyState))&&(n.onload=n.onreadystatechange=null,n.parentNode&&n.parentNode.removeChild(n),n=null,t||i(200,"success"))},r.insertBefore(n,r.firstChild)},abort:function(){n&&n.onload(t,!0)}}}});var On=[],Bn=/(=)\?(?=&|$)|\?\?/;b.ajaxSetup({jsonp:"callback",jsonpCallback:function(){var e=On.pop()||b.expando+"_"+vn++;return this[e]=!0,e}}),b.ajaxPrefilter("json jsonp",function(n,r,i){var o,a,s,u=n.jsonp!==!1&&(Bn.test(n.url)?"url":"string"==typeof n.data&&!(n.contentType||"").indexOf("application/x-www-form-urlencoded")&&Bn.test(n.data)&&"data");return u||"jsonp"===n.dataTypes[0]?(o=n.jsonpCallback=b.isFunction(n.jsonpCallback)?n.jsonpCallback():n.jsonpCallback,u?n[u]=n[u].replace(Bn,"$1"+o):n.jsonp!==!1&&(n.url+=(bn.test(n.url)?"&":"?")+n.jsonp+"="+o),n.converters["script json"]=function(){return s||b.error(o+" was not called"),s[0]},n.dataTypes[0]="json",a=e[o],e[o]=function(){s=arguments},i.always(function(){e[o]=a,n[o]&&(n.jsonpCallback=r.jsonpCallback,On.push(o)),s&&b.isFunction(a)&&a(s[0]),s=a=t}),"script"):t});var Pn,Rn,Wn=0,$n=e.ActiveXObject&&function(){var e;for(e in Pn)Pn[e](t,!0)};function In(){try{return new e.XMLHttpRequest}catch(t){}}function zn(){try{return new e.ActiveXObject("Microsoft.XMLHTTP")}catch(t){}}b.ajaxSettings.xhr=e.ActiveXObject?function(){return!this.isLocal&&In()||zn()}:In,Rn=b.ajaxSettings.xhr(),b.support.cors=!!Rn&&"withCredentials"in Rn,Rn=b.support.ajax=!!Rn,Rn&&b.ajaxTransport(function(n){if(!n.crossDomain||b.support.cors){var r;return{send:function(i,o){var a,s,u=n.xhr();if(n.username?u.open(n.type,n.url,n.async,n.username,n.password):u.open(n.type,n.url,n.async),n.xhrFields)for(s in n.xhrFields)u[s]=n.xhrFields[s];n.mimeType&&u.overrideMimeType&&u.overrideMimeType(n.mimeType),n.crossDomain||i["X-Requested-With"]||(i["X-Requested-With"]="XMLHttpRequest");try{for(s in i)u.setRequestHeader(s,i[s])}catch(l){}u.send(n.hasContent&&n.data||null),r=function(e,i){var s,l,c,p;try{if(r&&(i||4===u.readyState))if(r=t,a&&(u.onreadystatechange=b.noop,$n&&delete Pn[a]),i)4!==u.readyState&&u.abort();else{p={},s=u.status,l=u.getAllResponseHeaders(),"string"==typeof u.responseText&&(p.text=u.responseText);try{c=u.statusText}catch(f){c=""}s||!n.isLocal||n.crossDomain?1223===s&&(s=204):s=p.text?200:404}}catch(d){i||o(-1,d)}p&&o(s,c,p,l)},n.async?4===u.readyState?setTimeout(r):(a=++Wn,$n&&(Pn||(Pn={},b(e).unload($n)),Pn[a]=r),u.onreadystatechange=r):r()},abort:function(){r&&r(t,!0)}}}});var Xn,Un,Vn=/^(?:toggle|show|hide)$/,Yn=RegExp("^(?:([+-])=|)("+x+")([a-z%]*)$","i"),Jn=/queueHooks$/,Gn=[nr],Qn={"*":[function(e,t){var n,r,i=this.createTween(e,t),o=Yn.exec(t),a=i.cur(),s=+a||0,u=1,l=20;if(o){if(n=+o[2],r=o[3]||(b.cssNumber[e]?"":"px"),"px"!==r&&s){s=b.css(i.elem,e,!0)||n||1;do u=u||".5",s/=u,b.style(i.elem,e,s+r);while(u!==(u=i.cur()/a)&&1!==u&&--l)}i.unit=r,i.start=s,i.end=o[1]?s+(o[1]+1)*n:n}return i}]};function Kn(){return setTimeout(function(){Xn=t}),Xn=b.now()}function Zn(e,t){b.each(t,function(t,n){var r=(Qn[t]||[]).concat(Qn["*"]),i=0,o=r.length;for(;o>i;i++)if(r[i].call(e,t,n))return})}function er(e,t,n){var r,i,o=0,a=Gn.length,s=b.Deferred().always(function(){delete u.elem}),u=function(){if(i)return!1;var t=Xn||Kn(),n=Math.max(0,l.startTime+l.duration-t),r=n/l.duration||0,o=1-r,a=0,u=l.tweens.length;for(;u>a;a++)l.tweens[a].run(o);return s.notifyWith(e,[l,o,n]),1>o&&u?n:(s.resolveWith(e,[l]),!1)},l=s.promise({elem:e,props:b.extend({},t),opts:b.extend(!0,{specialEasing:{}},n),originalProperties:t,originalOptions:n,startTime:Xn||Kn(),duration:n.duration,tweens:[],createTween:function(t,n){var r=b.Tween(e,l.opts,t,n,l.opts.specialEasing[t]||l.opts.easing);return l.tweens.push(r),r},stop:function(t){var n=0,r=t?l.tweens.length:0;if(i)return this;for(i=!0;r>n;n++)l.tweens[n].run(1);return t?s.resolveWith(e,[l,t]):s.rejectWith(e,[l,t]),this}}),c=l.props;for(tr(c,l.opts.specialEasing);a>o;o++)if(r=Gn[o].call(l,e,c,l.opts))return r;return Zn(l,c),b.isFunction(l.opts.start)&&l.opts.start.call(e,l),b.fx.timer(b.extend(u,{elem:e,anim:l,queue:l.opts.queue})),l.progress(l.opts.progress).done(l.opts.done,l.opts.complete).fail(l.opts.fail).always(l.opts.always)}function tr(e,t){var n,r,i,o,a;for(i in e)if(r=b.camelCase(i),o=t[r],n=e[i],b.isArray(n)&&(o=n[1],n=e[i]=n[0]),i!==r&&(e[r]=n,delete e[i]),a=b.cssHooks[r],a&&"expand"in a){n=a.expand(n),delete e[r];for(i in n)i in e||(e[i]=n[i],t[i]=o)}else t[r]=o}b.Animation=b.extend(er,{tweener:function(e,t){b.isFunction(e)?(t=e,e=["*"]):e=e.split(" ");var n,r=0,i=e.length;for(;i>r;r++)n=e[r],Qn[n]=Qn[n]||[],Qn[n].unshift(t)},prefilter:function(e,t){t?Gn.unshift(e):Gn.push(e)}});function nr(e,t,n){var r,i,o,a,s,u,l,c,p,f=this,d=e.style,h={},g=[],m=e.nodeType&&nn(e);n.queue||(c=b._queueHooks(e,"fx"),null==c.unqueued&&(c.unqueued=0,p=c.empty.fire,c.empty.fire=function(){c.unqueued||p()}),c.unqueued++,f.always(function(){f.always(function(){c.unqueued--,b.queue(e,"fx").length||c.empty.fire()})})),1===e.nodeType&&("height"in t||"width"in t)&&(n.overflow=[d.overflow,d.overflowX,d.overflowY],"inline"===b.css(e,"display")&&"none"===b.css(e,"float")&&(b.support.inlineBlockNeedsLayout&&"inline"!==un(e.nodeName)?d.zoom=1:d.display="inline-block")),n.overflow&&(d.overflow="hidden",b.support.shrinkWrapBlocks||f.always(function(){d.overflow=n.overflow[0],d.overflowX=n.overflow[1],d.overflowY=n.overflow[2]}));for(i in t)if(a=t[i],Vn.exec(a)){if(delete t[i],u=u||"toggle"===a,a===(m?"hide":"show"))continue;g.push(i)}if(o=g.length){s=b._data(e,"fxshow")||b._data(e,"fxshow",{}),"hidden"in s&&(m=s.hidden),u&&(s.hidden=!m),m?b(e).show():f.done(function(){b(e).hide()}),f.done(function(){var t;b._removeData(e,"fxshow");for(t in h)b.style(e,t,h[t])});for(i=0;o>i;i++)r=g[i],l=f.createTween(r,m?s[r]:0),h[r]=s[r]||b.style(e,r),r in s||(s[r]=l.start,m&&(l.end=l.start,l.start="width"===r||"height"===r?1:0))}}function rr(e,t,n,r,i){return new rr.prototype.init(e,t,n,r,i)}b.Tween=rr,rr.prototype={constructor:rr,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||(b.cssNumber[n]?"":"px")},cur:function(){var e=rr.propHooks[this.prop];return e&&e.get?e.get(this):rr.propHooks._default.get(this)},run:function(e){var t,n=rr.propHooks[this.prop];return this.pos=t=this.options.duration?b.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):rr.propHooks._default.set(this),this}},rr.prototype.init.prototype=rr.prototype,rr.propHooks={_default:{get:function(e){var t;return null==e.elem[e.prop]||e.elem.style&&null!=e.elem.style[e.prop]?(t=b.css(e.elem,e.prop,""),t&&"auto"!==t?t:0):e.elem[e.prop]},set:function(e){b.fx.step[e.prop]?b.fx.step[e.prop](e):e.elem.style&&(null!=e.elem.style[b.cssProps[e.prop]]||b.cssHooks[e.prop])?b.style(e.elem,e.prop,e.now+e.unit):e.elem[e.prop]=e.now}}},rr.propHooks.scrollTop=rr.propHooks.scrollLeft={set:function(e){e.elem.nodeType&&e.elem.parentNode&&(e.elem[e.prop]=e.now)}},b.each(["toggle","show","hide"],function(e,t){var n=b.fn[t];b.fn[t]=function(e,r,i){return null==e||"boolean"==typeof e?n.apply(this,arguments):this.animate(ir(t,!0),e,r,i)}}),b.fn.extend({fadeTo:function(e,t,n,r){return this.filter(nn).css("opacity",0).show().end().animate({opacity:t},e,n,r)},animate:function(e,t,n,r){var i=b.isEmptyObject(e),o=b.speed(t,n,r),a=function(){var t=er(this,b.extend({},e),o);a.finish=function(){t.stop(!0)},(i||b._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,n,r){var i=function(e){var t=e.stop;delete e.stop,t(r)};return"string"!=typeof e&&(r=n,n=e,e=t),n&&e!==!1&&this.queue(e||"fx",[]),this.each(function(){var t=!0,n=null!=e&&e+"queueHooks",o=b.timers,a=b._data(this);if(n)a[n]&&a[n].stop&&i(a[n]);else for(n in a)a[n]&&a[n].stop&&Jn.test(n)&&i(a[n]);for(n=o.length;n--;)o[n].elem!==this||null!=e&&o[n].queue!==e||(o[n].anim.stop(r),t=!1,o.splice(n,1));(t||!r)&&b.dequeue(this,e)})},finish:function(e){return e!==!1&&(e=e||"fx"),this.each(function(){var t,n=b._data(this),r=n[e+"queue"],i=n[e+"queueHooks"],o=b.timers,a=r?r.length:0;for(n.finish=!0,b.queue(this,e,[]),i&&i.cur&&i.cur.finish&&i.cur.finish.call(this),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})}});function ir(e,t){var n,r={height:e},i=0;for(t=t?1:0;4>i;i+=2-t)n=Zt[i],r["margin"+n]=r["padding"+n]=e;return t&&(r.opacity=r.width=e),r}b.each({slideDown:ir("show"),slideUp:ir("hide"),slideToggle:ir("toggle"),fadeIn:{opacity:"show"},fadeOut:{opacity:"hide"},fadeToggle:{opacity:"toggle"}},function(e,t){b.fn[e]=function(e,n,r){return this.animate(t,e,n,r)}}),b.speed=function(e,t,n){var r=e&&"object"==typeof e?b.extend({},e):{complete:n||!n&&t||b.isFunction(e)&&e,duration:e,easing:n&&t||t&&!b.isFunction(t)&&t};return r.duration=b.fx.off?0:"number"==typeof r.duration?r.duration:r.duration in b.fx.speeds?b.fx.speeds[r.duration]:b.fx.speeds._default,(null==r.queue||r.queue===!0)&&(r.queue="fx"),r.old=r.complete,r.complete=function(){b.isFunction(r.old)&&r.old.call(this),r.queue&&b.dequeue(this,r.queue)},r},b.easing={linear:function(e){return e},swing:function(e){return.5-Math.cos(e*Math.PI)/2}},b.timers=[],b.fx=rr.prototype.init,b.fx.tick=function(){var e,n=b.timers,r=0;for(Xn=b.now();n.length>r;r++)e=n[r],e()||n[r]!==e||n.splice(r--,1);n.length||b.fx.stop(),Xn=t},b.fx.timer=function(e){e()&&b.timers.push(e)&&b.fx.start()},b.fx.interval=13,b.fx.start=function(){Un||(Un=setInterval(b.fx.tick,b.fx.interval))},b.fx.stop=function(){clearInterval(Un),Un=null},b.fx.speeds={slow:600,fast:200,_default:400},b.fx.step={},b.expr&&b.expr.filters&&(b.expr.filters.animated=function(e){return b.grep(b.timers,function(t){return e===t.elem}).length}),b.fn.offset=function(e){if(arguments.length)return e===t?this:this.each(function(t){b.offset.setOffset(this,e,t)});var n,r,o={top:0,left:0},a=this[0],s=a&&a.ownerDocument;if(s)return n=s.documentElement,b.contains(n,a)?(typeof a.getBoundingClientRect!==i&&(o=a.getBoundingClientRect()),r=or(s),{top:o.top+(r.pageYOffset||n.scrollTop)-(n.clientTop||0),left:o.left+(r.pageXOffset||n.scrollLeft)-(n.clientLeft||0)}):o},b.offset={setOffset:function(e,t,n){var r=b.css(e,"position");"static"===r&&(e.style.position="relative");var i=b(e),o=i.offset(),a=b.css(e,"top"),s=b.css(e,"left"),u=("absolute"===r||"fixed"===r)&&b.inArray("auto",[a,s])>-1,l={},c={},p,f;u?(c=i.position(),p=c.top,f=c.left):(p=parseFloat(a)||0,f=parseFloat(s)||0),b.isFunction(t)&&(t=t.call(e,n,o)),null!=t.top&&(l.top=t.top-o.top+p),null!=t.left&&(l.left=t.left-o.left+f),"using"in t?t.using.call(e,l):i.css(l)}},b.fn.extend({position:function(){if(this[0]){var e,t,n={top:0,left:0},r=this[0];return"fixed"===b.css(r,"position")?t=r.getBoundingClientRect():(e=this.offsetParent(),t=this.offset(),b.nodeName(e[0],"html")||(n=e.offset()),n.top+=b.css(e[0],"borderTopWidth",!0),n.left+=b.css(e[0],"borderLeftWidth",!0)),{top:t.top-n.top-b.css(r,"marginTop",!0),left:t.left-n.left-b.css(r,"marginLeft",!0)}}},offsetParent:function(){return this.map(function(){var e=this.offsetParent||o.documentElement;while(e&&!b.nodeName(e,"html")&&"static"===b.css(e,"position"))e=e.offsetParent;return e||o.documentElement})}}),b.each({scrollLeft:"pageXOffset",scrollTop:"pageYOffset"},function(e,n){var r=/Y/.test(n);b.fn[e]=function(i){return b.access(this,function(e,i,o){var a=or(e);return o===t?a?n in a?a[n]:a.document.documentElement[i]:e[i]:(a?a.scrollTo(r?b(a).scrollLeft():o,r?o:b(a).scrollTop()):e[i]=o,t)},e,i,arguments.length,null)}});function or(e){return b.isWindow(e)?e:9===e.nodeType?e.defaultView||e.parentWindow:!1}b.each({Height:"height",Width:"width"},function(e,n){b.each({padding:"inner"+e,content:n,"":"outer"+e},function(r,i){b.fn[i]=function(i,o){var a=arguments.length&&(r||"boolean"!=typeof i),s=r||(i===!0||o===!0?"margin":"border");return b.access(this,function(n,r,i){var o;return b.isWindow(n)?n.document.documentElement["client"+e]:9===n.nodeType?(o=n.documentElement,Math.max(n.body["scroll"+e],o["scroll"+e],n.body["offset"+e],o["offset"+e],o["client"+e])):i===t?b.css(n,r,s):b.style(n,r,i,s)},n,a?i:t,a,null)}})}),e.jQuery=e.$=b,"function"==typeof define&&define.amd&&define.amd.jQuery&&define("jquery",[],function(){return b})})(window);
app/components/TwitterPicker/common/Swatch.js
juanda99/arasaac-frontend
import React from 'react' import reactCSS from 'reactcss' import { handleFocus } from '../helpers/interaction' import Checkboard from './Checkboard' const ENTER = 13 export const Swatch = ({ color, style, onClick = () => {}, onHover, title = color, children, focus, focusStyle = {} }) => { const transparent = color === 'transparent' const styles = reactCSS({ default: { swatch: { background: color, height: '100%', width: '100%', cursor: 'pointer', position: 'relative', outline: 'none', ...style, ...(focus ? focusStyle : {}) } } }) const handleClick = (e) => onClick(color, e) const handleKeyDown = (e) => e.keyCode === ENTER && onClick(color, e) const handleHover = (e) => onHover(color, e) const optionalEvents = {} if (onHover) { optionalEvents.onMouseOver = handleHover } return ( <div style={styles.swatch} onClick={handleClick} title={title} tabIndex={0} onKeyDown={handleKeyDown} {...optionalEvents} > {children} {transparent && ( <Checkboard borderRadius={styles.swatch.borderRadius} boxShadow='inset 0 0 0 1px rgba(0,0,0,0.1)' /> )} </div> ) } export default handleFocus(Swatch)
src/utils/ValidComponentChildren.js
leozdgao/react-bootstrap
import React from 'react'; /** * Maps children that are typically specified as `props.children`, * but only iterates 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)} mapFunction. * @param {*} mapContext Context for mapFunction. * @return {object} Object containing the ordered map of results. */ function mapValidComponents(children, func, context) { let index = 0; return React.Children.map(children, function (child) { if (React.isValidElement(child)) { let lastIndex = index; index++; return func.call(context, child, lastIndex); } return child; }); } /** * Iterates through 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)} forEachFunc. * @param {*} forEachContext Context for forEachContext. */ function forEachValidComponents(children, func, context) { let index = 0; return React.Children.forEach(children, function (child) { if (React.isValidElement(child)) { func.call(context, child, index); index++; } }); } /** * Count the number of "valid components" in the Children container. * * @param {?*} children Children tree container. * @returns {number} */ function numberOfValidComponents(children) { let count = 0; React.Children.forEach(children, function (child) { if (React.isValidElement(child)) { count++; } }); return count; } /** * Determine if the Child container has one or more "valid components". * * @param {?*} children Children tree container. * @returns {boolean} */ function hasValidComponent(children) { let hasValid = false; React.Children.forEach(children, function (child) { if (!hasValid && React.isValidElement(child)) { hasValid = true; } }); return hasValid; } export default { map: mapValidComponents, forEach: forEachValidComponents, numberOf: numberOfValidComponents, hasValidComponent };
app/javascript/mastodon/components/dropdown_menu.js
mimumemo/mastodon
import React from 'react'; import PropTypes from 'prop-types'; import ImmutablePropTypes from 'react-immutable-proptypes'; import IconButton from './icon_button'; import Overlay from 'react-overlays/lib/Overlay'; import Motion from '../features/ui/util/optional_motion'; import spring from 'react-motion/lib/spring'; import detectPassiveEvents from 'detect-passive-events'; const listenerOptions = detectPassiveEvents.hasSupport ? { passive: true } : false; let id = 0; class DropdownMenu extends React.PureComponent { static contextTypes = { router: PropTypes.object, }; static propTypes = { items: PropTypes.array.isRequired, onClose: PropTypes.func.isRequired, style: PropTypes.object, placement: PropTypes.string, arrowOffsetLeft: PropTypes.string, arrowOffsetTop: PropTypes.string, openedViaKeyboard: PropTypes.bool, }; static defaultProps = { style: {}, placement: 'bottom', }; state = { mounted: false, }; handleDocumentClick = e => { if (this.node && !this.node.contains(e.target)) { this.props.onClose(); } } componentDidMount () { document.addEventListener('click', this.handleDocumentClick, false); document.addEventListener('keydown', this.handleKeyDown, false); document.addEventListener('touchend', this.handleDocumentClick, listenerOptions); if (this.focusedItem && this.props.openedViaKeyboard) this.focusedItem.focus(); this.setState({ mounted: true }); } componentWillUnmount () { document.removeEventListener('click', this.handleDocumentClick, false); document.removeEventListener('keydown', this.handleKeyDown, false); document.removeEventListener('touchend', this.handleDocumentClick, listenerOptions); } setRef = c => { this.node = c; } setFocusRef = c => { this.focusedItem = c; } handleKeyDown = e => { const items = Array.from(this.node.getElementsByTagName('a')); const index = items.indexOf(document.activeElement); let element; switch(e.key) { case 'ArrowDown': element = items[index+1]; if (element) { element.focus(); } break; case 'ArrowUp': element = items[index-1]; if (element) { element.focus(); } break; case 'Home': element = items[0]; if (element) { element.focus(); } break; case 'End': element = items[items.length-1]; if (element) { element.focus(); } break; } } handleItemKeyDown = e => { if (e.key === 'Enter') { this.handleClick(e); } } handleClick = e => { const i = Number(e.currentTarget.getAttribute('data-index')); const { action, to } = this.props.items[i]; this.props.onClose(); if (typeof action === 'function') { e.preventDefault(); action(e); } else if (to) { e.preventDefault(); this.context.router.history.push(to); } } renderItem (option, i) { if (option === null) { return <li key={`sep-${i}`} className='dropdown-menu__separator' />; } const { text, href = '#' } = option; return ( <li className='dropdown-menu__item' key={`${text}-${i}`}> <a href={href} target='_blank' rel='noopener' role='button' tabIndex='0' ref={i === 0 ? this.setFocusRef : null} onClick={this.handleClick} onKeyDown={this.handleItemKeyDown} data-index={i}> {text} </a> </li> ); } render () { const { items, style, placement, arrowOffsetLeft, arrowOffsetTop } = this.props; const { mounted } = this.state; return ( <Motion defaultStyle={{ opacity: 0, scaleX: 0.85, scaleY: 0.75 }} style={{ opacity: spring(1, { damping: 35, stiffness: 400 }), scaleX: spring(1, { damping: 35, stiffness: 400 }), scaleY: spring(1, { damping: 35, stiffness: 400 }) }}> {({ opacity, scaleX, scaleY }) => ( // It should not be transformed when mounting because the resulting // size will be used to determine the coordinate of the menu by // react-overlays <div className={`dropdown-menu ${placement}`} style={{ ...style, opacity: opacity, transform: mounted ? `scale(${scaleX}, ${scaleY})` : null }} ref={this.setRef}> <div className={`dropdown-menu__arrow ${placement}`} style={{ left: arrowOffsetLeft, top: arrowOffsetTop }} /> <ul> {items.map((option, i) => this.renderItem(option, i))} </ul> </div> )} </Motion> ); } } export default class Dropdown extends React.PureComponent { static contextTypes = { router: PropTypes.object, }; static propTypes = { icon: PropTypes.string.isRequired, items: PropTypes.array.isRequired, size: PropTypes.number.isRequired, title: PropTypes.string, disabled: PropTypes.bool, status: ImmutablePropTypes.map, isUserTouching: PropTypes.func, isModalOpen: PropTypes.bool.isRequired, onOpen: PropTypes.func.isRequired, onClose: PropTypes.func.isRequired, dropdownPlacement: PropTypes.string, openDropdownId: PropTypes.number, openedViaKeyboard: PropTypes.bool, }; static defaultProps = { title: 'Menu', }; state = { id: id++, }; handleClick = ({ target, type }) => { if (this.state.id === this.props.openDropdownId) { this.handleClose(); } else { const { top } = target.getBoundingClientRect(); const placement = top * 2 < innerHeight ? 'bottom' : 'top'; this.props.onOpen(this.state.id, this.handleItemClick, placement, type !== 'click'); } } handleClose = () => { this.props.onClose(this.state.id); } handleKeyDown = e => { switch(e.key) { case ' ': case 'Enter': this.handleClick(e); e.preventDefault(); break; case 'Escape': this.handleClose(); break; } } handleItemClick = e => { const i = Number(e.currentTarget.getAttribute('data-index')); const { action, to } = this.props.items[i]; this.handleClose(); if (typeof action === 'function') { e.preventDefault(); action(); } else if (to) { e.preventDefault(); this.context.router.history.push(to); } } setTargetRef = c => { this.target = c; } findTarget = () => { return this.target; } componentWillUnmount = () => { if (this.state.id === this.props.openDropdownId) { this.handleClose(); } } render () { const { icon, items, size, title, disabled, dropdownPlacement, openDropdownId, openedViaKeyboard } = this.props; const open = this.state.id === openDropdownId; return ( <div onKeyDown={this.handleKeyDown}> <IconButton icon={icon} title={title} active={open} disabled={disabled} size={size} ref={this.setTargetRef} onClick={this.handleClick} /> <Overlay show={open} placement={dropdownPlacement} target={this.findTarget}> <DropdownMenu items={items} onClose={this.handleClose} openedViaKeyboard={openedViaKeyboard} /> </Overlay> </div> ); } }
ajax/libs/vue/1.0.19-csp/vue.common.js
AMoo-Miki/cdnjs
/*! * Vue.js v1.0.19-csp * (c) 2016 Evan You * Released under the MIT License. */ 'use strict'; function set(obj, key, val) { if (hasOwn(obj, key)) { obj[key] = val; return; } if (obj._isVue) { set(obj._data, key, val); return; } var ob = obj.__ob__; if (!ob) { obj[key] = val; return; } ob.convert(key, val); ob.dep.notify(); if (ob.vms) { var i = ob.vms.length; while (i--) { var vm = ob.vms[i]; vm._proxy(key); vm._digest(); } } return val; } /** * Delete a property and trigger change if necessary. * * @param {Object} obj * @param {String} key */ function del(obj, key) { if (!hasOwn(obj, key)) { return; } delete obj[key]; var ob = obj.__ob__; if (!ob) { return; } ob.dep.notify(); if (ob.vms) { var i = ob.vms.length; while (i--) { var vm = ob.vms[i]; vm._unproxy(key); vm._digest(); } } } var hasOwnProperty = Object.prototype.hasOwnProperty; /** * Check whether the object has the property. * * @param {Object} obj * @param {String} key * @return {Boolean} */ function hasOwn(obj, key) { return hasOwnProperty.call(obj, key); } /** * Check if an expression is a literal value. * * @param {String} exp * @return {Boolean} */ var literalValueRE = /^\s?(true|false|-?[\d\.]+|'[^']*'|"[^"]*")\s?$/; function isLiteral(exp) { return literalValueRE.test(exp); } /** * Check if a string starts with $ or _ * * @param {String} str * @return {Boolean} */ function isReserved(str) { var c = (str + '').charCodeAt(0); return c === 0x24 || c === 0x5F; } /** * Guard text output, make sure undefined outputs * empty string * * @param {*} value * @return {String} */ function _toString(value) { return value == null ? '' : value.toString(); } /** * Check and convert possible numeric strings to numbers * before setting back to data * * @param {*} value * @return {*|Number} */ function toNumber(value) { if (typeof value !== 'string') { return value; } else { var parsed = Number(value); return isNaN(parsed) ? value : parsed; } } /** * Convert string boolean literals into real booleans. * * @param {*} value * @return {*|Boolean} */ function toBoolean(value) { return value === 'true' ? true : value === 'false' ? false : value; } /** * Strip quotes from a string * * @param {String} str * @return {String | false} */ function stripQuotes(str) { var a = str.charCodeAt(0); var b = str.charCodeAt(str.length - 1); return a === b && (a === 0x22 || a === 0x27) ? str.slice(1, -1) : str; } /** * Camelize a hyphen-delmited string. * * @param {String} str * @return {String} */ var camelizeRE = /-(\w)/g; function camelize(str) { return str.replace(camelizeRE, toUpper); } function toUpper(_, c) { return c ? c.toUpperCase() : ''; } /** * Hyphenate a camelCase string. * * @param {String} str * @return {String} */ var hyphenateRE = /([a-z\d])([A-Z])/g; function hyphenate(str) { return str.replace(hyphenateRE, '$1-$2').toLowerCase(); } /** * Converts hyphen/underscore/slash delimitered names into * camelized classNames. * * e.g. my-component => MyComponent * some_else => SomeElse * some/comp => SomeComp * * @param {String} str * @return {String} */ var classifyRE = /(?:^|[-_\/])(\w)/g; function classify(str) { return str.replace(classifyRE, toUpper); } /** * Simple bind, faster than native * * @param {Function} fn * @param {Object} ctx * @return {Function} */ function bind(fn, ctx) { return function (a) { var l = arguments.length; return l ? l > 1 ? fn.apply(ctx, arguments) : fn.call(ctx, a) : fn.call(ctx); }; } /** * Convert an Array-like object to a real Array. * * @param {Array-like} list * @param {Number} [start] - start index * @return {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. * * @param {Object} to * @param {Object} from */ function extend(to, from) { var keys = Object.keys(from); var i = keys.length; while (i--) { to[keys[i]] = from[keys[i]]; } 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. * * @param {*} obj * @return {Boolean} */ function isObject(obj) { return obj !== null && typeof obj === 'object'; } /** * Strict object type check. Only returns true * for plain JavaScript objects. * * @param {*} obj * @return {Boolean} */ var toString = Object.prototype.toString; var OBJECT_STRING = '[object Object]'; function isPlainObject(obj) { return toString.call(obj) === OBJECT_STRING; } /** * Array type check. * * @param {*} obj * @return {Boolean} */ var isArray = Array.isArray; /** * Define a property. * * @param {Object} obj * @param {String} key * @param {*} val * @param {Boolean} [enumerable] */ function def(obj, key, val, enumerable) { Object.defineProperty(obj, key, { value: val, enumerable: !!enumerable, writable: true, configurable: true }); } /** * Debounce a function so it only gets called after the * input stops arriving after the given wait period. * * @param {Function} func * @param {Number} wait * @return {Function} - the debounced function */ function _debounce(func, wait) { var timeout, args, context, timestamp, result; var later = function later() { var last = Date.now() - timestamp; if (last < wait && last >= 0) { timeout = setTimeout(later, wait - last); } else { timeout = null; result = func.apply(context, args); if (!timeout) context = args = null; } }; return function () { context = this; args = arguments; timestamp = Date.now(); if (!timeout) { timeout = setTimeout(later, wait); } return result; }; } /** * Manual indexOf because it's slightly faster than * native. * * @param {Array} arr * @param {*} obj */ function indexOf(arr, obj) { var i = arr.length; while (i--) { if (arr[i] === obj) return i; } return -1; } /** * Make a cancellable version of an async callback. * * @param {Function} fn * @return {Function} */ function cancellable(fn) { var cb = function cb() { if (!cb.cancelled) { return fn.apply(this, arguments); } }; cb.cancel = function () { cb.cancelled = true; }; return cb; } /** * Check if two values are loosely equal - that is, * if they are plain objects, do they have the same shape? * * @param {*} a * @param {*} b * @return {Boolean} */ function looseEqual(a, b) { /* eslint-disable eqeqeq */ return a == b || (isObject(a) && isObject(b) ? JSON.stringify(a) === JSON.stringify(b) : false); /* eslint-enable eqeqeq */ } var hasProto = ('__proto__' in {}); // Browser environment sniffing var inBrowser = typeof window !== 'undefined' && Object.prototype.toString.call(window) !== '[object Object]'; // detect devtools var devtools = inBrowser && window.__VUE_DEVTOOLS_GLOBAL_HOOK__; // UA sniffing for working around browser-specific quirks var UA = inBrowser && window.navigator.userAgent.toLowerCase(); var isIE9 = UA && UA.indexOf('msie 9.0') > 0; var isAndroid = UA && UA.indexOf('android') > 0; var transitionProp = undefined; var transitionEndEvent = undefined; var animationProp = undefined; var animationEndEvent = undefined; // Transition property/event sniffing if (inBrowser && !isIE9) { var isWebkitTrans = window.ontransitionend === undefined && window.onwebkittransitionend !== undefined; var isWebkitAnim = window.onanimationend === undefined && window.onwebkitanimationend !== undefined; transitionProp = isWebkitTrans ? 'WebkitTransition' : 'transition'; transitionEndEvent = isWebkitTrans ? 'webkitTransitionEnd' : 'transitionend'; animationProp = isWebkitAnim ? 'WebkitAnimation' : 'animation'; animationEndEvent = isWebkitAnim ? 'webkitAnimationEnd' : 'animationend'; } /** * Defer a task to execute it asynchronously. Ideally this * should be executed as a microtask, so we leverage * MutationObserver if it's available, and fallback to * setTimeout(0). * * @param {Function} cb * @param {Object} ctx */ var nextTick = (function () { var callbacks = []; var pending = false; var timerFunc; function nextTickHandler() { pending = false; var copies = callbacks.slice(0); callbacks = []; for (var i = 0; i < copies.length; i++) { copies[i](); } } /* istanbul ignore if */ if (typeof MutationObserver !== 'undefined') { var counter = 1; var observer = new MutationObserver(nextTickHandler); var textNode = document.createTextNode(counter); observer.observe(textNode, { characterData: true }); timerFunc = function () { counter = (counter + 1) % 2; textNode.data = counter; }; } else { // webpack attempts to inject a shim for setImmediate // if it is used as a global, so we have to work around that to // avoid bundling unnecessary code. var context = inBrowser ? window : typeof global !== 'undefined' ? global : {}; timerFunc = context.setImmediate || setTimeout; } return function (cb, ctx) { var func = ctx ? function () { cb.call(ctx); } : cb; callbacks.push(func); if (pending) return; pending = true; timerFunc(nextTickHandler, 0); }; })(); function Cache(limit) { this.size = 0; this.limit = limit; this.head = this.tail = undefined; this._keymap = Object.create(null); } var p = Cache.prototype; /** * Put <value> into the cache associated with <key>. * Returns the entry which was removed to make room for * the new entry. Otherwise undefined is returned. * (i.e. if there was enough room already). * * @param {String} key * @param {*} value * @return {Entry|undefined} */ p.put = function (key, value) { var removed; if (this.size === this.limit) { removed = this.shift(); } var entry = this.get(key, true); if (!entry) { entry = { key: key }; this._keymap[key] = entry; if (this.tail) { this.tail.newer = entry; entry.older = this.tail; } else { this.head = entry; } this.tail = entry; this.size++; } entry.value = value; return removed; }; /** * Purge the least recently used (oldest) entry from the * cache. Returns the removed entry or undefined if the * cache was empty. */ p.shift = function () { var entry = this.head; if (entry) { this.head = this.head.newer; this.head.older = undefined; entry.newer = entry.older = undefined; this._keymap[entry.key] = undefined; this.size--; } return entry; }; /** * Get and register recent use of <key>. Returns the value * associated with <key> or undefined if not in cache. * * @param {String} key * @param {Boolean} returnEntry * @return {Entry|*} */ p.get = function (key, returnEntry) { var entry = this._keymap[key]; if (entry === undefined) return; if (entry === this.tail) { return returnEntry ? entry : entry.value; } // HEAD--------------TAIL // <.older .newer> // <--- add direction -- // A B C <D> E if (entry.newer) { if (entry === this.head) { this.head = entry.newer; } entry.newer.older = entry.older; // C <-- E. } if (entry.older) { entry.older.newer = entry.newer; // C. --> E } entry.newer = undefined; // D --x entry.older = this.tail; // D. --> E if (this.tail) { this.tail.newer = entry; // E. <-- D } this.tail = entry; return returnEntry ? entry : entry.value; }; var cache$1 = new Cache(1000); var filterTokenRE = /[^\s'"]+|'[^']*'|"[^"]*"/g; var reservedArgRE = /^in$|^-?\d+/; /** * Parser state */ var str; var dir; var c; var prev; var i; var l; var lastFilterIndex; var inSingle; var inDouble; var curly; var square; var paren; /** * Push a filter to the current directive object */ function pushFilter() { var exp = str.slice(lastFilterIndex, i).trim(); var filter; if (exp) { filter = {}; var tokens = exp.match(filterTokenRE); filter.name = tokens[0]; if (tokens.length > 1) { filter.args = tokens.slice(1).map(processFilterArg); } } if (filter) { (dir.filters = dir.filters || []).push(filter); } lastFilterIndex = i + 1; } /** * Check if an argument is dynamic and strip quotes. * * @param {String} arg * @return {Object} */ function processFilterArg(arg) { if (reservedArgRE.test(arg)) { return { value: toNumber(arg), dynamic: false }; } else { var stripped = stripQuotes(arg); var dynamic = stripped === arg; return { value: dynamic ? arg : stripped, dynamic: dynamic }; } } /** * Parse a directive value and extract the expression * and its filters into a descriptor. * * Example: * * "a + 1 | uppercase" will yield: * { * expression: 'a + 1', * filters: [ * { name: 'uppercase', args: null } * ] * } * * @param {String} s * @return {Object} */ function parseDirective(s) { var hit = cache$1.get(s); if (hit) { return hit; } // reset parser state str = s; inSingle = inDouble = false; curly = square = paren = 0; lastFilterIndex = 0; dir = {}; for (i = 0, l = str.length; i < l; i++) { prev = c; c = str.charCodeAt(i); if (inSingle) { // check single quote if (c === 0x27 && prev !== 0x5C) inSingle = !inSingle; } else if (inDouble) { // check double quote if (c === 0x22 && prev !== 0x5C) inDouble = !inDouble; } else if (c === 0x7C && // pipe str.charCodeAt(i + 1) !== 0x7C && str.charCodeAt(i - 1) !== 0x7C) { if (dir.expression == null) { // first filter, end of expression lastFilterIndex = i + 1; dir.expression = str.slice(0, i).trim(); } else { // already has filter pushFilter(); } } else { switch (c) { case 0x22: inDouble = true;break; // " case 0x27: inSingle = true;break; // ' case 0x28: paren++;break; // ( case 0x29: paren--;break; // ) case 0x5B: square++;break; // [ case 0x5D: square--;break; // ] case 0x7B: curly++;break; // { case 0x7D: curly--;break; // } } } } if (dir.expression == null) { dir.expression = str.slice(0, i).trim(); } else if (lastFilterIndex !== 0) { pushFilter(); } cache$1.put(s, dir); return dir; } var directive = Object.freeze({ parseDirective: parseDirective }); var regexEscapeRE = /[-.*+?^${}()|[\]\/\\]/g; var cache = undefined; var tagRE = undefined; var htmlRE = undefined; /** * Escape a string so it can be used in a RegExp * constructor. * * @param {String} str */ function escapeRegex(str) { return str.replace(regexEscapeRE, '\\$&'); } function compileRegex() { var open = escapeRegex(config.delimiters[0]); var close = escapeRegex(config.delimiters[1]); var unsafeOpen = escapeRegex(config.unsafeDelimiters[0]); var unsafeClose = escapeRegex(config.unsafeDelimiters[1]); tagRE = new RegExp(unsafeOpen + '(.+?)' + unsafeClose + '|' + open + '(.+?)' + close, 'g'); htmlRE = new RegExp('^' + unsafeOpen + '.*' + unsafeClose + '$'); // reset cache cache = new Cache(1000); } /** * Parse a template text string into an array of tokens. * * @param {String} text * @return {Array<Object> | null} * - {String} type * - {String} value * - {Boolean} [html] * - {Boolean} [oneTime] */ function parseText(text) { if (!cache) { compileRegex(); } var hit = cache.get(text); if (hit) { return hit; } text = text.replace(/\n/g, ''); if (!tagRE.test(text)) { return null; } var tokens = []; var lastIndex = tagRE.lastIndex = 0; var match, index, html, value, first, oneTime; /* eslint-disable no-cond-assign */ while (match = tagRE.exec(text)) { /* eslint-enable no-cond-assign */ index = match.index; // push text token if (index > lastIndex) { tokens.push({ value: text.slice(lastIndex, index) }); } // tag token html = htmlRE.test(match[0]); value = html ? match[1] : match[2]; first = value.charCodeAt(0); oneTime = first === 42; // * value = oneTime ? value.slice(1) : value; tokens.push({ tag: true, value: value.trim(), html: html, oneTime: oneTime }); lastIndex = index + match[0].length; } if (lastIndex < text.length) { tokens.push({ value: text.slice(lastIndex) }); } cache.put(text, tokens); return tokens; } /** * Format a list of tokens into an expression. * e.g. tokens parsed from 'a {{b}} c' can be serialized * into one single expression as '"a " + b + " c"'. * * @param {Array} tokens * @param {Vue} [vm] * @return {String} */ function tokensToExp(tokens, vm) { if (tokens.length > 1) { return tokens.map(function (token) { return formatToken(token, vm); }).join('+'); } else { return formatToken(tokens[0], vm, true); } } /** * Format a single token. * * @param {Object} token * @param {Vue} [vm] * @param {Boolean} [single] * @return {String} */ function formatToken(token, vm, single) { return token.tag ? token.oneTime && vm ? '"' + vm.$eval(token.value) + '"' : inlineFilters(token.value, single) : '"' + token.value + '"'; } /** * For an attribute with multiple interpolation tags, * e.g. attr="some-{{thing | filter}}", in order to combine * the whole thing into a single watchable expression, we * have to inline those filters. This function does exactly * that. This is a bit hacky but it avoids heavy changes * to directive parser and watcher mechanism. * * @param {String} exp * @param {Boolean} single * @return {String} */ var filterRE = /[^|]\|[^|]/; function inlineFilters(exp, single) { if (!filterRE.test(exp)) { return single ? exp : '(' + exp + ')'; } else { var dir = parseDirective(exp); if (!dir.filters) { return '(' + exp + ')'; } else { return 'this._applyFilters(' + dir.expression + // value ',null,' + // oldValue (null for read) JSON.stringify(dir.filters) + // filter descriptors ',false)'; // write? } } } var text = Object.freeze({ compileRegex: compileRegex, parseText: parseText, tokensToExp: tokensToExp }); var delimiters = ['{{', '}}']; var unsafeDelimiters = ['{{{', '}}}']; var config = Object.defineProperties({ /** * Whether to print debug messages. * Also enables stack trace for warnings. * * @type {Boolean} */ debug: false, /** * Whether to suppress warnings. * * @type {Boolean} */ silent: false, /** * Whether to use async rendering. */ async: true, /** * Whether to warn against errors caught when evaluating * expressions. */ warnExpressionErrors: true, /** * Whether to allow devtools inspection. * Disabled by default in production builds. */ devtools: process.env.NODE_ENV !== 'production', /** * Internal flag to indicate the delimiters have been * changed. * * @type {Boolean} */ _delimitersChanged: true, /** * List of asset types that a component can own. * * @type {Array} */ _assetTypes: ['component', 'directive', 'elementDirective', 'filter', 'transition', 'partial'], /** * prop binding modes */ _propBindingModes: { ONE_WAY: 0, TWO_WAY: 1, ONE_TIME: 2 }, /** * Max circular updates allowed in a batcher flush cycle. */ _maxUpdateCount: 100 }, { delimiters: { /** * Interpolation delimiters. Changing these would trigger * the text parser to re-compile the regular expressions. * * @type {Array<String>} */ get: function get() { return delimiters; }, set: function set(val) { delimiters = val; compileRegex(); }, configurable: true, enumerable: true }, unsafeDelimiters: { get: function get() { return unsafeDelimiters; }, set: function set(val) { unsafeDelimiters = val; compileRegex(); }, configurable: true, enumerable: true } }); var warn = undefined; if (process.env.NODE_ENV !== 'production') { (function () { var hasConsole = typeof console !== 'undefined'; warn = function (msg, e) { if (hasConsole && (!config.silent || config.debug)) { console.warn('[Vue warn]: ' + msg); /* istanbul ignore if */ if (config.debug) { if (e) { throw e; } else { console.warn(new Error('Warning Stack Trace').stack); } } } }; })(); } /** * Append with transition. * * @param {Element} el * @param {Element} target * @param {Vue} vm * @param {Function} [cb] */ function appendWithTransition(el, target, vm, cb) { applyTransition(el, 1, function () { target.appendChild(el); }, vm, cb); } /** * InsertBefore with transition. * * @param {Element} el * @param {Element} target * @param {Vue} vm * @param {Function} [cb] */ function beforeWithTransition(el, target, vm, cb) { applyTransition(el, 1, function () { before(el, target); }, vm, cb); } /** * Remove with transition. * * @param {Element} el * @param {Vue} vm * @param {Function} [cb] */ function removeWithTransition(el, vm, cb) { applyTransition(el, -1, function () { remove(el); }, vm, cb); } /** * Apply transitions with an operation callback. * * @param {Element} el * @param {Number} direction * 1: enter * -1: leave * @param {Function} op - the actual DOM operation * @param {Vue} vm * @param {Function} [cb] */ function applyTransition(el, direction, op, vm, cb) { var transition = el.__v_trans; if (!transition || // skip if there are no js hooks and CSS transition is // not supported !transition.hooks && !transitionEndEvent || // skip transitions for initial compile !vm._isCompiled || // if the vm is being manipulated by a parent directive // during the parent's compilation phase, skip the // animation. vm.$parent && !vm.$parent._isCompiled) { op(); if (cb) cb(); return; } var action = direction > 0 ? 'enter' : 'leave'; transition[action](op, cb); } var transition = Object.freeze({ appendWithTransition: appendWithTransition, beforeWithTransition: beforeWithTransition, removeWithTransition: removeWithTransition, applyTransition: applyTransition }); /** * Query an element selector if it's not an element already. * * @param {String|Element} el * @return {Element} */ 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 el; } /** * Check if a node is in the document. * Note: document.documentElement.contains should work here * but always returns false for comment nodes in phantomjs, * making unit tests difficult. This is fixed by doing the * contains() check on the node's parentNode instead of * the node itself. * * @param {Node} node * @return {Boolean} */ function inDoc(node) { var doc = document.documentElement; var parent = node && node.parentNode; return doc === node || doc === parent || !!(parent && parent.nodeType === 1 && doc.contains(parent)); } /** * Get and remove an attribute from a node. * * @param {Node} node * @param {String} _attr */ function getAttr(node, _attr) { var val = node.getAttribute(_attr); if (val !== null) { node.removeAttribute(_attr); } return val; } /** * Get an attribute with colon or v-bind: prefix. * * @param {Node} node * @param {String} name * @return {String|null} */ function getBindAttr(node, name) { var val = getAttr(node, ':' + name); if (val === null) { val = getAttr(node, 'v-bind:' + name); } return val; } /** * Check the presence of a bind attribute. * * @param {Node} node * @param {String} name * @return {Boolean} */ function hasBindAttr(node, name) { return node.hasAttribute(name) || node.hasAttribute(':' + name) || node.hasAttribute('v-bind:' + name); } /** * Insert el before target * * @param {Element} el * @param {Element} target */ function before(el, target) { target.parentNode.insertBefore(el, target); } /** * Insert el after target * * @param {Element} el * @param {Element} target */ function after(el, target) { if (target.nextSibling) { before(el, target.nextSibling); } else { target.parentNode.appendChild(el); } } /** * Remove el from DOM * * @param {Element} el */ function remove(el) { el.parentNode.removeChild(el); } /** * Prepend el to target * * @param {Element} el * @param {Element} target */ function prepend(el, target) { if (target.firstChild) { before(el, target.firstChild); } else { target.appendChild(el); } } /** * Replace target with el * * @param {Element} target * @param {Element} el */ function replace(target, el) { var parent = target.parentNode; if (parent) { parent.replaceChild(el, target); } } /** * Add event listener shorthand. * * @param {Element} el * @param {String} event * @param {Function} cb * @param {Boolean} [useCapture] */ function on(el, event, cb, useCapture) { el.addEventListener(event, cb, useCapture); } /** * Remove event listener shorthand. * * @param {Element} el * @param {String} event * @param {Function} cb */ function off(el, event, cb) { el.removeEventListener(event, cb); } /** * For IE9 compat: when both class and :class are present * getAttribute('class') returns wrong value... * * @param {Element} el * @return {String} */ function getClass(el) { var classname = el.className; if (typeof classname === 'object') { classname = classname.baseVal || ''; } return classname; } /** * In IE9, setAttribute('class') will result in empty class * if the element also has the :class attribute; However in * PhantomJS, setting `className` does not work on SVG elements... * So we have to do a conditional check here. * * @param {Element} el * @param {String} cls */ function setClass(el, cls) { /* istanbul ignore if */ if (isIE9 && !/svg$/.test(el.namespaceURI)) { el.className = cls; } else { el.setAttribute('class', cls); } } /** * Add class with compatibility for IE & SVG * * @param {Element} el * @param {String} cls */ function addClass(el, cls) { if (el.classList) { el.classList.add(cls); } else { var cur = ' ' + getClass(el) + ' '; if (cur.indexOf(' ' + cls + ' ') < 0) { setClass(el, (cur + cls).trim()); } } } /** * Remove class with compatibility for IE & SVG * * @param {Element} el * @param {String} cls */ function removeClass(el, cls) { if (el.classList) { el.classList.remove(cls); } else { var cur = ' ' + getClass(el) + ' '; var tar = ' ' + cls + ' '; while (cur.indexOf(tar) >= 0) { cur = cur.replace(tar, ' '); } setClass(el, cur.trim()); } if (!el.className) { el.removeAttribute('class'); } } /** * Extract raw content inside an element into a temporary * container div * * @param {Element} el * @param {Boolean} asFragment * @return {Element|DocumentFragment} */ function extractContent(el, asFragment) { var child; var rawContent; /* istanbul ignore if */ if (isTemplate(el) && isFragment(el.content)) { el = el.content; } if (el.hasChildNodes()) { trimNode(el); rawContent = asFragment ? document.createDocumentFragment() : document.createElement('div'); /* eslint-disable no-cond-assign */ while (child = el.firstChild) { /* eslint-enable no-cond-assign */ rawContent.appendChild(child); } } return rawContent; } /** * Trim possible empty head/tail text and comment * nodes inside a parent. * * @param {Node} node */ function trimNode(node) { var child; /* eslint-disable no-sequences */ while ((child = node.firstChild, isTrimmable(child))) { node.removeChild(child); } while ((child = node.lastChild, isTrimmable(child))) { node.removeChild(child); } /* eslint-enable no-sequences */ } function isTrimmable(node) { return node && (node.nodeType === 3 && !node.data.trim() || node.nodeType === 8); } /** * Check if an element is a template tag. * Note if the template appears inside an SVG its tagName * will be in lowercase. * * @param {Element} el */ function isTemplate(el) { return el.tagName && el.tagName.toLowerCase() === 'template'; } /** * Create an "anchor" for performing dom insertion/removals. * This is used in a number of scenarios: * - fragment instance * - v-html * - v-if * - v-for * - component * * @param {String} content * @param {Boolean} persist - IE trashes empty textNodes on * cloneNode(true), so in certain * cases the anchor needs to be * non-empty to be persisted in * templates. * @return {Comment|Text} */ function createAnchor(content, persist) { var anchor = config.debug ? document.createComment(content) : document.createTextNode(persist ? ' ' : ''); anchor.__v_anchor = true; return anchor; } /** * Find a component ref attribute that starts with $. * * @param {Element} node * @return {String|undefined} */ var refRE = /^v-ref:/; function findRef(node) { if (node.hasAttributes()) { var attrs = node.attributes; for (var i = 0, l = attrs.length; i < l; i++) { var name = attrs[i].name; if (refRE.test(name)) { return camelize(name.replace(refRE, '')); } } } } /** * Map a function to a range of nodes . * * @param {Node} node * @param {Node} end * @param {Function} op */ function mapNodeRange(node, end, op) { var next; while (node !== end) { next = node.nextSibling; op(node); node = next; } op(end); } /** * Remove a range of nodes with transition, store * the nodes in a fragment with correct ordering, * and call callback when done. * * @param {Node} start * @param {Node} end * @param {Vue} vm * @param {DocumentFragment} frag * @param {Function} cb */ function removeNodeRange(start, end, vm, frag, cb) { var done = false; var removed = 0; var nodes = []; mapNodeRange(start, end, function (node) { if (node === end) done = true; nodes.push(node); removeWithTransition(node, vm, onRemoved); }); function onRemoved() { removed++; if (done && removed >= nodes.length) { for (var i = 0; i < nodes.length; i++) { frag.appendChild(nodes[i]); } cb && cb(); } } } /** * Check if a node is a DocumentFragment. * * @param {Node} node * @return {Boolean} */ function isFragment(node) { return node && node.nodeType === 11; } /** * Get outerHTML of elements, taking care * of SVG elements in IE as well. * * @param {Element} el * @return {String} */ function getOuterHTML(el) { if (el.outerHTML) { return el.outerHTML; } else { var container = document.createElement('div'); container.appendChild(el.cloneNode(true)); return container.innerHTML; } } var commonTagRE = /^(div|p|span|img|a|b|i|br|ul|ol|li|h1|h2|h3|h4|h5|h6|code|pre|table|th|td|tr|form|label|input|select|option|nav|article|section|header|footer)$/i; var reservedTagRE = /^(slot|partial|component)$/i; var isUnknownElement = undefined; if (process.env.NODE_ENV !== 'production') { isUnknownElement = function (el, tag) { if (tag.indexOf('-') > -1) { // http://stackoverflow.com/a/28210364/1070244 return el.constructor === window.HTMLUnknownElement || el.constructor === window.HTMLElement; } else { return (/HTMLUnknownElement/.test(el.toString()) && // Chrome returns unknown for several HTML5 elements. // https://code.google.com/p/chromium/issues/detail?id=540526 !/^(data|time|rtc|rb)$/.test(tag) ); } }; } /** * Check if an element is a component, if yes return its * component id. * * @param {Element} el * @param {Object} options * @return {Object|undefined} */ function checkComponentAttr(el, options) { var tag = el.tagName.toLowerCase(); var hasAttrs = el.hasAttributes(); if (!commonTagRE.test(tag) && !reservedTagRE.test(tag)) { if (resolveAsset(options, 'components', tag)) { return { id: tag }; } else { var is = hasAttrs && getIsBinding(el); if (is) { return is; } else if (process.env.NODE_ENV !== 'production') { var expectedTag = options._componentNameMap && options._componentNameMap[tag]; if (expectedTag) { warn('Unknown custom element: <' + tag + '> - ' + 'did you mean <' + expectedTag + '>? ' + 'HTML is case-insensitive, remember to use kebab-case in templates.'); } else if (isUnknownElement(el, tag)) { warn('Unknown custom element: <' + tag + '> - did you ' + 'register the component correctly? For recursive components, ' + 'make sure to provide the "name" option.'); } } } } else if (hasAttrs) { return getIsBinding(el); } } /** * Get "is" binding from an element. * * @param {Element} el * @return {Object|undefined} */ function getIsBinding(el) { // dynamic syntax var exp = getAttr(el, 'is'); if (exp != null) { return { id: exp }; } else { exp = getBindAttr(el, 'is'); if (exp != null) { return { id: exp, dynamic: true }; } } } /** * Option overwriting strategies are functions that handle * how to merge a parent option value and a child option * value into the final value. * * All strategy functions follow the same signature: * * @param {*} parentVal * @param {*} childVal * @param {Vue} [vm] */ var strats = config.optionMergeStrategies = Object.create(null); /** * 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.'); 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; } }; } }; /** * El */ strats.el = function (parentVal, childVal, vm) { if (!vm && childVal && typeof childVal !== 'function') { process.env.NODE_ENV !== 'production' && warn('The "el" option should be a function ' + 'that returns a per-instance value in component ' + 'definitions.'); return; } var ret = childVal || parentVal; // invoke the element factory if this is instance merge return vm && typeof ret === 'function' ? ret.call(vm) : ret; }; /** * Hooks and param attributes are merged as arrays. */ strats.init = strats.created = strats.ready = strats.attached = strats.detached = strats.beforeCompile = strats.compiled = strats.beforeDestroy = strats.destroyed = strats.activate = function (parentVal, childVal) { return childVal ? parentVal ? parentVal.concat(childVal) : isArray(childVal) ? childVal : [childVal] : parentVal; }; /** * 0.11 deprecation warning */ strats.paramAttributes = function () { /* istanbul ignore next */ process.env.NODE_ENV !== 'production' && warn('"paramAttributes" option has been deprecated in 0.12. ' + 'Use "props" instead.'); }; /** * 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); return childVal ? extend(res, guardArrayAssets(childVal)) : res; } config._assetTypes.forEach(function (type) { strats[type + 's'] = mergeAssets; }); /** * Events & Watchers. * * Events & watchers hashes should not overwrite one * another, so we merge them as arrays. */ strats.watch = strats.events = function (parentVal, childVal) { 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 && !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 defaultStrat(parentVal, childVal) { return childVal === undefined ? parentVal : childVal; }; /** * Make sure component options get converted to actual * constructors. * * @param {Object} options */ function guardComponents(options) { if (options.components) { var components = options.components = guardArrayAssets(options.components); var ids = Object.keys(components); var def; if (process.env.NODE_ENV !== 'production') { var map = options._componentNameMap = {}; } for (var i = 0, l = ids.length; i < l; i++) { var key = ids[i]; if (commonTagRE.test(key) || reservedTagRE.test(key)) { process.env.NODE_ENV !== 'production' && warn('Do not use built-in or reserved HTML elements as component ' + 'id: ' + key); continue; } // record a all lowercase <-> kebab-case mapping for // possible custom element case error warning if (process.env.NODE_ENV !== 'production') { map[key.replace(/-/g, '').toLowerCase()] = hyphenate(key); } def = components[key]; if (isPlainObject(def)) { components[key] = Vue.extend(def); } } } } /** * Ensure all props option syntax are normalized into the * Object-based format. * * @param {Object} options */ function guardProps(options) { var props = options.props; var i, val; if (isArray(props)) { options.props = {}; i = props.length; while (i--) { val = props[i]; if (typeof val === 'string') { options.props[val] = null; } else if (val.name) { options.props[val.name] = val; } } } else if (isPlainObject(props)) { var keys = Object.keys(props); i = keys.length; while (i--) { val = props[keys[i]]; if (typeof val === 'function') { props[keys[i]] = { type: val }; } } } } /** * Guard an Array-format assets option and converted it * into the key-value Object format. * * @param {Object|Array} assets * @return {Object} */ function guardArrayAssets(assets) { if (isArray(assets)) { var res = {}; var i = assets.length; var asset; while (i--) { asset = assets[i]; var id = typeof asset === 'function' ? asset.options && asset.options.name || asset.id : asset.name || asset.id; if (!id) { process.env.NODE_ENV !== 'production' && warn('Array-syntax assets must provide a "name" or "id" field.'); } else { res[id] = asset; } } return res; } return assets; } /** * Merge two option objects into a new one. * Core utility used in both instantiation and inheritance. * * @param {Object} parent * @param {Object} child * @param {Vue} [vm] - if vm is present, indicates this is * an instantiation merge. */ function mergeOptions(parent, child, vm) { guardComponents(child); guardProps(child); var options = {}; var key; if (child.mixins) { for (var i = 0, l = child.mixins.length; i < l; i++) { parent = mergeOptions(parent, child.mixins[i], vm); } } 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. * * @param {Object} options * @param {String} type * @param {String} id * @return {Object|Function} */ function resolveAsset(options, type, id) { /* istanbul ignore if */ if (typeof id !== 'string') { return; } var assets = options[type]; var camelizedId; return assets[id] || // camelCase ID assets[camelizedId = camelize(id)] || // Pascal Case ID assets[camelizedId.charAt(0).toUpperCase() + camelizedId.slice(1)]; } /** * Assert asset exists */ function assertAsset(val, type, id) { if (!val) { process.env.NODE_ENV !== 'production' && warn('Failed to resolve ' + type + ': ' + id); } } var uid$1 = 0; /** * A dep is an observable that can have multiple * directives subscribing to it. * * @constructor */ function Dep() { this.id = uid$1++; this.subs = []; } // 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; /** * Add a directive subscriber. * * @param {Directive} sub */ Dep.prototype.addSub = function (sub) { this.subs.push(sub); }; /** * Remove a directive subscriber. * * @param {Directive} sub */ Dep.prototype.removeSub = function (sub) { this.subs.$remove(sub); }; /** * Add self as a dependency to the target watcher. */ Dep.prototype.depend = function () { Dep.target.addDep(this); }; /** * Notify all subscribers of a new value. */ Dep.prototype.notify = function () { // stablize the subscriber list first var subs = toArray(this.subs); for (var i = 0, l = subs.length; i < l; i++) { subs[i].update(); } }; var arrayProto = Array.prototype; var arrayMethods = Object.create(arrayProto) /** * Intercept mutating methods and emit events */ ;['push', 'pop', 'shift', 'unshift', 'splice', 'sort', 'reverse'].forEach(function (method) { // cache original method var original = arrayProto[method]; def(arrayMethods, method, function mutator() { // avoid leaking arguments: // http://jsperf.com/closure-with-arguments var i = arguments.length; var args = new Array(i); while (i--) { args[i] = arguments[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; }); }); /** * Swap the element at the given index with a new value * and emits corresponding event. * * @param {Number} index * @param {*} val * @return {*} - replaced element */ def(arrayProto, '$set', function $set(index, val) { if (index >= this.length) { this.length = Number(index) + 1; } return this.splice(index, 1, val)[0]; }); /** * Convenience method to remove the element at given index. * * @param {Number} index * @param {*} val */ def(arrayProto, '$remove', function $remove(item) { /* istanbul ignore if */ if (!this.length) return; var index = indexOf(this, item); if (index > -1) { return this.splice(index, 1); } }); var arrayKeys = Object.getOwnPropertyNames(arrayMethods); /** * 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. * * @param {Array|Object} value * @constructor */ function Observer(value) { this.value = value; this.dep = new Dep(); def(value, '__ob__', this); if (isArray(value)) { var augment = hasProto ? protoAugment : copyAugment; augment(value, arrayMethods, arrayKeys); this.observeArray(value); } else { this.walk(value); } } // Instance methods /** * Walk through each property and convert them into * getter/setters. This method should only be called when * value type is Object. * * @param {Object} obj */ Observer.prototype.walk = function (obj) { var keys = Object.keys(obj); for (var i = 0, l = keys.length; i < l; i++) { this.convert(keys[i], obj[keys[i]]); } }; /** * Observe a list of Array items. * * @param {Array} items */ Observer.prototype.observeArray = function (items) { for (var i = 0, l = items.length; i < l; i++) { observe(items[i]); } }; /** * Convert a property into getter/setter so we can emit * the events when the property is accessed/changed. * * @param {String} key * @param {*} val */ Observer.prototype.convert = function (key, val) { defineReactive(this.value, key, val); }; /** * Add an owner vm, so that when $set/$delete mutations * happen we can notify owner vms to proxy the keys and * digest the watchers. This is only called when the object * is observed as an instance's root $data. * * @param {Vue} vm */ Observer.prototype.addVm = function (vm) { (this.vms || (this.vms = [])).push(vm); }; /** * Remove an owner vm. This is called when the object is * swapped out as an instance's $data object. * * @param {Vue} vm */ Observer.prototype.removeVm = function (vm) { this.vms.$remove(vm); }; // helpers /** * Augment an target Object or Array by intercepting * the prototype chain using __proto__ * * @param {Object|Array} target * @param {Object} src */ 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. * * @param {Object|Array} target * @param {Object} proto */ 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. * * @param {*} value * @param {Vue} [vm] * @return {Observer|undefined} * @static */ function observe(value, vm) { if (!value || typeof value !== 'object') { return; } var ob; if (hasOwn(value, '__ob__') && value.__ob__ instanceof Observer) { ob = value.__ob__; } else if ((isArray(value) || isPlainObject(value)) && Object.isExtensible(value) && !value._isVue) { ob = new Observer(value); } if (ob && vm) { ob.addVm(vm); } return ob; } /** * Define a reactive property on an Object. * * @param {Object} obj * @param {String} key * @param {*} val * @param {Boolean} doNotObserve */ function defineReactive(obj, key, val, doNotObserve) { 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; // if doNotObserve is true, only use the child value observer // if it already exists, and do not attempt to create it. // this allows freezing a large object from the root and // avoid unnecessary observation inside v-for fragments. var childOb = doNotObserve ? isObject(val) && val.__ob__ : 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 (isArray(value)) { for (var e, i = 0, l = value.length; i < l; i++) { e = value[i]; e && e.__ob__ && e.__ob__.dep.depend(); } } } return value; }, set: function reactiveSetter(newVal) { var value = getter ? getter.call(obj) : val; if (newVal === value) { return; } if (setter) { setter.call(obj, newVal); } else { val = newVal; } childOb = doNotObserve ? isObject(newVal) && newVal.__ob__ : observe(newVal); dep.notify(); } }); } var util = Object.freeze({ defineReactive: defineReactive, set: set, del: del, hasOwn: hasOwn, isLiteral: isLiteral, isReserved: isReserved, _toString: _toString, toNumber: toNumber, toBoolean: toBoolean, stripQuotes: stripQuotes, camelize: camelize, hyphenate: hyphenate, classify: classify, bind: bind, toArray: toArray, extend: extend, isObject: isObject, isPlainObject: isPlainObject, def: def, debounce: _debounce, indexOf: indexOf, cancellable: cancellable, looseEqual: looseEqual, isArray: isArray, hasProto: hasProto, inBrowser: inBrowser, devtools: devtools, isIE9: isIE9, isAndroid: isAndroid, get transitionProp () { return transitionProp; }, get transitionEndEvent () { return transitionEndEvent; }, get animationProp () { return animationProp; }, get animationEndEvent () { return animationEndEvent; }, nextTick: nextTick, query: query, inDoc: inDoc, getAttr: getAttr, getBindAttr: getBindAttr, hasBindAttr: hasBindAttr, before: before, after: after, remove: remove, prepend: prepend, replace: replace, on: on, off: off, setClass: setClass, addClass: addClass, removeClass: removeClass, extractContent: extractContent, trimNode: trimNode, isTemplate: isTemplate, createAnchor: createAnchor, findRef: findRef, mapNodeRange: mapNodeRange, removeNodeRange: removeNodeRange, isFragment: isFragment, getOuterHTML: getOuterHTML, mergeOptions: mergeOptions, resolveAsset: resolveAsset, assertAsset: assertAsset, checkComponentAttr: checkComponentAttr, commonTagRE: commonTagRE, reservedTagRE: reservedTagRE, get warn () { return warn; } }); var uid = 0; function initMixin (Vue) { /** * The main init sequence. This is called for every * instance, including ones that are created from extended * constructors. * * @param {Object} options - this options object should be * the result of merging class * options and the options passed * in to the constructor. */ Vue.prototype._init = function (options) { options = options || {}; this.$el = null; this.$parent = options.parent; this.$root = this.$parent ? this.$parent.$root : this; this.$children = []; this.$refs = {}; // child vm references this.$els = {}; // element references this._watchers = []; // all watchers as an array this._directives = []; // all directives // a uid this._uid = uid++; // a flag to avoid this being observed this._isVue = true; // events bookkeeping this._events = {}; // registered callbacks this._eventsCount = {}; // for $broadcast optimization // fragment instance properties this._isFragment = false; this._fragment = // @type {DocumentFragment} this._fragmentStart = // @type {Text|Comment} this._fragmentEnd = null; // @type {Text|Comment} // lifecycle state this._isCompiled = this._isDestroyed = this._isReady = this._isAttached = this._isBeingDestroyed = this._vForRemoving = false; this._unlinkFn = null; // context: // if this is a transcluded component, context // will be the common parent vm of this instance // and its host. this._context = options._context || this.$parent; // scope: // if this is inside an inline v-for, the scope // will be the intermediate scope created for this // repeat fragment. this is used for linking props // and container directives. this._scope = options._scope; // fragment: // if this instance is compiled inside a Fragment, it // needs to reigster itself as a child of that fragment // for attach/detach to work properly. this._frag = options._frag; if (this._frag) { this._frag.children.push(this); } // push self into parent / transclusion host if (this.$parent) { this.$parent.$children.push(this); } // merge options. options = this.$options = mergeOptions(this.constructor.options, options, this); // set ref this._updateRef(); // initialize data as empty object. // it will be filled up in _initScope(). this._data = {}; // save raw constructor data before merge // so that we know which properties are provided at // instantiation. this._runtimeData = options.data; // call init hook this._callHook('init'); // initialize data observation and scope inheritance. this._initState(); // setup event system and option events. this._initEvents(); // call created hook this._callHook('created'); // if `el` option is passed, start compilation. if (options.el) { this.$mount(options.el); } }; } var __commonjs_global = typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : this; var primitives = (function (module, global) { var exports = module.exports; var names = ['Object', 'String', 'Boolean', 'Number', 'RegExp', 'Date', 'Array'] var immutable = {string: 'String', boolean: 'Boolean', number: 'Number' } var primitives = names.map(getGlobal) var protos = primitives.map(getProto) var protoReplacements = {} module.exports = Primitives function Primitives(context){ if (this instanceof Primitives){ this.context = context for (var i=0;i<names.length;i++){ if (!this.context[names[i]]){ this.context[names[i]] = wrap(primitives[i]) } } } else { return new Primitives(context) } } Primitives.prototype.replace = function(value){ var primIndex = primitives.indexOf(value) var protoIndex = protos.indexOf(value) if (~primIndex){ var name = names[primIndex] return this.context[name] } else if (~protoIndex) { var name = names[protoIndex] return this.context[name].prototype } else { return value } } Primitives.prototype.getPropertyObject = function(object, property){ if (immutable[typeof object]){ return this.getPrototypeOf(object) } return object } Primitives.prototype.isPrimitive = function(value){ return !!~primitives.indexOf(value) || !!~protos.indexOf(value) } Primitives.prototype.getPrototypeOf = function(value){ if (value == null){ // handle null and undefined return value } var immutableType = immutable[typeof value] if (immutableType){ var proto = this.context[immutableType].prototype } else { var proto = Object.getPrototypeOf(value) } if (!proto || proto === Object.prototype){ return null } else { var replacement = this.replace(proto) if (replacement === value){ replacement = this.replace(Object.prototype) } return replacement } } Primitives.prototype.applyNew = function(func, args){ if (func.wrapped){ var prim = Object.getPrototypeOf(func) var instance = new (Function.prototype.bind.apply(prim, arguments)) setProto(instance, func.prototype) return instance } else { return new (Function.prototype.bind.apply(func, arguments)) } } function getProto(func){ return func.prototype } function getGlobal(str){ return global[str] } function setProto(obj, proto){ obj.__proto__ = proto } function wrap(prim){ var proto = Object.create(prim.prototype) var result = function() { if (this instanceof result){ prim.apply(this, arguments) } else { var instance = prim.apply(null, arguments) setProto(instance, proto) return instance } } setProto(result, prim) result.prototype = proto result.wrapped = true return result } return module.exports; })({exports:{}}, __commonjs_global); var infiniteChecker = (function (module) { var exports = module.exports; module.exports = InfiniteChecker function InfiniteChecker(maxIterations){ if (this instanceof InfiniteChecker){ this.maxIterations = maxIterations this.count = 0 } else { return new InfiniteChecker(maxIterations) } } InfiniteChecker.prototype.check = function(){ this.count += 1 if (this.count > this.maxIterations){ throw new Error('Infinite loop detected - reached max iterations') } } return module.exports; })({exports:{}}); var index$1 = (function (module) { var exports = module.exports; module.exports = hoist function hoist(ast){ var parentStack = [] var variables = [] var functions = [] if (Array.isArray(ast)){ walkAll(ast) prependScope(ast, variables, functions) } else { walk(ast) } return ast // walk through each node of a program of block statement function walkAll(nodes){ var result = null for (var i=0;i<nodes.length;i++){ var childNode = nodes[i] if (childNode.type === 'EmptyStatement') continue var result = walk(childNode) if (result === 'remove'){ nodes.splice(i--, 1) } } } function walk(node){ var parent = parentStack[parentStack.length-1] var remove = false parentStack.push(node) var excludeBody = false if (shouldScope(node, parent)){ hoist(node.body) excludeBody = true } if (node.type === 'VariableDeclarator'){ variables.push(node) } if (node.type === 'FunctionDeclaration'){ functions.push(node) remove = true } for (var key in node){ if (key === 'type' || (excludeBody && key === 'body')) continue if (key in node && node[key] && typeof node[key] == 'object'){ if (node[key].type){ walk(node[key]) } else if (Array.isArray(node[key])){ walkAll(node[key]) } } } parentStack.pop() if (remove){ return 'remove' } } } function shouldScope(node, parent){ if (node.type === 'Program'){ return true } else if (node.type === 'BlockStatement'){ if (parent && (parent.type === 'FunctionExpression' || parent.type === 'FunctionDeclaration')){ return true } } } function prependScope(nodes, variables, functions){ if (variables && variables.length){ var declarations = [] for (var i=0;i<variables.length;i++){ declarations.push({ type: 'VariableDeclarator', id: variables[i].id, init: null }) } nodes.unshift({ type: 'VariableDeclaration', kind: 'var', declarations: declarations }) } if (functions && functions.length){ for (var i=0;i<functions.length;i++){ nodes.unshift(functions[i]) } } } return module.exports; })({exports:{}}); var esprima = (function (module) { var exports = module.exports; /* Copyright (C) 2012 Ariya Hidayat <[email protected]> Copyright (C) 2012 Mathias Bynens <[email protected]> Copyright (C) 2012 Joost-Wim Boekesteijn <[email protected]> Copyright (C) 2012 Kris Kowal <[email protected]> Copyright (C) 2012 Yusuke Suzuki <[email protected]> Copyright (C) 2012 Arpad Borsos <[email protected]> Copyright (C) 2011 Ariya Hidayat <[email protected]> Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /*jslint bitwise:true plusplus:true */ /*global esprima:true, define:true, exports:true, window: true, throwError: true, createLiteral: true, generateStatement: true, parseAssignmentExpression: true, parseBlock: true, parseExpression: true, parseFunctionDeclaration: true, parseFunctionExpression: true, parseFunctionSourceElements: true, parseVariableIdentifier: true, parseLeftHandSideExpression: true, parseStatement: true, parseSourceElement: true */ (function (root, factory) { 'use strict'; // Universal Module Definition (UMD) to support AMD, CommonJS/Node.js, // Rhino, and plain browser loading. if (typeof define === 'function' && define.amd) { define(['exports'], factory); } else if (typeof exports !== 'undefined') { factory(exports); } else { factory((root.esprima = {})); } }(this, function (exports) { 'use strict'; var Token, TokenName, Syntax, PropertyKind, Messages, Regex, source, strict, index, lineNumber, lineStart, length, buffer, state, extra; Token = { BooleanLiteral: 1, EOF: 2, Identifier: 3, Keyword: 4, NullLiteral: 5, NumericLiteral: 6, Punctuator: 7, StringLiteral: 8 }; TokenName = {}; TokenName[Token.BooleanLiteral] = 'Boolean'; TokenName[Token.EOF] = '<end>'; TokenName[Token.Identifier] = 'Identifier'; TokenName[Token.Keyword] = 'Keyword'; TokenName[Token.NullLiteral] = 'Null'; TokenName[Token.NumericLiteral] = 'Numeric'; TokenName[Token.Punctuator] = 'Punctuator'; TokenName[Token.StringLiteral] = 'String'; Syntax = { AssignmentExpression: 'AssignmentExpression', ArrayExpression: 'ArrayExpression', BlockStatement: 'BlockStatement', BinaryExpression: 'BinaryExpression', BreakStatement: 'BreakStatement', CallExpression: 'CallExpression', CatchClause: 'CatchClause', ConditionalExpression: 'ConditionalExpression', ContinueStatement: 'ContinueStatement', DoWhileStatement: 'DoWhileStatement', DebuggerStatement: 'DebuggerStatement', EmptyStatement: 'EmptyStatement', ExpressionStatement: 'ExpressionStatement', ForStatement: 'ForStatement', ForInStatement: 'ForInStatement', FunctionDeclaration: 'FunctionDeclaration', FunctionExpression: 'FunctionExpression', Identifier: 'Identifier', IfStatement: 'IfStatement', Literal: 'Literal', LabeledStatement: 'LabeledStatement', LogicalExpression: 'LogicalExpression', MemberExpression: 'MemberExpression', NewExpression: 'NewExpression', ObjectExpression: 'ObjectExpression', Program: 'Program', Property: 'Property', ReturnStatement: 'ReturnStatement', SequenceExpression: 'SequenceExpression', SwitchStatement: 'SwitchStatement', SwitchCase: 'SwitchCase', ThisExpression: 'ThisExpression', ThrowStatement: 'ThrowStatement', TryStatement: 'TryStatement', UnaryExpression: 'UnaryExpression', UpdateExpression: 'UpdateExpression', VariableDeclaration: 'VariableDeclaration', VariableDeclarator: 'VariableDeclarator', WhileStatement: 'WhileStatement', WithStatement: 'WithStatement' }; PropertyKind = { Data: 1, Get: 2, Set: 4 }; // Error messages should be identical to V8. Messages = { UnexpectedToken: 'Unexpected token %0', UnexpectedNumber: 'Unexpected number', UnexpectedString: 'Unexpected string', UnexpectedIdentifier: 'Unexpected identifier', UnexpectedReserved: 'Unexpected reserved word', UnexpectedEOS: 'Unexpected end of input', NewlineAfterThrow: 'Illegal newline after throw', InvalidRegExp: 'Invalid regular expression', UnterminatedRegExp: 'Invalid regular expression: missing /', InvalidLHSInAssignment: 'Invalid left-hand side in assignment', InvalidLHSInForIn: 'Invalid left-hand side in for-in', MultipleDefaultsInSwitch: 'More than one default clause in switch statement', NoCatchOrFinally: 'Missing catch or finally after try', UnknownLabel: 'Undefined label \'%0\'', Redeclaration: '%0 \'%1\' has already been declared', IllegalContinue: 'Illegal continue statement', IllegalBreak: 'Illegal break statement', IllegalReturn: 'Illegal return statement', StrictModeWith: 'Strict mode code may not include a with statement', StrictCatchVariable: 'Catch variable may not be eval or arguments in strict mode', StrictVarName: 'Variable name may not be eval or arguments in strict mode', StrictParamName: 'Parameter name eval or arguments is not allowed in strict mode', StrictParamDupe: 'Strict mode function may not have duplicate parameter names', StrictFunctionName: 'Function name may not be eval or arguments in strict mode', StrictOctalLiteral: 'Octal literals are not allowed in strict mode.', StrictDelete: 'Delete of an unqualified identifier in strict mode.', StrictDuplicateProperty: 'Duplicate data property in object literal not allowed in strict mode', AccessorDataProperty: 'Object literal may not have data and accessor property with the same name', AccessorGetSet: 'Object literal may not have multiple get/set accessors with the same name', StrictLHSAssignment: 'Assignment to eval or arguments is not allowed in strict mode', StrictLHSPostfix: 'Postfix increment/decrement may not have eval or arguments operand in strict mode', StrictLHSPrefix: 'Prefix increment/decrement may not have eval or arguments operand in strict mode', StrictReservedWord: 'Use of future reserved word in strict mode' }; // See also tools/generate-unicode-regex.py. Regex = { NonAsciiIdentifierStart: new RegExp('[\xaa\xb5\xba\xc0-\xd6\xd8-\xf6\xf8-\u02c1\u02c6-\u02d1\u02e0-\u02e4\u02ec\u02ee\u0370-\u0374\u0376\u0377\u037a-\u037d\u0386\u0388-\u038a\u038c\u038e-\u03a1\u03a3-\u03f5\u03f7-\u0481\u048a-\u0527\u0531-\u0556\u0559\u0561-\u0587\u05d0-\u05ea\u05f0-\u05f2\u0620-\u064a\u066e\u066f\u0671-\u06d3\u06d5\u06e5\u06e6\u06ee\u06ef\u06fa-\u06fc\u06ff\u0710\u0712-\u072f\u074d-\u07a5\u07b1\u07ca-\u07ea\u07f4\u07f5\u07fa\u0800-\u0815\u081a\u0824\u0828\u0840-\u0858\u08a0\u08a2-\u08ac\u0904-\u0939\u093d\u0950\u0958-\u0961\u0971-\u0977\u0979-\u097f\u0985-\u098c\u098f\u0990\u0993-\u09a8\u09aa-\u09b0\u09b2\u09b6-\u09b9\u09bd\u09ce\u09dc\u09dd\u09df-\u09e1\u09f0\u09f1\u0a05-\u0a0a\u0a0f\u0a10\u0a13-\u0a28\u0a2a-\u0a30\u0a32\u0a33\u0a35\u0a36\u0a38\u0a39\u0a59-\u0a5c\u0a5e\u0a72-\u0a74\u0a85-\u0a8d\u0a8f-\u0a91\u0a93-\u0aa8\u0aaa-\u0ab0\u0ab2\u0ab3\u0ab5-\u0ab9\u0abd\u0ad0\u0ae0\u0ae1\u0b05-\u0b0c\u0b0f\u0b10\u0b13-\u0b28\u0b2a-\u0b30\u0b32\u0b33\u0b35-\u0b39\u0b3d\u0b5c\u0b5d\u0b5f-\u0b61\u0b71\u0b83\u0b85-\u0b8a\u0b8e-\u0b90\u0b92-\u0b95\u0b99\u0b9a\u0b9c\u0b9e\u0b9f\u0ba3\u0ba4\u0ba8-\u0baa\u0bae-\u0bb9\u0bd0\u0c05-\u0c0c\u0c0e-\u0c10\u0c12-\u0c28\u0c2a-\u0c33\u0c35-\u0c39\u0c3d\u0c58\u0c59\u0c60\u0c61\u0c85-\u0c8c\u0c8e-\u0c90\u0c92-\u0ca8\u0caa-\u0cb3\u0cb5-\u0cb9\u0cbd\u0cde\u0ce0\u0ce1\u0cf1\u0cf2\u0d05-\u0d0c\u0d0e-\u0d10\u0d12-\u0d3a\u0d3d\u0d4e\u0d60\u0d61\u0d7a-\u0d7f\u0d85-\u0d96\u0d9a-\u0db1\u0db3-\u0dbb\u0dbd\u0dc0-\u0dc6\u0e01-\u0e30\u0e32\u0e33\u0e40-\u0e46\u0e81\u0e82\u0e84\u0e87\u0e88\u0e8a\u0e8d\u0e94-\u0e97\u0e99-\u0e9f\u0ea1-\u0ea3\u0ea5\u0ea7\u0eaa\u0eab\u0ead-\u0eb0\u0eb2\u0eb3\u0ebd\u0ec0-\u0ec4\u0ec6\u0edc-\u0edf\u0f00\u0f40-\u0f47\u0f49-\u0f6c\u0f88-\u0f8c\u1000-\u102a\u103f\u1050-\u1055\u105a-\u105d\u1061\u1065\u1066\u106e-\u1070\u1075-\u1081\u108e\u10a0-\u10c5\u10c7\u10cd\u10d0-\u10fa\u10fc-\u1248\u124a-\u124d\u1250-\u1256\u1258\u125a-\u125d\u1260-\u1288\u128a-\u128d\u1290-\u12b0\u12b2-\u12b5\u12b8-\u12be\u12c0\u12c2-\u12c5\u12c8-\u12d6\u12d8-\u1310\u1312-\u1315\u1318-\u135a\u1380-\u138f\u13a0-\u13f4\u1401-\u166c\u166f-\u167f\u1681-\u169a\u16a0-\u16ea\u16ee-\u16f0\u1700-\u170c\u170e-\u1711\u1720-\u1731\u1740-\u1751\u1760-\u176c\u176e-\u1770\u1780-\u17b3\u17d7\u17dc\u1820-\u1877\u1880-\u18a8\u18aa\u18b0-\u18f5\u1900-\u191c\u1950-\u196d\u1970-\u1974\u1980-\u19ab\u19c1-\u19c7\u1a00-\u1a16\u1a20-\u1a54\u1aa7\u1b05-\u1b33\u1b45-\u1b4b\u1b83-\u1ba0\u1bae\u1baf\u1bba-\u1be5\u1c00-\u1c23\u1c4d-\u1c4f\u1c5a-\u1c7d\u1ce9-\u1cec\u1cee-\u1cf1\u1cf5\u1cf6\u1d00-\u1dbf\u1e00-\u1f15\u1f18-\u1f1d\u1f20-\u1f45\u1f48-\u1f4d\u1f50-\u1f57\u1f59\u1f5b\u1f5d\u1f5f-\u1f7d\u1f80-\u1fb4\u1fb6-\u1fbc\u1fbe\u1fc2-\u1fc4\u1fc6-\u1fcc\u1fd0-\u1fd3\u1fd6-\u1fdb\u1fe0-\u1fec\u1ff2-\u1ff4\u1ff6-\u1ffc\u2071\u207f\u2090-\u209c\u2102\u2107\u210a-\u2113\u2115\u2119-\u211d\u2124\u2126\u2128\u212a-\u212d\u212f-\u2139\u213c-\u213f\u2145-\u2149\u214e\u2160-\u2188\u2c00-\u2c2e\u2c30-\u2c5e\u2c60-\u2ce4\u2ceb-\u2cee\u2cf2\u2cf3\u2d00-\u2d25\u2d27\u2d2d\u2d30-\u2d67\u2d6f\u2d80-\u2d96\u2da0-\u2da6\u2da8-\u2dae\u2db0-\u2db6\u2db8-\u2dbe\u2dc0-\u2dc6\u2dc8-\u2dce\u2dd0-\u2dd6\u2dd8-\u2dde\u2e2f\u3005-\u3007\u3021-\u3029\u3031-\u3035\u3038-\u303c\u3041-\u3096\u309d-\u309f\u30a1-\u30fa\u30fc-\u30ff\u3105-\u312d\u3131-\u318e\u31a0-\u31ba\u31f0-\u31ff\u3400-\u4db5\u4e00-\u9fcc\ua000-\ua48c\ua4d0-\ua4fd\ua500-\ua60c\ua610-\ua61f\ua62a\ua62b\ua640-\ua66e\ua67f-\ua697\ua6a0-\ua6ef\ua717-\ua71f\ua722-\ua788\ua78b-\ua78e\ua790-\ua793\ua7a0-\ua7aa\ua7f8-\ua801\ua803-\ua805\ua807-\ua80a\ua80c-\ua822\ua840-\ua873\ua882-\ua8b3\ua8f2-\ua8f7\ua8fb\ua90a-\ua925\ua930-\ua946\ua960-\ua97c\ua984-\ua9b2\ua9cf\uaa00-\uaa28\uaa40-\uaa42\uaa44-\uaa4b\uaa60-\uaa76\uaa7a\uaa80-\uaaaf\uaab1\uaab5\uaab6\uaab9-\uaabd\uaac0\uaac2\uaadb-\uaadd\uaae0-\uaaea\uaaf2-\uaaf4\uab01-\uab06\uab09-\uab0e\uab11-\uab16\uab20-\uab26\uab28-\uab2e\uabc0-\uabe2\uac00-\ud7a3\ud7b0-\ud7c6\ud7cb-\ud7fb\uf900-\ufa6d\ufa70-\ufad9\ufb00-\ufb06\ufb13-\ufb17\ufb1d\ufb1f-\ufb28\ufb2a-\ufb36\ufb38-\ufb3c\ufb3e\ufb40\ufb41\ufb43\ufb44\ufb46-\ufbb1\ufbd3-\ufd3d\ufd50-\ufd8f\ufd92-\ufdc7\ufdf0-\ufdfb\ufe70-\ufe74\ufe76-\ufefc\uff21-\uff3a\uff41-\uff5a\uff66-\uffbe\uffc2-\uffc7\uffca-\uffcf\uffd2-\uffd7\uffda-\uffdc]'), NonAsciiIdentifierPart: new RegExp('[\xaa\xb5\xba\xc0-\xd6\xd8-\xf6\xf8-\u02c1\u02c6-\u02d1\u02e0-\u02e4\u02ec\u02ee\u0300-\u0374\u0376\u0377\u037a-\u037d\u0386\u0388-\u038a\u038c\u038e-\u03a1\u03a3-\u03f5\u03f7-\u0481\u0483-\u0487\u048a-\u0527\u0531-\u0556\u0559\u0561-\u0587\u0591-\u05bd\u05bf\u05c1\u05c2\u05c4\u05c5\u05c7\u05d0-\u05ea\u05f0-\u05f2\u0610-\u061a\u0620-\u0669\u066e-\u06d3\u06d5-\u06dc\u06df-\u06e8\u06ea-\u06fc\u06ff\u0710-\u074a\u074d-\u07b1\u07c0-\u07f5\u07fa\u0800-\u082d\u0840-\u085b\u08a0\u08a2-\u08ac\u08e4-\u08fe\u0900-\u0963\u0966-\u096f\u0971-\u0977\u0979-\u097f\u0981-\u0983\u0985-\u098c\u098f\u0990\u0993-\u09a8\u09aa-\u09b0\u09b2\u09b6-\u09b9\u09bc-\u09c4\u09c7\u09c8\u09cb-\u09ce\u09d7\u09dc\u09dd\u09df-\u09e3\u09e6-\u09f1\u0a01-\u0a03\u0a05-\u0a0a\u0a0f\u0a10\u0a13-\u0a28\u0a2a-\u0a30\u0a32\u0a33\u0a35\u0a36\u0a38\u0a39\u0a3c\u0a3e-\u0a42\u0a47\u0a48\u0a4b-\u0a4d\u0a51\u0a59-\u0a5c\u0a5e\u0a66-\u0a75\u0a81-\u0a83\u0a85-\u0a8d\u0a8f-\u0a91\u0a93-\u0aa8\u0aaa-\u0ab0\u0ab2\u0ab3\u0ab5-\u0ab9\u0abc-\u0ac5\u0ac7-\u0ac9\u0acb-\u0acd\u0ad0\u0ae0-\u0ae3\u0ae6-\u0aef\u0b01-\u0b03\u0b05-\u0b0c\u0b0f\u0b10\u0b13-\u0b28\u0b2a-\u0b30\u0b32\u0b33\u0b35-\u0b39\u0b3c-\u0b44\u0b47\u0b48\u0b4b-\u0b4d\u0b56\u0b57\u0b5c\u0b5d\u0b5f-\u0b63\u0b66-\u0b6f\u0b71\u0b82\u0b83\u0b85-\u0b8a\u0b8e-\u0b90\u0b92-\u0b95\u0b99\u0b9a\u0b9c\u0b9e\u0b9f\u0ba3\u0ba4\u0ba8-\u0baa\u0bae-\u0bb9\u0bbe-\u0bc2\u0bc6-\u0bc8\u0bca-\u0bcd\u0bd0\u0bd7\u0be6-\u0bef\u0c01-\u0c03\u0c05-\u0c0c\u0c0e-\u0c10\u0c12-\u0c28\u0c2a-\u0c33\u0c35-\u0c39\u0c3d-\u0c44\u0c46-\u0c48\u0c4a-\u0c4d\u0c55\u0c56\u0c58\u0c59\u0c60-\u0c63\u0c66-\u0c6f\u0c82\u0c83\u0c85-\u0c8c\u0c8e-\u0c90\u0c92-\u0ca8\u0caa-\u0cb3\u0cb5-\u0cb9\u0cbc-\u0cc4\u0cc6-\u0cc8\u0cca-\u0ccd\u0cd5\u0cd6\u0cde\u0ce0-\u0ce3\u0ce6-\u0cef\u0cf1\u0cf2\u0d02\u0d03\u0d05-\u0d0c\u0d0e-\u0d10\u0d12-\u0d3a\u0d3d-\u0d44\u0d46-\u0d48\u0d4a-\u0d4e\u0d57\u0d60-\u0d63\u0d66-\u0d6f\u0d7a-\u0d7f\u0d82\u0d83\u0d85-\u0d96\u0d9a-\u0db1\u0db3-\u0dbb\u0dbd\u0dc0-\u0dc6\u0dca\u0dcf-\u0dd4\u0dd6\u0dd8-\u0ddf\u0df2\u0df3\u0e01-\u0e3a\u0e40-\u0e4e\u0e50-\u0e59\u0e81\u0e82\u0e84\u0e87\u0e88\u0e8a\u0e8d\u0e94-\u0e97\u0e99-\u0e9f\u0ea1-\u0ea3\u0ea5\u0ea7\u0eaa\u0eab\u0ead-\u0eb9\u0ebb-\u0ebd\u0ec0-\u0ec4\u0ec6\u0ec8-\u0ecd\u0ed0-\u0ed9\u0edc-\u0edf\u0f00\u0f18\u0f19\u0f20-\u0f29\u0f35\u0f37\u0f39\u0f3e-\u0f47\u0f49-\u0f6c\u0f71-\u0f84\u0f86-\u0f97\u0f99-\u0fbc\u0fc6\u1000-\u1049\u1050-\u109d\u10a0-\u10c5\u10c7\u10cd\u10d0-\u10fa\u10fc-\u1248\u124a-\u124d\u1250-\u1256\u1258\u125a-\u125d\u1260-\u1288\u128a-\u128d\u1290-\u12b0\u12b2-\u12b5\u12b8-\u12be\u12c0\u12c2-\u12c5\u12c8-\u12d6\u12d8-\u1310\u1312-\u1315\u1318-\u135a\u135d-\u135f\u1380-\u138f\u13a0-\u13f4\u1401-\u166c\u166f-\u167f\u1681-\u169a\u16a0-\u16ea\u16ee-\u16f0\u1700-\u170c\u170e-\u1714\u1720-\u1734\u1740-\u1753\u1760-\u176c\u176e-\u1770\u1772\u1773\u1780-\u17d3\u17d7\u17dc\u17dd\u17e0-\u17e9\u180b-\u180d\u1810-\u1819\u1820-\u1877\u1880-\u18aa\u18b0-\u18f5\u1900-\u191c\u1920-\u192b\u1930-\u193b\u1946-\u196d\u1970-\u1974\u1980-\u19ab\u19b0-\u19c9\u19d0-\u19d9\u1a00-\u1a1b\u1a20-\u1a5e\u1a60-\u1a7c\u1a7f-\u1a89\u1a90-\u1a99\u1aa7\u1b00-\u1b4b\u1b50-\u1b59\u1b6b-\u1b73\u1b80-\u1bf3\u1c00-\u1c37\u1c40-\u1c49\u1c4d-\u1c7d\u1cd0-\u1cd2\u1cd4-\u1cf6\u1d00-\u1de6\u1dfc-\u1f15\u1f18-\u1f1d\u1f20-\u1f45\u1f48-\u1f4d\u1f50-\u1f57\u1f59\u1f5b\u1f5d\u1f5f-\u1f7d\u1f80-\u1fb4\u1fb6-\u1fbc\u1fbe\u1fc2-\u1fc4\u1fc6-\u1fcc\u1fd0-\u1fd3\u1fd6-\u1fdb\u1fe0-\u1fec\u1ff2-\u1ff4\u1ff6-\u1ffc\u200c\u200d\u203f\u2040\u2054\u2071\u207f\u2090-\u209c\u20d0-\u20dc\u20e1\u20e5-\u20f0\u2102\u2107\u210a-\u2113\u2115\u2119-\u211d\u2124\u2126\u2128\u212a-\u212d\u212f-\u2139\u213c-\u213f\u2145-\u2149\u214e\u2160-\u2188\u2c00-\u2c2e\u2c30-\u2c5e\u2c60-\u2ce4\u2ceb-\u2cf3\u2d00-\u2d25\u2d27\u2d2d\u2d30-\u2d67\u2d6f\u2d7f-\u2d96\u2da0-\u2da6\u2da8-\u2dae\u2db0-\u2db6\u2db8-\u2dbe\u2dc0-\u2dc6\u2dc8-\u2dce\u2dd0-\u2dd6\u2dd8-\u2dde\u2de0-\u2dff\u2e2f\u3005-\u3007\u3021-\u302f\u3031-\u3035\u3038-\u303c\u3041-\u3096\u3099\u309a\u309d-\u309f\u30a1-\u30fa\u30fc-\u30ff\u3105-\u312d\u3131-\u318e\u31a0-\u31ba\u31f0-\u31ff\u3400-\u4db5\u4e00-\u9fcc\ua000-\ua48c\ua4d0-\ua4fd\ua500-\ua60c\ua610-\ua62b\ua640-\ua66f\ua674-\ua67d\ua67f-\ua697\ua69f-\ua6f1\ua717-\ua71f\ua722-\ua788\ua78b-\ua78e\ua790-\ua793\ua7a0-\ua7aa\ua7f8-\ua827\ua840-\ua873\ua880-\ua8c4\ua8d0-\ua8d9\ua8e0-\ua8f7\ua8fb\ua900-\ua92d\ua930-\ua953\ua960-\ua97c\ua980-\ua9c0\ua9cf-\ua9d9\uaa00-\uaa36\uaa40-\uaa4d\uaa50-\uaa59\uaa60-\uaa76\uaa7a\uaa7b\uaa80-\uaac2\uaadb-\uaadd\uaae0-\uaaef\uaaf2-\uaaf6\uab01-\uab06\uab09-\uab0e\uab11-\uab16\uab20-\uab26\uab28-\uab2e\uabc0-\uabea\uabec\uabed\uabf0-\uabf9\uac00-\ud7a3\ud7b0-\ud7c6\ud7cb-\ud7fb\uf900-\ufa6d\ufa70-\ufad9\ufb00-\ufb06\ufb13-\ufb17\ufb1d-\ufb28\ufb2a-\ufb36\ufb38-\ufb3c\ufb3e\ufb40\ufb41\ufb43\ufb44\ufb46-\ufbb1\ufbd3-\ufd3d\ufd50-\ufd8f\ufd92-\ufdc7\ufdf0-\ufdfb\ufe00-\ufe0f\ufe20-\ufe26\ufe33\ufe34\ufe4d-\ufe4f\ufe70-\ufe74\ufe76-\ufefc\uff10-\uff19\uff21-\uff3a\uff3f\uff41-\uff5a\uff66-\uffbe\uffc2-\uffc7\uffca-\uffcf\uffd2-\uffd7\uffda-\uffdc]') }; // Ensure the condition is true, otherwise throw an error. // This is only to have a better contract semantic, i.e. another safety net // to catch a logic error. The condition shall be fulfilled in normal case. // Do NOT use this to enforce a certain condition on any user input. function assert(condition, message) { if (!condition) { throw new Error('ASSERT: ' + message); } } function sliceSource(from, to) { return source.slice(from, to); } if (typeof 'esprima'[0] === 'undefined') { sliceSource = function sliceArraySource(from, to) { return source.slice(from, to).join(''); }; } function isDecimalDigit(ch) { return '0123456789'.indexOf(ch) >= 0; } function isHexDigit(ch) { return '0123456789abcdefABCDEF'.indexOf(ch) >= 0; } function isOctalDigit(ch) { return '01234567'.indexOf(ch) >= 0; } // 7.2 White Space function isWhiteSpace(ch) { return (ch === ' ') || (ch === '\u0009') || (ch === '\u000B') || (ch === '\u000C') || (ch === '\u00A0') || (ch.charCodeAt(0) >= 0x1680 && '\u1680\u180E\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200A\u202F\u205F\u3000\uFEFF'.indexOf(ch) >= 0); } // 7.3 Line Terminators function isLineTerminator(ch) { return (ch === '\n' || ch === '\r' || ch === '\u2028' || ch === '\u2029'); } // 7.6 Identifier Names and Identifiers function isIdentifierStart(ch) { return (ch === '$') || (ch === '_') || (ch === '\\') || (ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z') || ((ch.charCodeAt(0) >= 0x80) && Regex.NonAsciiIdentifierStart.test(ch)); } function isIdentifierPart(ch) { return (ch === '$') || (ch === '_') || (ch === '\\') || (ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z') || ((ch >= '0') && (ch <= '9')) || ((ch.charCodeAt(0) >= 0x80) && Regex.NonAsciiIdentifierPart.test(ch)); } // 7.6.1.2 Future Reserved Words function isFutureReservedWord(id) { switch (id) { // Future reserved words. case 'class': case 'enum': case 'export': case 'extends': case 'import': case 'super': return true; } return false; } function isStrictModeReservedWord(id) { switch (id) { // Strict Mode reserved words. case 'implements': case 'interface': case 'package': case 'private': case 'protected': case 'public': case 'static': case 'yield': case 'let': return true; } return false; } function isRestrictedWord(id) { return id === 'eval' || id === 'arguments'; } // 7.6.1.1 Keywords function isKeyword(id) { var keyword = false; switch (id.length) { case 2: keyword = (id === 'if') || (id === 'in') || (id === 'do'); break; case 3: keyword = (id === 'var') || (id === 'for') || (id === 'new') || (id === 'try'); break; case 4: keyword = (id === 'this') || (id === 'else') || (id === 'case') || (id === 'void') || (id === 'with'); break; case 5: keyword = (id === 'while') || (id === 'break') || (id === 'catch') || (id === 'throw'); break; case 6: keyword = (id === 'return') || (id === 'typeof') || (id === 'delete') || (id === 'switch'); break; case 7: keyword = (id === 'default') || (id === 'finally'); break; case 8: keyword = (id === 'function') || (id === 'continue') || (id === 'debugger'); break; case 10: keyword = (id === 'instanceof'); break; } if (keyword) { return true; } switch (id) { // Future reserved words. // 'const' is specialized as Keyword in V8. case 'const': return true; // For compatiblity to SpiderMonkey and ES.next case 'yield': case 'let': return true; } if (strict && isStrictModeReservedWord(id)) { return true; } return isFutureReservedWord(id); } // 7.4 Comments function skipComment() { var ch, blockComment, lineComment; blockComment = false; lineComment = false; while (index < length) { ch = source[index]; if (lineComment) { ch = source[index++]; if (isLineTerminator(ch)) { lineComment = false; if (ch === '\r' && source[index] === '\n') { ++index; } ++lineNumber; lineStart = index; } } else if (blockComment) { if (isLineTerminator(ch)) { if (ch === '\r' && source[index + 1] === '\n') { ++index; } ++lineNumber; ++index; lineStart = index; if (index >= length) { throwError({}, Messages.UnexpectedToken, 'ILLEGAL'); } } else { ch = source[index++]; if (index >= length) { throwError({}, Messages.UnexpectedToken, 'ILLEGAL'); } if (ch === '*') { ch = source[index]; if (ch === '/') { ++index; blockComment = false; } } } } else if (ch === '/') { ch = source[index + 1]; if (ch === '/') { index += 2; lineComment = true; } else if (ch === '*') { index += 2; blockComment = true; if (index >= length) { throwError({}, Messages.UnexpectedToken, 'ILLEGAL'); } } else { break; } } else if (isWhiteSpace(ch)) { ++index; } else if (isLineTerminator(ch)) { ++index; if (ch === '\r' && source[index] === '\n') { ++index; } ++lineNumber; lineStart = index; } else { break; } } } function scanHexEscape(prefix) { var i, len, ch, code = 0; len = (prefix === 'u') ? 4 : 2; for (i = 0; i < len; ++i) { if (index < length && isHexDigit(source[index])) { ch = source[index++]; code = code * 16 + '0123456789abcdef'.indexOf(ch.toLowerCase()); } else { return ''; } } return String.fromCharCode(code); } function scanIdentifier() { var ch, start, id, restore; ch = source[index]; if (!isIdentifierStart(ch)) { return; } start = index; if (ch === '\\') { ++index; if (source[index] !== 'u') { return; } ++index; restore = index; ch = scanHexEscape('u'); if (ch) { if (ch === '\\' || !isIdentifierStart(ch)) { return; } id = ch; } else { index = restore; id = 'u'; } } else { id = source[index++]; } while (index < length) { ch = source[index]; if (!isIdentifierPart(ch)) { break; } if (ch === '\\') { ++index; if (source[index] !== 'u') { return; } ++index; restore = index; ch = scanHexEscape('u'); if (ch) { if (ch === '\\' || !isIdentifierPart(ch)) { return; } id += ch; } else { index = restore; id += 'u'; } } else { id += source[index++]; } } // There is no keyword or literal with only one character. // Thus, it must be an identifier. if (id.length === 1) { return { type: Token.Identifier, value: id, lineNumber: lineNumber, lineStart: lineStart, range: [start, index] }; } if (isKeyword(id)) { return { type: Token.Keyword, value: id, lineNumber: lineNumber, lineStart: lineStart, range: [start, index] }; } // 7.8.1 Null Literals if (id === 'null') { return { type: Token.NullLiteral, value: id, lineNumber: lineNumber, lineStart: lineStart, range: [start, index] }; } // 7.8.2 Boolean Literals if (id === 'true' || id === 'false') { return { type: Token.BooleanLiteral, value: id, lineNumber: lineNumber, lineStart: lineStart, range: [start, index] }; } return { type: Token.Identifier, value: id, lineNumber: lineNumber, lineStart: lineStart, range: [start, index] }; } // 7.7 Punctuators function scanPunctuator() { var start = index, ch1 = source[index], ch2, ch3, ch4; // Check for most common single-character punctuators. if (ch1 === ';' || ch1 === '{' || ch1 === '}') { ++index; return { type: Token.Punctuator, value: ch1, lineNumber: lineNumber, lineStart: lineStart, range: [start, index] }; } if (ch1 === ',' || ch1 === '(' || ch1 === ')') { ++index; return { type: Token.Punctuator, value: ch1, lineNumber: lineNumber, lineStart: lineStart, range: [start, index] }; } // Dot (.) can also start a floating-point number, hence the need // to check the next character. ch2 = source[index + 1]; if (ch1 === '.' && !isDecimalDigit(ch2)) { return { type: Token.Punctuator, value: source[index++], lineNumber: lineNumber, lineStart: lineStart, range: [start, index] }; } // Peek more characters. ch3 = source[index + 2]; ch4 = source[index + 3]; // 4-character punctuator: >>>= if (ch1 === '>' && ch2 === '>' && ch3 === '>') { if (ch4 === '=') { index += 4; return { type: Token.Punctuator, value: '>>>=', lineNumber: lineNumber, lineStart: lineStart, range: [start, index] }; } } // 3-character punctuators: === !== >>> <<= >>= if (ch1 === '=' && ch2 === '=' && ch3 === '=') { index += 3; return { type: Token.Punctuator, value: '===', lineNumber: lineNumber, lineStart: lineStart, range: [start, index] }; } if (ch1 === '!' && ch2 === '=' && ch3 === '=') { index += 3; return { type: Token.Punctuator, value: '!==', lineNumber: lineNumber, lineStart: lineStart, range: [start, index] }; } if (ch1 === '>' && ch2 === '>' && ch3 === '>') { index += 3; return { type: Token.Punctuator, value: '>>>', lineNumber: lineNumber, lineStart: lineStart, range: [start, index] }; } if (ch1 === '<' && ch2 === '<' && ch3 === '=') { index += 3; return { type: Token.Punctuator, value: '<<=', lineNumber: lineNumber, lineStart: lineStart, range: [start, index] }; } if (ch1 === '>' && ch2 === '>' && ch3 === '=') { index += 3; return { type: Token.Punctuator, value: '>>=', lineNumber: lineNumber, lineStart: lineStart, range: [start, index] }; } // 2-character punctuators: <= >= == != ++ -- << >> && || // += -= *= %= &= |= ^= /= if (ch2 === '=') { if ('<>=!+-*%&|^/'.indexOf(ch1) >= 0) { index += 2; return { type: Token.Punctuator, value: ch1 + ch2, lineNumber: lineNumber, lineStart: lineStart, range: [start, index] }; } } if (ch1 === ch2 && ('+-<>&|'.indexOf(ch1) >= 0)) { if ('+-<>&|'.indexOf(ch2) >= 0) { index += 2; return { type: Token.Punctuator, value: ch1 + ch2, lineNumber: lineNumber, lineStart: lineStart, range: [start, index] }; } } // The remaining 1-character punctuators. if ('[]<>+-*%&|^!~?:=/'.indexOf(ch1) >= 0) { return { type: Token.Punctuator, value: source[index++], lineNumber: lineNumber, lineStart: lineStart, range: [start, index] }; } } // 7.8.3 Numeric Literals function scanNumericLiteral() { var number, start, ch; ch = source[index]; assert(isDecimalDigit(ch) || (ch === '.'), 'Numeric literal must start with a decimal digit or a decimal point'); start = index; number = ''; if (ch !== '.') { number = source[index++]; ch = source[index]; // Hex number starts with '0x'. // Octal number starts with '0'. if (number === '0') { if (ch === 'x' || ch === 'X') { number += source[index++]; while (index < length) { ch = source[index]; if (!isHexDigit(ch)) { break; } number += source[index++]; } if (number.length <= 2) { // only 0x throwError({}, Messages.UnexpectedToken, 'ILLEGAL'); } if (index < length) { ch = source[index]; if (isIdentifierStart(ch)) { throwError({}, Messages.UnexpectedToken, 'ILLEGAL'); } } return { type: Token.NumericLiteral, value: parseInt(number, 16), lineNumber: lineNumber, lineStart: lineStart, range: [start, index] }; } else if (isOctalDigit(ch)) { number += source[index++]; while (index < length) { ch = source[index]; if (!isOctalDigit(ch)) { break; } number += source[index++]; } if (index < length) { ch = source[index]; if (isIdentifierStart(ch) || isDecimalDigit(ch)) { throwError({}, Messages.UnexpectedToken, 'ILLEGAL'); } } return { type: Token.NumericLiteral, value: parseInt(number, 8), octal: true, lineNumber: lineNumber, lineStart: lineStart, range: [start, index] }; } // decimal number starts with '0' such as '09' is illegal. if (isDecimalDigit(ch)) { throwError({}, Messages.UnexpectedToken, 'ILLEGAL'); } } while (index < length) { ch = source[index]; if (!isDecimalDigit(ch)) { break; } number += source[index++]; } } if (ch === '.') { number += source[index++]; while (index < length) { ch = source[index]; if (!isDecimalDigit(ch)) { break; } number += source[index++]; } } if (ch === 'e' || ch === 'E') { number += source[index++]; ch = source[index]; if (ch === '+' || ch === '-') { number += source[index++]; } ch = source[index]; if (isDecimalDigit(ch)) { number += source[index++]; while (index < length) { ch = source[index]; if (!isDecimalDigit(ch)) { break; } number += source[index++]; } } else { ch = 'character ' + ch; if (index >= length) { ch = '<end>'; } throwError({}, Messages.UnexpectedToken, 'ILLEGAL'); } } if (index < length) { ch = source[index]; if (isIdentifierStart(ch)) { throwError({}, Messages.UnexpectedToken, 'ILLEGAL'); } } return { type: Token.NumericLiteral, value: parseFloat(number), lineNumber: lineNumber, lineStart: lineStart, range: [start, index] }; } // 7.8.4 String Literals function scanStringLiteral() { var str = '', quote, start, ch, code, unescaped, restore, octal = false; quote = source[index]; assert((quote === '\'' || quote === '"'), 'String literal must starts with a quote'); start = index; ++index; while (index < length) { ch = source[index++]; if (ch === quote) { quote = ''; break; } else if (ch === '\\') { ch = source[index++]; if (!isLineTerminator(ch)) { switch (ch) { case 'n': str += '\n'; break; case 'r': str += '\r'; break; case 't': str += '\t'; break; case 'u': case 'x': restore = index; unescaped = scanHexEscape(ch); if (unescaped) { str += unescaped; } else { index = restore; str += ch; } break; case 'b': str += '\b'; break; case 'f': str += '\f'; break; case 'v': str += '\x0B'; break; default: if (isOctalDigit(ch)) { code = '01234567'.indexOf(ch); // \0 is not octal escape sequence if (code !== 0) { octal = true; } if (index < length && isOctalDigit(source[index])) { octal = true; code = code * 8 + '01234567'.indexOf(source[index++]); // 3 digits are only allowed when string starts // with 0, 1, 2, 3 if ('0123'.indexOf(ch) >= 0 && index < length && isOctalDigit(source[index])) { code = code * 8 + '01234567'.indexOf(source[index++]); } } str += String.fromCharCode(code); } else { str += ch; } break; } } else { ++lineNumber; if (ch === '\r' && source[index] === '\n') { ++index; } } } else if (isLineTerminator(ch)) { break; } else { str += ch; } } if (quote !== '') { throwError({}, Messages.UnexpectedToken, 'ILLEGAL'); } return { type: Token.StringLiteral, value: str, octal: octal, lineNumber: lineNumber, lineStart: lineStart, range: [start, index] }; } function scanRegExp() { var str, ch, start, pattern, flags, value, classMarker = false, restore, terminated = false; buffer = null; skipComment(); start = index; ch = source[index]; assert(ch === '/', 'Regular expression literal must start with a slash'); str = source[index++]; while (index < length) { ch = source[index++]; str += ch; if (ch === '\\') { ch = source[index++]; // ECMA-262 7.8.5 if (isLineTerminator(ch)) { throwError({}, Messages.UnterminatedRegExp); } str += ch; } else if (classMarker) { if (ch === ']') { classMarker = false; } } else { if (ch === '/') { terminated = true; break; } else if (ch === '[') { classMarker = true; } else if (isLineTerminator(ch)) { throwError({}, Messages.UnterminatedRegExp); } } } if (!terminated) { throwError({}, Messages.UnterminatedRegExp); } // Exclude leading and trailing slash. pattern = str.substr(1, str.length - 2); flags = ''; while (index < length) { ch = source[index]; if (!isIdentifierPart(ch)) { break; } ++index; if (ch === '\\' && index < length) { ch = source[index]; if (ch === 'u') { ++index; restore = index; ch = scanHexEscape('u'); if (ch) { flags += ch; str += '\\u'; for (; restore < index; ++restore) { str += source[restore]; } } else { index = restore; flags += 'u'; str += '\\u'; } } else { str += '\\'; } } else { flags += ch; str += ch; } } try { value = new RegExp(pattern, flags); } catch (e) { throwError({}, Messages.InvalidRegExp); } return { literal: str, value: value, range: [start, index] }; } function isIdentifierName(token) { return token.type === Token.Identifier || token.type === Token.Keyword || token.type === Token.BooleanLiteral || token.type === Token.NullLiteral; } function advance() { var ch, token; skipComment(); if (index >= length) { return { type: Token.EOF, lineNumber: lineNumber, lineStart: lineStart, range: [index, index] }; } token = scanPunctuator(); if (typeof token !== 'undefined') { return token; } ch = source[index]; if (ch === '\'' || ch === '"') { return scanStringLiteral(); } if (ch === '.' || isDecimalDigit(ch)) { return scanNumericLiteral(); } token = scanIdentifier(); if (typeof token !== 'undefined') { return token; } throwError({}, Messages.UnexpectedToken, 'ILLEGAL'); } function lex() { var token; if (buffer) { index = buffer.range[1]; lineNumber = buffer.lineNumber; lineStart = buffer.lineStart; token = buffer; buffer = null; return token; } buffer = null; return advance(); } function lookahead() { var pos, line, start; if (buffer !== null) { return buffer; } pos = index; line = lineNumber; start = lineStart; buffer = advance(); index = pos; lineNumber = line; lineStart = start; return buffer; } // Return true if there is a line terminator before the next token. function peekLineTerminator() { var pos, line, start, found; pos = index; line = lineNumber; start = lineStart; skipComment(); found = lineNumber !== line; index = pos; lineNumber = line; lineStart = start; return found; } // Throw an exception function throwError(token, messageFormat) { var error, args = Array.prototype.slice.call(arguments, 2), msg = messageFormat.replace( /%(\d)/g, function (whole, index) { return args[index] || ''; } ); if (typeof token.lineNumber === 'number') { error = new Error('Line ' + token.lineNumber + ': ' + msg); error.index = token.range[0]; error.lineNumber = token.lineNumber; error.column = token.range[0] - lineStart + 1; } else { error = new Error('Line ' + lineNumber + ': ' + msg); error.index = index; error.lineNumber = lineNumber; error.column = index - lineStart + 1; } throw error; } function throwErrorTolerant() { try { throwError.apply(null, arguments); } catch (e) { if (extra.errors) { extra.errors.push(e); } else { throw e; } } } // Throw an exception because of the token. function throwUnexpected(token) { if (token.type === Token.EOF) { throwError(token, Messages.UnexpectedEOS); } if (token.type === Token.NumericLiteral) { throwError(token, Messages.UnexpectedNumber); } if (token.type === Token.StringLiteral) { throwError(token, Messages.UnexpectedString); } if (token.type === Token.Identifier) { throwError(token, Messages.UnexpectedIdentifier); } if (token.type === Token.Keyword) { if (isFutureReservedWord(token.value)) { throwError(token, Messages.UnexpectedReserved); } else if (strict && isStrictModeReservedWord(token.value)) { throwErrorTolerant(token, Messages.StrictReservedWord); return; } throwError(token, Messages.UnexpectedToken, token.value); } // BooleanLiteral, NullLiteral, or Punctuator. throwError(token, Messages.UnexpectedToken, token.value); } // Expect the next token to match the specified punctuator. // If not, an exception will be thrown. function expect(value) { var token = lex(); if (token.type !== Token.Punctuator || token.value !== value) { throwUnexpected(token); } } // Expect the next token to match the specified keyword. // If not, an exception will be thrown. function expectKeyword(keyword) { var token = lex(); if (token.type !== Token.Keyword || token.value !== keyword) { throwUnexpected(token); } } // Return true if the next token matches the specified punctuator. function match(value) { var token = lookahead(); return token.type === Token.Punctuator && token.value === value; } // Return true if the next token matches the specified keyword function matchKeyword(keyword) { var token = lookahead(); return token.type === Token.Keyword && token.value === keyword; } // Return true if the next token is an assignment operator function matchAssign() { var token = lookahead(), op = token.value; if (token.type !== Token.Punctuator) { return false; } return op === '=' || op === '*=' || op === '/=' || op === '%=' || op === '+=' || op === '-=' || op === '<<=' || op === '>>=' || op === '>>>=' || op === '&=' || op === '^=' || op === '|='; } function consumeSemicolon() { var token, line; // Catch the very common case first. if (source[index] === ';') { lex(); return; } line = lineNumber; skipComment(); if (lineNumber !== line) { return; } if (match(';')) { lex(); return; } token = lookahead(); if (token.type !== Token.EOF && !match('}')) { throwUnexpected(token); } } // Return true if provided expression is LeftHandSideExpression function isLeftHandSide(expr) { return expr.type === Syntax.Identifier || expr.type === Syntax.MemberExpression; } // 11.1.4 Array Initialiser function parseArrayInitialiser() { var elements = []; expect('['); while (!match(']')) { if (match(',')) { lex(); elements.push(null); } else { elements.push(parseAssignmentExpression()); if (!match(']')) { expect(','); } } } expect(']'); return { type: Syntax.ArrayExpression, elements: elements }; } // 11.1.5 Object Initialiser function parsePropertyFunction(param, first) { var previousStrict, body; previousStrict = strict; body = parseFunctionSourceElements(); if (first && strict && isRestrictedWord(param[0].name)) { throwErrorTolerant(first, Messages.StrictParamName); } strict = previousStrict; return { type: Syntax.FunctionExpression, id: null, params: param, defaults: [], body: body, rest: null, generator: false, expression: false }; } function parseObjectPropertyKey() { var token = lex(); // Note: This function is called only from parseObjectProperty(), where // EOF and Punctuator tokens are already filtered out. if (token.type === Token.StringLiteral || token.type === Token.NumericLiteral) { if (strict && token.octal) { throwErrorTolerant(token, Messages.StrictOctalLiteral); } return createLiteral(token); } return { type: Syntax.Identifier, name: token.value }; } function parseObjectProperty() { var token, key, id, param; token = lookahead(); if (token.type === Token.Identifier) { id = parseObjectPropertyKey(); // Property Assignment: Getter and Setter. if (token.value === 'get' && !match(':')) { key = parseObjectPropertyKey(); expect('('); expect(')'); return { type: Syntax.Property, key: key, value: parsePropertyFunction([]), kind: 'get' }; } else if (token.value === 'set' && !match(':')) { key = parseObjectPropertyKey(); expect('('); token = lookahead(); if (token.type !== Token.Identifier) { expect(')'); throwErrorTolerant(token, Messages.UnexpectedToken, token.value); return { type: Syntax.Property, key: key, value: parsePropertyFunction([]), kind: 'set' }; } else { param = [ parseVariableIdentifier() ]; expect(')'); return { type: Syntax.Property, key: key, value: parsePropertyFunction(param, token), kind: 'set' }; } } else { expect(':'); return { type: Syntax.Property, key: id, value: parseAssignmentExpression(), kind: 'init' }; } } else if (token.type === Token.EOF || token.type === Token.Punctuator) { throwUnexpected(token); } else { key = parseObjectPropertyKey(); expect(':'); return { type: Syntax.Property, key: key, value: parseAssignmentExpression(), kind: 'init' }; } } function parseObjectInitialiser() { var properties = [], property, name, kind, map = {}, toString = String; expect('{'); while (!match('}')) { property = parseObjectProperty(); if (property.key.type === Syntax.Identifier) { name = property.key.name; } else { name = toString(property.key.value); } kind = (property.kind === 'init') ? PropertyKind.Data : (property.kind === 'get') ? PropertyKind.Get : PropertyKind.Set; if (Object.prototype.hasOwnProperty.call(map, name)) { if (map[name] === PropertyKind.Data) { if (strict && kind === PropertyKind.Data) { throwErrorTolerant({}, Messages.StrictDuplicateProperty); } else if (kind !== PropertyKind.Data) { throwErrorTolerant({}, Messages.AccessorDataProperty); } } else { if (kind === PropertyKind.Data) { throwErrorTolerant({}, Messages.AccessorDataProperty); } else if (map[name] & kind) { throwErrorTolerant({}, Messages.AccessorGetSet); } } map[name] |= kind; } else { map[name] = kind; } properties.push(property); if (!match('}')) { expect(','); } } expect('}'); return { type: Syntax.ObjectExpression, properties: properties }; } // 11.1.6 The Grouping Operator function parseGroupExpression() { var expr; expect('('); expr = parseExpression(); expect(')'); return expr; } // 11.1 Primary Expressions function parsePrimaryExpression() { var token = lookahead(), type = token.type; if (type === Token.Identifier) { return { type: Syntax.Identifier, name: lex().value }; } if (type === Token.StringLiteral || type === Token.NumericLiteral) { if (strict && token.octal) { throwErrorTolerant(token, Messages.StrictOctalLiteral); } return createLiteral(lex()); } if (type === Token.Keyword) { if (matchKeyword('this')) { lex(); return { type: Syntax.ThisExpression }; } if (matchKeyword('function')) { return parseFunctionExpression(); } } if (type === Token.BooleanLiteral) { lex(); token.value = (token.value === 'true'); return createLiteral(token); } if (type === Token.NullLiteral) { lex(); token.value = null; return createLiteral(token); } if (match('[')) { return parseArrayInitialiser(); } if (match('{')) { return parseObjectInitialiser(); } if (match('(')) { return parseGroupExpression(); } if (match('/') || match('/=')) { return createLiteral(scanRegExp()); } return throwUnexpected(lex()); } // 11.2 Left-Hand-Side Expressions function parseArguments() { var args = []; expect('('); if (!match(')')) { while (index < length) { args.push(parseAssignmentExpression()); if (match(')')) { break; } expect(','); } } expect(')'); return args; } function parseNonComputedProperty() { var token = lex(); if (!isIdentifierName(token)) { throwUnexpected(token); } return { type: Syntax.Identifier, name: token.value }; } function parseNonComputedMember() { expect('.'); return parseNonComputedProperty(); } function parseComputedMember() { var expr; expect('['); expr = parseExpression(); expect(']'); return expr; } function parseNewExpression() { var expr; expectKeyword('new'); expr = { type: Syntax.NewExpression, callee: parseLeftHandSideExpression(), 'arguments': [] }; if (match('(')) { expr['arguments'] = parseArguments(); } return expr; } function parseLeftHandSideExpressionAllowCall() { var expr; expr = matchKeyword('new') ? parseNewExpression() : parsePrimaryExpression(); while (match('.') || match('[') || match('(')) { if (match('(')) { expr = { type: Syntax.CallExpression, callee: expr, 'arguments': parseArguments() }; } else if (match('[')) { expr = { type: Syntax.MemberExpression, computed: true, object: expr, property: parseComputedMember() }; } else { expr = { type: Syntax.MemberExpression, computed: false, object: expr, property: parseNonComputedMember() }; } } return expr; } function parseLeftHandSideExpression() { var expr; expr = matchKeyword('new') ? parseNewExpression() : parsePrimaryExpression(); while (match('.') || match('[')) { if (match('[')) { expr = { type: Syntax.MemberExpression, computed: true, object: expr, property: parseComputedMember() }; } else { expr = { type: Syntax.MemberExpression, computed: false, object: expr, property: parseNonComputedMember() }; } } return expr; } // 11.3 Postfix Expressions function parsePostfixExpression() { var expr = parseLeftHandSideExpressionAllowCall(), token; token = lookahead(); if (token.type !== Token.Punctuator) { return expr; } if ((match('++') || match('--')) && !peekLineTerminator()) { // 11.3.1, 11.3.2 if (strict && expr.type === Syntax.Identifier && isRestrictedWord(expr.name)) { throwErrorTolerant({}, Messages.StrictLHSPostfix); } if (!isLeftHandSide(expr)) { throwErrorTolerant({}, Messages.InvalidLHSInAssignment); } expr = { type: Syntax.UpdateExpression, operator: lex().value, argument: expr, prefix: false }; } return expr; } // 11.4 Unary Operators function parseUnaryExpression() { var token, expr; token = lookahead(); if (token.type !== Token.Punctuator && token.type !== Token.Keyword) { return parsePostfixExpression(); } if (match('++') || match('--')) { token = lex(); expr = parseUnaryExpression(); // 11.4.4, 11.4.5 if (strict && expr.type === Syntax.Identifier && isRestrictedWord(expr.name)) { throwErrorTolerant({}, Messages.StrictLHSPrefix); } if (!isLeftHandSide(expr)) { throwErrorTolerant({}, Messages.InvalidLHSInAssignment); } expr = { type: Syntax.UpdateExpression, operator: token.value, argument: expr, prefix: true }; return expr; } if (match('+') || match('-') || match('~') || match('!')) { expr = { type: Syntax.UnaryExpression, operator: lex().value, argument: parseUnaryExpression(), prefix: true }; return expr; } if (matchKeyword('delete') || matchKeyword('void') || matchKeyword('typeof')) { expr = { type: Syntax.UnaryExpression, operator: lex().value, argument: parseUnaryExpression(), prefix: true }; if (strict && expr.operator === 'delete' && expr.argument.type === Syntax.Identifier) { throwErrorTolerant({}, Messages.StrictDelete); } return expr; } return parsePostfixExpression(); } // 11.5 Multiplicative Operators function parseMultiplicativeExpression() { var expr = parseUnaryExpression(); while (match('*') || match('/') || match('%')) { expr = { type: Syntax.BinaryExpression, operator: lex().value, left: expr, right: parseUnaryExpression() }; } return expr; } // 11.6 Additive Operators function parseAdditiveExpression() { var expr = parseMultiplicativeExpression(); while (match('+') || match('-')) { expr = { type: Syntax.BinaryExpression, operator: lex().value, left: expr, right: parseMultiplicativeExpression() }; } return expr; } // 11.7 Bitwise Shift Operators function parseShiftExpression() { var expr = parseAdditiveExpression(); while (match('<<') || match('>>') || match('>>>')) { expr = { type: Syntax.BinaryExpression, operator: lex().value, left: expr, right: parseAdditiveExpression() }; } return expr; } // 11.8 Relational Operators function parseRelationalExpression() { var expr, previousAllowIn; previousAllowIn = state.allowIn; state.allowIn = true; expr = parseShiftExpression(); while (match('<') || match('>') || match('<=') || match('>=') || (previousAllowIn && matchKeyword('in')) || matchKeyword('instanceof')) { expr = { type: Syntax.BinaryExpression, operator: lex().value, left: expr, right: parseShiftExpression() }; } state.allowIn = previousAllowIn; return expr; } // 11.9 Equality Operators function parseEqualityExpression() { var expr = parseRelationalExpression(); while (match('==') || match('!=') || match('===') || match('!==')) { expr = { type: Syntax.BinaryExpression, operator: lex().value, left: expr, right: parseRelationalExpression() }; } return expr; } // 11.10 Binary Bitwise Operators function parseBitwiseANDExpression() { var expr = parseEqualityExpression(); while (match('&')) { lex(); expr = { type: Syntax.BinaryExpression, operator: '&', left: expr, right: parseEqualityExpression() }; } return expr; } function parseBitwiseXORExpression() { var expr = parseBitwiseANDExpression(); while (match('^')) { lex(); expr = { type: Syntax.BinaryExpression, operator: '^', left: expr, right: parseBitwiseANDExpression() }; } return expr; } function parseBitwiseORExpression() { var expr = parseBitwiseXORExpression(); while (match('|')) { lex(); expr = { type: Syntax.BinaryExpression, operator: '|', left: expr, right: parseBitwiseXORExpression() }; } return expr; } // 11.11 Binary Logical Operators function parseLogicalANDExpression() { var expr = parseBitwiseORExpression(); while (match('&&')) { lex(); expr = { type: Syntax.LogicalExpression, operator: '&&', left: expr, right: parseBitwiseORExpression() }; } return expr; } function parseLogicalORExpression() { var expr = parseLogicalANDExpression(); while (match('||')) { lex(); expr = { type: Syntax.LogicalExpression, operator: '||', left: expr, right: parseLogicalANDExpression() }; } return expr; } // 11.12 Conditional Operator function parseConditionalExpression() { var expr, previousAllowIn, consequent; expr = parseLogicalORExpression(); if (match('?')) { lex(); previousAllowIn = state.allowIn; state.allowIn = true; consequent = parseAssignmentExpression(); state.allowIn = previousAllowIn; expect(':'); expr = { type: Syntax.ConditionalExpression, test: expr, consequent: consequent, alternate: parseAssignmentExpression() }; } return expr; } // 11.13 Assignment Operators function parseAssignmentExpression() { var token, expr; token = lookahead(); expr = parseConditionalExpression(); if (matchAssign()) { // LeftHandSideExpression if (!isLeftHandSide(expr)) { throwErrorTolerant({}, Messages.InvalidLHSInAssignment); } // 11.13.1 if (strict && expr.type === Syntax.Identifier && isRestrictedWord(expr.name)) { throwErrorTolerant(token, Messages.StrictLHSAssignment); } expr = { type: Syntax.AssignmentExpression, operator: lex().value, left: expr, right: parseAssignmentExpression() }; } return expr; } // 11.14 Comma Operator function parseExpression() { var expr = parseAssignmentExpression(); if (match(',')) { expr = { type: Syntax.SequenceExpression, expressions: [ expr ] }; while (index < length) { if (!match(',')) { break; } lex(); expr.expressions.push(parseAssignmentExpression()); } } return expr; } // 12.1 Block function parseStatementList() { var list = [], statement; while (index < length) { if (match('}')) { break; } statement = parseSourceElement(); if (typeof statement === 'undefined') { break; } list.push(statement); } return list; } function parseBlock() { var block; expect('{'); block = parseStatementList(); expect('}'); return { type: Syntax.BlockStatement, body: block }; } // 12.2 Variable Statement function parseVariableIdentifier() { var token = lex(); if (token.type !== Token.Identifier) { throwUnexpected(token); } return { type: Syntax.Identifier, name: token.value }; } function parseVariableDeclaration(kind) { var id = parseVariableIdentifier(), init = null; // 12.2.1 if (strict && isRestrictedWord(id.name)) { throwErrorTolerant({}, Messages.StrictVarName); } if (kind === 'const') { expect('='); init = parseAssignmentExpression(); } else if (match('=')) { lex(); init = parseAssignmentExpression(); } return { type: Syntax.VariableDeclarator, id: id, init: init }; } function parseVariableDeclarationList(kind) { var list = []; do { list.push(parseVariableDeclaration(kind)); if (!match(',')) { break; } lex(); } while (index < length); return list; } function parseVariableStatement() { var declarations; expectKeyword('var'); declarations = parseVariableDeclarationList(); consumeSemicolon(); return { type: Syntax.VariableDeclaration, declarations: declarations, kind: 'var' }; } // kind may be `const` or `let` // Both are experimental and not in the specification yet. // see http://wiki.ecmascript.org/doku.php?id=harmony:const // and http://wiki.ecmascript.org/doku.php?id=harmony:let function parseConstLetDeclaration(kind) { var declarations; expectKeyword(kind); declarations = parseVariableDeclarationList(kind); consumeSemicolon(); return { type: Syntax.VariableDeclaration, declarations: declarations, kind: kind }; } // 12.3 Empty Statement function parseEmptyStatement() { expect(';'); return { type: Syntax.EmptyStatement }; } // 12.4 Expression Statement function parseExpressionStatement() { var expr = parseExpression(); consumeSemicolon(); return { type: Syntax.ExpressionStatement, expression: expr }; } // 12.5 If statement function parseIfStatement() { var test, consequent, alternate; expectKeyword('if'); expect('('); test = parseExpression(); expect(')'); consequent = parseStatement(); if (matchKeyword('else')) { lex(); alternate = parseStatement(); } else { alternate = null; } return { type: Syntax.IfStatement, test: test, consequent: consequent, alternate: alternate }; } // 12.6 Iteration Statements function parseDoWhileStatement() { var body, test, oldInIteration; expectKeyword('do'); oldInIteration = state.inIteration; state.inIteration = true; body = parseStatement(); state.inIteration = oldInIteration; expectKeyword('while'); expect('('); test = parseExpression(); expect(')'); if (match(';')) { lex(); } return { type: Syntax.DoWhileStatement, body: body, test: test }; } function parseWhileStatement() { var test, body, oldInIteration; expectKeyword('while'); expect('('); test = parseExpression(); expect(')'); oldInIteration = state.inIteration; state.inIteration = true; body = parseStatement(); state.inIteration = oldInIteration; return { type: Syntax.WhileStatement, test: test, body: body }; } function parseForVariableDeclaration() { var token = lex(); return { type: Syntax.VariableDeclaration, declarations: parseVariableDeclarationList(), kind: token.value }; } function parseForStatement() { var init, test, update, left, right, body, oldInIteration; init = test = update = null; expectKeyword('for'); expect('('); if (match(';')) { lex(); } else { if (matchKeyword('var') || matchKeyword('let')) { state.allowIn = false; init = parseForVariableDeclaration(); state.allowIn = true; if (init.declarations.length === 1 && matchKeyword('in')) { lex(); left = init; right = parseExpression(); init = null; } } else { state.allowIn = false; init = parseExpression(); state.allowIn = true; if (matchKeyword('in')) { // LeftHandSideExpression if (!isLeftHandSide(init)) { throwErrorTolerant({}, Messages.InvalidLHSInForIn); } lex(); left = init; right = parseExpression(); init = null; } } if (typeof left === 'undefined') { expect(';'); } } if (typeof left === 'undefined') { if (!match(';')) { test = parseExpression(); } expect(';'); if (!match(')')) { update = parseExpression(); } } expect(')'); oldInIteration = state.inIteration; state.inIteration = true; body = parseStatement(); state.inIteration = oldInIteration; if (typeof left === 'undefined') { return { type: Syntax.ForStatement, init: init, test: test, update: update, body: body }; } return { type: Syntax.ForInStatement, left: left, right: right, body: body, each: false }; } // 12.7 The continue statement function parseContinueStatement() { var token, label = null; expectKeyword('continue'); // Optimize the most common form: 'continue;'. if (source[index] === ';') { lex(); if (!state.inIteration) { throwError({}, Messages.IllegalContinue); } return { type: Syntax.ContinueStatement, label: null }; } if (peekLineTerminator()) { if (!state.inIteration) { throwError({}, Messages.IllegalContinue); } return { type: Syntax.ContinueStatement, label: null }; } token = lookahead(); if (token.type === Token.Identifier) { label = parseVariableIdentifier(); if (!Object.prototype.hasOwnProperty.call(state.labelSet, label.name)) { throwError({}, Messages.UnknownLabel, label.name); } } consumeSemicolon(); if (label === null && !state.inIteration) { throwError({}, Messages.IllegalContinue); } return { type: Syntax.ContinueStatement, label: label }; } // 12.8 The break statement function parseBreakStatement() { var token, label = null; expectKeyword('break'); // Optimize the most common form: 'break;'. if (source[index] === ';') { lex(); if (!(state.inIteration || state.inSwitch)) { throwError({}, Messages.IllegalBreak); } return { type: Syntax.BreakStatement, label: null }; } if (peekLineTerminator()) { if (!(state.inIteration || state.inSwitch)) { throwError({}, Messages.IllegalBreak); } return { type: Syntax.BreakStatement, label: null }; } token = lookahead(); if (token.type === Token.Identifier) { label = parseVariableIdentifier(); if (!Object.prototype.hasOwnProperty.call(state.labelSet, label.name)) { throwError({}, Messages.UnknownLabel, label.name); } } consumeSemicolon(); if (label === null && !(state.inIteration || state.inSwitch)) { throwError({}, Messages.IllegalBreak); } return { type: Syntax.BreakStatement, label: label }; } // 12.9 The return statement function parseReturnStatement() { var token, argument = null; expectKeyword('return'); if (!state.inFunctionBody) { throwErrorTolerant({}, Messages.IllegalReturn); } // 'return' followed by a space and an identifier is very common. if (source[index] === ' ') { if (isIdentifierStart(source[index + 1])) { argument = parseExpression(); consumeSemicolon(); return { type: Syntax.ReturnStatement, argument: argument }; } } if (peekLineTerminator()) { return { type: Syntax.ReturnStatement, argument: null }; } if (!match(';')) { token = lookahead(); if (!match('}') && token.type !== Token.EOF) { argument = parseExpression(); } } consumeSemicolon(); return { type: Syntax.ReturnStatement, argument: argument }; } // 12.10 The with statement function parseWithStatement() { var object, body; if (strict) { throwErrorTolerant({}, Messages.StrictModeWith); } expectKeyword('with'); expect('('); object = parseExpression(); expect(')'); body = parseStatement(); return { type: Syntax.WithStatement, object: object, body: body }; } // 12.10 The swith statement function parseSwitchCase() { var test, consequent = [], statement; if (matchKeyword('default')) { lex(); test = null; } else { expectKeyword('case'); test = parseExpression(); } expect(':'); while (index < length) { if (match('}') || matchKeyword('default') || matchKeyword('case')) { break; } statement = parseStatement(); if (typeof statement === 'undefined') { break; } consequent.push(statement); } return { type: Syntax.SwitchCase, test: test, consequent: consequent }; } function parseSwitchStatement() { var discriminant, cases, clause, oldInSwitch, defaultFound; expectKeyword('switch'); expect('('); discriminant = parseExpression(); expect(')'); expect('{'); cases = []; if (match('}')) { lex(); return { type: Syntax.SwitchStatement, discriminant: discriminant, cases: cases }; } oldInSwitch = state.inSwitch; state.inSwitch = true; defaultFound = false; while (index < length) { if (match('}')) { break; } clause = parseSwitchCase(); if (clause.test === null) { if (defaultFound) { throwError({}, Messages.MultipleDefaultsInSwitch); } defaultFound = true; } cases.push(clause); } state.inSwitch = oldInSwitch; expect('}'); return { type: Syntax.SwitchStatement, discriminant: discriminant, cases: cases }; } // 12.13 The throw statement function parseThrowStatement() { var argument; expectKeyword('throw'); if (peekLineTerminator()) { throwError({}, Messages.NewlineAfterThrow); } argument = parseExpression(); consumeSemicolon(); return { type: Syntax.ThrowStatement, argument: argument }; } // 12.14 The try statement function parseCatchClause() { var param; expectKeyword('catch'); expect('('); if (match(')')) { throwUnexpected(lookahead()); } param = parseVariableIdentifier(); // 12.14.1 if (strict && isRestrictedWord(param.name)) { throwErrorTolerant({}, Messages.StrictCatchVariable); } expect(')'); return { type: Syntax.CatchClause, param: param, body: parseBlock() }; } function parseTryStatement() { var block, handlers = [], finalizer = null; expectKeyword('try'); block = parseBlock(); if (matchKeyword('catch')) { handlers.push(parseCatchClause()); } if (matchKeyword('finally')) { lex(); finalizer = parseBlock(); } if (handlers.length === 0 && !finalizer) { throwError({}, Messages.NoCatchOrFinally); } return { type: Syntax.TryStatement, block: block, guardedHandlers: [], handlers: handlers, finalizer: finalizer }; } // 12.15 The debugger statement function parseDebuggerStatement() { expectKeyword('debugger'); consumeSemicolon(); return { type: Syntax.DebuggerStatement }; } // 12 Statements function parseStatement() { var token = lookahead(), expr, labeledBody; if (token.type === Token.EOF) { throwUnexpected(token); } if (token.type === Token.Punctuator) { switch (token.value) { case ';': return parseEmptyStatement(); case '{': return parseBlock(); case '(': return parseExpressionStatement(); default: break; } } if (token.type === Token.Keyword) { switch (token.value) { case 'break': return parseBreakStatement(); case 'continue': return parseContinueStatement(); case 'debugger': return parseDebuggerStatement(); case 'do': return parseDoWhileStatement(); case 'for': return parseForStatement(); case 'function': return parseFunctionDeclaration(); case 'if': return parseIfStatement(); case 'return': return parseReturnStatement(); case 'switch': return parseSwitchStatement(); case 'throw': return parseThrowStatement(); case 'try': return parseTryStatement(); case 'var': return parseVariableStatement(); case 'while': return parseWhileStatement(); case 'with': return parseWithStatement(); default: break; } } expr = parseExpression(); // 12.12 Labelled Statements if ((expr.type === Syntax.Identifier) && match(':')) { lex(); if (Object.prototype.hasOwnProperty.call(state.labelSet, expr.name)) { throwError({}, Messages.Redeclaration, 'Label', expr.name); } state.labelSet[expr.name] = true; labeledBody = parseStatement(); delete state.labelSet[expr.name]; return { type: Syntax.LabeledStatement, label: expr, body: labeledBody }; } consumeSemicolon(); return { type: Syntax.ExpressionStatement, expression: expr }; } // 13 Function Definition function parseFunctionSourceElements() { var sourceElement, sourceElements = [], token, directive, firstRestricted, oldLabelSet, oldInIteration, oldInSwitch, oldInFunctionBody; expect('{'); while (index < length) { token = lookahead(); if (token.type !== Token.StringLiteral) { break; } sourceElement = parseSourceElement(); sourceElements.push(sourceElement); if (sourceElement.expression.type !== Syntax.Literal) { // this is not directive break; } directive = sliceSource(token.range[0] + 1, token.range[1] - 1); if (directive === 'use strict') { strict = true; if (firstRestricted) { throwErrorTolerant(firstRestricted, Messages.StrictOctalLiteral); } } else { if (!firstRestricted && token.octal) { firstRestricted = token; } } } oldLabelSet = state.labelSet; oldInIteration = state.inIteration; oldInSwitch = state.inSwitch; oldInFunctionBody = state.inFunctionBody; state.labelSet = {}; state.inIteration = false; state.inSwitch = false; state.inFunctionBody = true; while (index < length) { if (match('}')) { break; } sourceElement = parseSourceElement(); if (typeof sourceElement === 'undefined') { break; } sourceElements.push(sourceElement); } expect('}'); state.labelSet = oldLabelSet; state.inIteration = oldInIteration; state.inSwitch = oldInSwitch; state.inFunctionBody = oldInFunctionBody; return { type: Syntax.BlockStatement, body: sourceElements }; } function parseFunctionDeclaration() { var id, param, params = [], body, token, stricted, firstRestricted, message, previousStrict, paramSet; expectKeyword('function'); token = lookahead(); id = parseVariableIdentifier(); if (strict) { if (isRestrictedWord(token.value)) { throwErrorTolerant(token, Messages.StrictFunctionName); } } else { if (isRestrictedWord(token.value)) { firstRestricted = token; message = Messages.StrictFunctionName; } else if (isStrictModeReservedWord(token.value)) { firstRestricted = token; message = Messages.StrictReservedWord; } } expect('('); if (!match(')')) { paramSet = {}; while (index < length) { token = lookahead(); param = parseVariableIdentifier(); if (strict) { if (isRestrictedWord(token.value)) { stricted = token; message = Messages.StrictParamName; } if (Object.prototype.hasOwnProperty.call(paramSet, token.value)) { stricted = token; message = Messages.StrictParamDupe; } } else if (!firstRestricted) { if (isRestrictedWord(token.value)) { firstRestricted = token; message = Messages.StrictParamName; } else if (isStrictModeReservedWord(token.value)) { firstRestricted = token; message = Messages.StrictReservedWord; } else if (Object.prototype.hasOwnProperty.call(paramSet, token.value)) { firstRestricted = token; message = Messages.StrictParamDupe; } } params.push(param); paramSet[param.name] = true; if (match(')')) { break; } expect(','); } } expect(')'); previousStrict = strict; body = parseFunctionSourceElements(); if (strict && firstRestricted) { throwError(firstRestricted, message); } if (strict && stricted) { throwErrorTolerant(stricted, message); } strict = previousStrict; return { type: Syntax.FunctionDeclaration, id: id, params: params, defaults: [], body: body, rest: null, generator: false, expression: false }; } function parseFunctionExpression() { var token, id = null, stricted, firstRestricted, message, param, params = [], body, previousStrict, paramSet; expectKeyword('function'); if (!match('(')) { token = lookahead(); id = parseVariableIdentifier(); if (strict) { if (isRestrictedWord(token.value)) { throwErrorTolerant(token, Messages.StrictFunctionName); } } else { if (isRestrictedWord(token.value)) { firstRestricted = token; message = Messages.StrictFunctionName; } else if (isStrictModeReservedWord(token.value)) { firstRestricted = token; message = Messages.StrictReservedWord; } } } expect('('); if (!match(')')) { paramSet = {}; while (index < length) { token = lookahead(); param = parseVariableIdentifier(); if (strict) { if (isRestrictedWord(token.value)) { stricted = token; message = Messages.StrictParamName; } if (Object.prototype.hasOwnProperty.call(paramSet, token.value)) { stricted = token; message = Messages.StrictParamDupe; } } else if (!firstRestricted) { if (isRestrictedWord(token.value)) { firstRestricted = token; message = Messages.StrictParamName; } else if (isStrictModeReservedWord(token.value)) { firstRestricted = token; message = Messages.StrictReservedWord; } else if (Object.prototype.hasOwnProperty.call(paramSet, token.value)) { firstRestricted = token; message = Messages.StrictParamDupe; } } params.push(param); paramSet[param.name] = true; if (match(')')) { break; } expect(','); } } expect(')'); previousStrict = strict; body = parseFunctionSourceElements(); if (strict && firstRestricted) { throwError(firstRestricted, message); } if (strict && stricted) { throwErrorTolerant(stricted, message); } strict = previousStrict; return { type: Syntax.FunctionExpression, id: id, params: params, defaults: [], body: body, rest: null, generator: false, expression: false }; } // 14 Program function parseSourceElement() { var token = lookahead(); if (token.type === Token.Keyword) { switch (token.value) { case 'const': case 'let': return parseConstLetDeclaration(token.value); case 'function': return parseFunctionDeclaration(); default: return parseStatement(); } } if (token.type !== Token.EOF) { return parseStatement(); } } function parseSourceElements() { var sourceElement, sourceElements = [], token, directive, firstRestricted; while (index < length) { token = lookahead(); if (token.type !== Token.StringLiteral) { break; } sourceElement = parseSourceElement(); sourceElements.push(sourceElement); if (sourceElement.expression.type !== Syntax.Literal) { // this is not directive break; } directive = sliceSource(token.range[0] + 1, token.range[1] - 1); if (directive === 'use strict') { strict = true; if (firstRestricted) { throwErrorTolerant(firstRestricted, Messages.StrictOctalLiteral); } } else { if (!firstRestricted && token.octal) { firstRestricted = token; } } } while (index < length) { sourceElement = parseSourceElement(); if (typeof sourceElement === 'undefined') { break; } sourceElements.push(sourceElement); } return sourceElements; } function parseProgram() { var program; strict = false; program = { type: Syntax.Program, body: parseSourceElements() }; return program; } // The following functions are needed only when the option to preserve // the comments is active. function addComment(type, value, start, end, loc) { assert(typeof start === 'number', 'Comment must have valid position'); // Because the way the actual token is scanned, often the comments // (if any) are skipped twice during the lexical analysis. // Thus, we need to skip adding a comment if the comment array already // handled it. if (extra.comments.length > 0) { if (extra.comments[extra.comments.length - 1].range[1] > start) { return; } } extra.comments.push({ type: type, value: value, range: [start, end], loc: loc }); } function scanComment() { var comment, ch, loc, start, blockComment, lineComment; comment = ''; blockComment = false; lineComment = false; while (index < length) { ch = source[index]; if (lineComment) { ch = source[index++]; if (isLineTerminator(ch)) { loc.end = { line: lineNumber, column: index - lineStart - 1 }; lineComment = false; addComment('Line', comment, start, index - 1, loc); if (ch === '\r' && source[index] === '\n') { ++index; } ++lineNumber; lineStart = index; comment = ''; } else if (index >= length) { lineComment = false; comment += ch; loc.end = { line: lineNumber, column: length - lineStart }; addComment('Line', comment, start, length, loc); } else { comment += ch; } } else if (blockComment) { if (isLineTerminator(ch)) { if (ch === '\r' && source[index + 1] === '\n') { ++index; comment += '\r\n'; } else { comment += ch; } ++lineNumber; ++index; lineStart = index; if (index >= length) { throwError({}, Messages.UnexpectedToken, 'ILLEGAL'); } } else { ch = source[index++]; if (index >= length) { throwError({}, Messages.UnexpectedToken, 'ILLEGAL'); } comment += ch; if (ch === '*') { ch = source[index]; if (ch === '/') { comment = comment.substr(0, comment.length - 1); blockComment = false; ++index; loc.end = { line: lineNumber, column: index - lineStart }; addComment('Block', comment, start, index, loc); comment = ''; } } } } else if (ch === '/') { ch = source[index + 1]; if (ch === '/') { loc = { start: { line: lineNumber, column: index - lineStart } }; start = index; index += 2; lineComment = true; if (index >= length) { loc.end = { line: lineNumber, column: index - lineStart }; lineComment = false; addComment('Line', comment, start, index, loc); } } else if (ch === '*') { start = index; index += 2; blockComment = true; loc = { start: { line: lineNumber, column: index - lineStart - 2 } }; if (index >= length) { throwError({}, Messages.UnexpectedToken, 'ILLEGAL'); } } else { break; } } else if (isWhiteSpace(ch)) { ++index; } else if (isLineTerminator(ch)) { ++index; if (ch === '\r' && source[index] === '\n') { ++index; } ++lineNumber; lineStart = index; } else { break; } } } function filterCommentLocation() { var i, entry, comment, comments = []; for (i = 0; i < extra.comments.length; ++i) { entry = extra.comments[i]; comment = { type: entry.type, value: entry.value }; if (extra.range) { comment.range = entry.range; } if (extra.loc) { comment.loc = entry.loc; } comments.push(comment); } extra.comments = comments; } function collectToken() { var start, loc, token, range, value; skipComment(); start = index; loc = { start: { line: lineNumber, column: index - lineStart } }; token = extra.advance(); loc.end = { line: lineNumber, column: index - lineStart }; if (token.type !== Token.EOF) { range = [token.range[0], token.range[1]]; value = sliceSource(token.range[0], token.range[1]); extra.tokens.push({ type: TokenName[token.type], value: value, range: range, loc: loc }); } return token; } function collectRegex() { var pos, loc, regex, token; skipComment(); pos = index; loc = { start: { line: lineNumber, column: index - lineStart } }; regex = extra.scanRegExp(); loc.end = { line: lineNumber, column: index - lineStart }; // Pop the previous token, which is likely '/' or '/=' if (extra.tokens.length > 0) { token = extra.tokens[extra.tokens.length - 1]; if (token.range[0] === pos && token.type === 'Punctuator') { if (token.value === '/' || token.value === '/=') { extra.tokens.pop(); } } } extra.tokens.push({ type: 'RegularExpression', value: regex.literal, range: [pos, index], loc: loc }); return regex; } function filterTokenLocation() { var i, entry, token, tokens = []; for (i = 0; i < extra.tokens.length; ++i) { entry = extra.tokens[i]; token = { type: entry.type, value: entry.value }; if (extra.range) { token.range = entry.range; } if (extra.loc) { token.loc = entry.loc; } tokens.push(token); } extra.tokens = tokens; } function createLiteral(token) { return { type: Syntax.Literal, value: token.value }; } function createRawLiteral(token) { return { type: Syntax.Literal, value: token.value, raw: sliceSource(token.range[0], token.range[1]) }; } function createLocationMarker() { var marker = {}; marker.range = [index, index]; marker.loc = { start: { line: lineNumber, column: index - lineStart }, end: { line: lineNumber, column: index - lineStart } }; marker.end = function () { this.range[1] = index; this.loc.end.line = lineNumber; this.loc.end.column = index - lineStart; }; marker.applyGroup = function (node) { if (extra.range) { node.groupRange = [this.range[0], this.range[1]]; } if (extra.loc) { node.groupLoc = { start: { line: this.loc.start.line, column: this.loc.start.column }, end: { line: this.loc.end.line, column: this.loc.end.column } }; } }; marker.apply = function (node) { if (extra.range) { node.range = [this.range[0], this.range[1]]; } if (extra.loc) { node.loc = { start: { line: this.loc.start.line, column: this.loc.start.column }, end: { line: this.loc.end.line, column: this.loc.end.column } }; } }; return marker; } function trackGroupExpression() { var marker, expr; skipComment(); marker = createLocationMarker(); expect('('); expr = parseExpression(); expect(')'); marker.end(); marker.applyGroup(expr); return expr; } function trackLeftHandSideExpression() { var marker, expr; skipComment(); marker = createLocationMarker(); expr = matchKeyword('new') ? parseNewExpression() : parsePrimaryExpression(); while (match('.') || match('[')) { if (match('[')) { expr = { type: Syntax.MemberExpression, computed: true, object: expr, property: parseComputedMember() }; marker.end(); marker.apply(expr); } else { expr = { type: Syntax.MemberExpression, computed: false, object: expr, property: parseNonComputedMember() }; marker.end(); marker.apply(expr); } } return expr; } function trackLeftHandSideExpressionAllowCall() { var marker, expr; skipComment(); marker = createLocationMarker(); expr = matchKeyword('new') ? parseNewExpression() : parsePrimaryExpression(); while (match('.') || match('[') || match('(')) { if (match('(')) { expr = { type: Syntax.CallExpression, callee: expr, 'arguments': parseArguments() }; marker.end(); marker.apply(expr); } else if (match('[')) { expr = { type: Syntax.MemberExpression, computed: true, object: expr, property: parseComputedMember() }; marker.end(); marker.apply(expr); } else { expr = { type: Syntax.MemberExpression, computed: false, object: expr, property: parseNonComputedMember() }; marker.end(); marker.apply(expr); } } return expr; } function filterGroup(node) { var n, i, entry; n = (Object.prototype.toString.apply(node) === '[object Array]') ? [] : {}; for (i in node) { if (node.hasOwnProperty(i) && i !== 'groupRange' && i !== 'groupLoc') { entry = node[i]; if (entry === null || typeof entry !== 'object' || entry instanceof RegExp) { n[i] = entry; } else { n[i] = filterGroup(entry); } } } return n; } function wrapTrackingFunction(range, loc) { return function (parseFunction) { function isBinary(node) { return node.type === Syntax.LogicalExpression || node.type === Syntax.BinaryExpression; } function visit(node) { var start, end; if (isBinary(node.left)) { visit(node.left); } if (isBinary(node.right)) { visit(node.right); } if (range) { if (node.left.groupRange || node.right.groupRange) { start = node.left.groupRange ? node.left.groupRange[0] : node.left.range[0]; end = node.right.groupRange ? node.right.groupRange[1] : node.right.range[1]; node.range = [start, end]; } else if (typeof node.range === 'undefined') { start = node.left.range[0]; end = node.right.range[1]; node.range = [start, end]; } } if (loc) { if (node.left.groupLoc || node.right.groupLoc) { start = node.left.groupLoc ? node.left.groupLoc.start : node.left.loc.start; end = node.right.groupLoc ? node.right.groupLoc.end : node.right.loc.end; node.loc = { start: start, end: end }; } else if (typeof node.loc === 'undefined') { node.loc = { start: node.left.loc.start, end: node.right.loc.end }; } } } return function () { var marker, node; skipComment(); marker = createLocationMarker(); node = parseFunction.apply(null, arguments); marker.end(); if (range && typeof node.range === 'undefined') { marker.apply(node); } if (loc && typeof node.loc === 'undefined') { marker.apply(node); } if (isBinary(node)) { visit(node); } return node; }; }; } function patch() { var wrapTracking; if (extra.comments) { extra.skipComment = skipComment; skipComment = scanComment; } if (extra.raw) { extra.createLiteral = createLiteral; createLiteral = createRawLiteral; } if (extra.range || extra.loc) { extra.parseGroupExpression = parseGroupExpression; extra.parseLeftHandSideExpression = parseLeftHandSideExpression; extra.parseLeftHandSideExpressionAllowCall = parseLeftHandSideExpressionAllowCall; parseGroupExpression = trackGroupExpression; parseLeftHandSideExpression = trackLeftHandSideExpression; parseLeftHandSideExpressionAllowCall = trackLeftHandSideExpressionAllowCall; wrapTracking = wrapTrackingFunction(extra.range, extra.loc); extra.parseAdditiveExpression = parseAdditiveExpression; extra.parseAssignmentExpression = parseAssignmentExpression; extra.parseBitwiseANDExpression = parseBitwiseANDExpression; extra.parseBitwiseORExpression = parseBitwiseORExpression; extra.parseBitwiseXORExpression = parseBitwiseXORExpression; extra.parseBlock = parseBlock; extra.parseFunctionSourceElements = parseFunctionSourceElements; extra.parseCatchClause = parseCatchClause; extra.parseComputedMember = parseComputedMember; extra.parseConditionalExpression = parseConditionalExpression; extra.parseConstLetDeclaration = parseConstLetDeclaration; extra.parseEqualityExpression = parseEqualityExpression; extra.parseExpression = parseExpression; extra.parseForVariableDeclaration = parseForVariableDeclaration; extra.parseFunctionDeclaration = parseFunctionDeclaration; extra.parseFunctionExpression = parseFunctionExpression; extra.parseLogicalANDExpression = parseLogicalANDExpression; extra.parseLogicalORExpression = parseLogicalORExpression; extra.parseMultiplicativeExpression = parseMultiplicativeExpression; extra.parseNewExpression = parseNewExpression; extra.parseNonComputedProperty = parseNonComputedProperty; extra.parseObjectProperty = parseObjectProperty; extra.parseObjectPropertyKey = parseObjectPropertyKey; extra.parsePostfixExpression = parsePostfixExpression; extra.parsePrimaryExpression = parsePrimaryExpression; extra.parseProgram = parseProgram; extra.parsePropertyFunction = parsePropertyFunction; extra.parseRelationalExpression = parseRelationalExpression; extra.parseStatement = parseStatement; extra.parseShiftExpression = parseShiftExpression; extra.parseSwitchCase = parseSwitchCase; extra.parseUnaryExpression = parseUnaryExpression; extra.parseVariableDeclaration = parseVariableDeclaration; extra.parseVariableIdentifier = parseVariableIdentifier; parseAdditiveExpression = wrapTracking(extra.parseAdditiveExpression); parseAssignmentExpression = wrapTracking(extra.parseAssignmentExpression); parseBitwiseANDExpression = wrapTracking(extra.parseBitwiseANDExpression); parseBitwiseORExpression = wrapTracking(extra.parseBitwiseORExpression); parseBitwiseXORExpression = wrapTracking(extra.parseBitwiseXORExpression); parseBlock = wrapTracking(extra.parseBlock); parseFunctionSourceElements = wrapTracking(extra.parseFunctionSourceElements); parseCatchClause = wrapTracking(extra.parseCatchClause); parseComputedMember = wrapTracking(extra.parseComputedMember); parseConditionalExpression = wrapTracking(extra.parseConditionalExpression); parseConstLetDeclaration = wrapTracking(extra.parseConstLetDeclaration); parseEqualityExpression = wrapTracking(extra.parseEqualityExpression); parseExpression = wrapTracking(extra.parseExpression); parseForVariableDeclaration = wrapTracking(extra.parseForVariableDeclaration); parseFunctionDeclaration = wrapTracking(extra.parseFunctionDeclaration); parseFunctionExpression = wrapTracking(extra.parseFunctionExpression); parseLeftHandSideExpression = wrapTracking(parseLeftHandSideExpression); parseLogicalANDExpression = wrapTracking(extra.parseLogicalANDExpression); parseLogicalORExpression = wrapTracking(extra.parseLogicalORExpression); parseMultiplicativeExpression = wrapTracking(extra.parseMultiplicativeExpression); parseNewExpression = wrapTracking(extra.parseNewExpression); parseNonComputedProperty = wrapTracking(extra.parseNonComputedProperty); parseObjectProperty = wrapTracking(extra.parseObjectProperty); parseObjectPropertyKey = wrapTracking(extra.parseObjectPropertyKey); parsePostfixExpression = wrapTracking(extra.parsePostfixExpression); parsePrimaryExpression = wrapTracking(extra.parsePrimaryExpression); parseProgram = wrapTracking(extra.parseProgram); parsePropertyFunction = wrapTracking(extra.parsePropertyFunction); parseRelationalExpression = wrapTracking(extra.parseRelationalExpression); parseStatement = wrapTracking(extra.parseStatement); parseShiftExpression = wrapTracking(extra.parseShiftExpression); parseSwitchCase = wrapTracking(extra.parseSwitchCase); parseUnaryExpression = wrapTracking(extra.parseUnaryExpression); parseVariableDeclaration = wrapTracking(extra.parseVariableDeclaration); parseVariableIdentifier = wrapTracking(extra.parseVariableIdentifier); } if (typeof extra.tokens !== 'undefined') { extra.advance = advance; extra.scanRegExp = scanRegExp; advance = collectToken; scanRegExp = collectRegex; } } function unpatch() { if (typeof extra.skipComment === 'function') { skipComment = extra.skipComment; } if (extra.raw) { createLiteral = extra.createLiteral; } if (extra.range || extra.loc) { parseAdditiveExpression = extra.parseAdditiveExpression; parseAssignmentExpression = extra.parseAssignmentExpression; parseBitwiseANDExpression = extra.parseBitwiseANDExpression; parseBitwiseORExpression = extra.parseBitwiseORExpression; parseBitwiseXORExpression = extra.parseBitwiseXORExpression; parseBlock = extra.parseBlock; parseFunctionSourceElements = extra.parseFunctionSourceElements; parseCatchClause = extra.parseCatchClause; parseComputedMember = extra.parseComputedMember; parseConditionalExpression = extra.parseConditionalExpression; parseConstLetDeclaration = extra.parseConstLetDeclaration; parseEqualityExpression = extra.parseEqualityExpression; parseExpression = extra.parseExpression; parseForVariableDeclaration = extra.parseForVariableDeclaration; parseFunctionDeclaration = extra.parseFunctionDeclaration; parseFunctionExpression = extra.parseFunctionExpression; parseGroupExpression = extra.parseGroupExpression; parseLeftHandSideExpression = extra.parseLeftHandSideExpression; parseLeftHandSideExpressionAllowCall = extra.parseLeftHandSideExpressionAllowCall; parseLogicalANDExpression = extra.parseLogicalANDExpression; parseLogicalORExpression = extra.parseLogicalORExpression; parseMultiplicativeExpression = extra.parseMultiplicativeExpression; parseNewExpression = extra.parseNewExpression; parseNonComputedProperty = extra.parseNonComputedProperty; parseObjectProperty = extra.parseObjectProperty; parseObjectPropertyKey = extra.parseObjectPropertyKey; parsePrimaryExpression = extra.parsePrimaryExpression; parsePostfixExpression = extra.parsePostfixExpression; parseProgram = extra.parseProgram; parsePropertyFunction = extra.parsePropertyFunction; parseRelationalExpression = extra.parseRelationalExpression; parseStatement = extra.parseStatement; parseShiftExpression = extra.parseShiftExpression; parseSwitchCase = extra.parseSwitchCase; parseUnaryExpression = extra.parseUnaryExpression; parseVariableDeclaration = extra.parseVariableDeclaration; parseVariableIdentifier = extra.parseVariableIdentifier; } if (typeof extra.scanRegExp === 'function') { advance = extra.advance; scanRegExp = extra.scanRegExp; } } function stringToArray(str) { var length = str.length, result = [], i; for (i = 0; i < length; ++i) { result[i] = str.charAt(i); } return result; } function parse(code, options) { var program, toString; toString = String; if (typeof code !== 'string' && !(code instanceof String)) { code = toString(code); } source = code; index = 0; lineNumber = (source.length > 0) ? 1 : 0; lineStart = 0; length = source.length; buffer = null; state = { allowIn: true, labelSet: {}, inFunctionBody: false, inIteration: false, inSwitch: false }; extra = {}; if (typeof options !== 'undefined') { extra.range = (typeof options.range === 'boolean') && options.range; extra.loc = (typeof options.loc === 'boolean') && options.loc; extra.raw = (typeof options.raw === 'boolean') && options.raw; if (typeof options.tokens === 'boolean' && options.tokens) { extra.tokens = []; } if (typeof options.comment === 'boolean' && options.comment) { extra.comments = []; } if (typeof options.tolerant === 'boolean' && options.tolerant) { extra.errors = []; } } if (length > 0) { if (typeof source[0] === 'undefined') { // Try first to convert to a string. This is good as fast path // for old IE which understands string indexing for string // literals only and not for string object. if (code instanceof String) { source = code.valueOf(); } // Force accessing the characters via an array. if (typeof source[0] === 'undefined') { source = stringToArray(code); } } } patch(); try { program = parseProgram(); if (typeof extra.comments !== 'undefined') { filterCommentLocation(); program.comments = extra.comments; } if (typeof extra.tokens !== 'undefined') { filterTokenLocation(); program.tokens = extra.tokens; } if (typeof extra.errors !== 'undefined') { program.errors = extra.errors; } if (extra.range || extra.loc) { program.body = filterGroup(program.body); } } catch (e) { throw e; } finally { unpatch(); extra = {}; } return program; } // Sync with package.json. exports.version = '1.0.4'; exports.parse = parse; // Deep copy. exports.Syntax = (function () { var name, types = {}; if (typeof Object.create === 'function') { types = Object.create(null); } for (name in Syntax) { if (Syntax.hasOwnProperty(name)) { types[name] = Syntax[name]; } } if (typeof Object.freeze === 'function') { Object.freeze(types); } return types; }()); })); /* vim: set sw=4 ts=4 et tw=80 : */ return module.exports; })({exports:{}}); var index = (function (module, global) { var exports = module.exports; var parse = esprima.parse var hoist = index$1 var InfiniteChecker = infiniteChecker var Primitives = primitives module.exports = safeEval module.exports.FunctionFactory = FunctionFactory module.exports.Function = FunctionFactory() var maxIterations = 1000000 // 'eval' with a controlled environment function safeEval(src, parentContext){ var tree = prepareAst(src) var context = Object.create(parentContext || {}) return finalValue(evaluateAst(tree, context)) } // create a 'Function' constructor for a controlled environment function FunctionFactory(parentContext){ var context = Object.create(parentContext || {}) return function Function() { // normalize arguments array var args = Array.prototype.slice.call(arguments) var src = args.slice(-1)[0] args = args.slice(0,-1) if (typeof src === 'string'){ //HACK: esprima doesn't like returns outside functions src = parse('function a(){' + src + '}').body[0].body } var tree = prepareAst(src) return getFunction(tree, args, context) } } // takes an AST or js source and returns an AST function prepareAst(src){ var tree = (typeof src === 'string') ? parse(src) : src return hoist(tree) } // evaluate an AST in the given context function evaluateAst(tree, context){ var safeFunction = FunctionFactory(context) var primitives = Primitives(context) // block scoped context for catch (ex) and 'let' var blockContext = context return walk(tree) // recursively walk every node in an array function walkAll(nodes){ var result = undefined for (var i=0;i<nodes.length;i++){ var childNode = nodes[i] if (childNode.type === 'EmptyStatement') continue result = walk(childNode) if (result instanceof ReturnValue){ return result } } return result } // recursively evalutate the node of an AST function walk(node){ if (!node) return switch (node.type) { case 'Program': return walkAll(node.body) case 'BlockStatement': enterBlock() var result = walkAll(node.body) leaveBlock() return result case 'FunctionDeclaration': var params = node.params.map(getName) var value = getFunction(node.body, params, blockContext) return context[node.id.name] = value case 'FunctionExpression': var params = node.params.map(getName) return getFunction(node.body, params, blockContext) case 'ReturnStatement': var value = walk(node.argument) return new ReturnValue('return', value) case 'BreakStatement': return new ReturnValue('break') case 'ContinueStatement': return new ReturnValue('continue') case 'ExpressionStatement': return walk(node.expression) case 'AssignmentExpression': return setValue(blockContext, node.left, node.right, node.operator) case 'UpdateExpression': return setValue(blockContext, node.argument, null, node.operator) case 'VariableDeclaration': node.declarations.forEach(function(declaration){ var target = node.kind === 'let' ? blockContext : context if (declaration.init){ target[declaration.id.name] = walk(declaration.init) } else { target[declaration.id.name] = undefined } }) break case 'SwitchStatement': var defaultHandler = null var matched = false var value = walk(node.discriminant) var result = undefined enterBlock() var i = 0 while (result == null){ if (i<node.cases.length){ if (node.cases[i].test){ // check or fall through matched = matched || (walk(node.cases[i].test) === value) } else if (defaultHandler == null) { defaultHandler = i } if (matched){ var r = walkAll(node.cases[i].consequent) if (r instanceof ReturnValue){ // break out if (r.type == 'break') break result = r } } i += 1 // continue } else if (!matched && defaultHandler != null){ // go back and do the default handler i = defaultHandler matched = true } else { // nothing we can do break } } leaveBlock() return result case 'IfStatement': if (walk(node.test)){ return walk(node.consequent) } else if (node.alternate) { return walk(node.alternate) } case 'ForStatement': var infinite = InfiniteChecker(maxIterations) var result = undefined enterBlock() // allow lets on delarations for (walk(node.init); walk(node.test); walk(node.update)){ var r = walk(node.body) // handle early return, continue and break if (r instanceof ReturnValue){ if (r.type == 'continue') continue if (r.type == 'break') break result = r break } infinite.check() } leaveBlock() return result case 'ForInStatement': var infinite = InfiniteChecker(maxIterations) var result = undefined var value = walk(node.right) var property = node.left var target = context enterBlock() if (property.type == 'VariableDeclaration'){ walk(property) property = property.declarations[0].id if (property.kind === 'let'){ target = blockContext } } for (var key in value){ setValue(target, property, {type: 'Literal', value: key}) var r = walk(node.body) // handle early return, continue and break if (r instanceof ReturnValue){ if (r.type == 'continue') continue if (r.type == 'break') break result = r break } infinite.check() } leaveBlock() return result case 'WhileStatement': var infinite = InfiniteChecker(maxIterations) while (walk(node.test)){ walk(node.body) infinite.check() } break case 'TryStatement': try { walk(node.block) } catch (error) { enterBlock() var catchClause = node.handlers[0] if (catchClause) { blockContext[catchClause.param.name] = error walk(catchClause.body) } leaveBlock() } finally { if (node.finalizer) { walk(node.finalizer) } } break case 'Literal': return node.value case 'UnaryExpression': var val = walk(node.argument) switch(node.operator) { case '+': return +val case '-': return -val case '~': return ~val case '!': return !val case 'typeof': return typeof val default: return unsupportedExpression(node) } case 'ArrayExpression': var obj = blockContext['Array']() for (var i=0;i<node.elements.length;i++){ obj.push(walk(node.elements[i])) } return obj case 'ObjectExpression': var obj = blockContext['Object']() for (var i = 0; i < node.properties.length; i++) { var prop = node.properties[i] var value = (prop.value === null) ? prop.value : walk(prop.value) obj[prop.key.value || prop.key.name] = value } return obj case 'NewExpression': var args = node.arguments.map(function(arg){ return walk(arg) }) var target = walk(node.callee) return primitives.applyNew(target, args) case 'BinaryExpression': var l = walk(node.left) var r = walk(node.right) switch(node.operator) { case '==': return l === r case '===': return l === r case '!=': return l != r case '!==': return l !== r case '+': return l + r case '-': return l - r case '*': return l * r case '/': return l / r case '%': return l % r case '<': return l < r case '<=': return l <= r case '>': return l > r case '>=': return l >= r case '|': return l | r case '&': return l & r case '^': return l ^ r case 'instanceof': return l instanceof r default: return unsupportedExpression(node) } case 'LogicalExpression': switch(node.operator) { case '&&': return walk(node.left) && walk(node.right) case '||': return walk(node.left) || walk(node.right) default: return unsupportedExpression(node) } case 'ThisExpression': return blockContext['this'] case 'Identifier': if (node.name === 'undefined'){ return undefined } else if (hasProperty(blockContext, node.name, primitives)){ return finalValue(blockContext[node.name]) } else { throw new ReferenceError(node.name + ' is not defined') } case 'CallExpression': var args = node.arguments.map(function(arg){ return walk(arg) }) var object = null var target = walk(node.callee) if (node.callee.type === 'MemberExpression'){ object = walk(node.callee.object) } return target.apply(object, args) case 'MemberExpression': var obj = walk(node.object) if (node.computed){ var prop = walk(node.property) } else { var prop = node.property.name } obj = primitives.getPropertyObject(obj, prop) return checkValue(obj[prop]); case 'ConditionalExpression': var val = walk(node.test) return val ? walk(node.consequent) : walk(node.alternate) case 'EmptyStatement': return default: return unsupportedExpression(node) } } // safely retrieve a value function checkValue(value){ if (value === Function$1){ value = safeFunction } return finalValue(value) } // block scope context control function enterBlock(){ blockContext = Object.create(blockContext) } function leaveBlock(){ blockContext = Object.getPrototypeOf(blockContext) } // set a value in the specified context if allowed function setValue(object, left, right, operator){ var name = null if (left.type === 'Identifier'){ name = left.name // handle parent context shadowing object = objectForKey(object, name, primitives) } else if (left.type === 'MemberExpression'){ if (left.computed){ name = walk(left.property) } else { name = left.property.name } object = walk(left.object) } // stop built in properties from being able to be changed if (canSetProperty(object, name, primitives)){ switch(operator) { case undefined: return object[name] = walk(right) case '=': return object[name] = walk(right) case '+=': return object[name] += walk(right) case '-=': return object[name] -= walk(right) case '++': return object[name]++ case '--': return object[name]-- } } } } // when an unsupported expression is encountered, throw an error function unsupportedExpression(node){ console.error(node) var err = new Error('Unsupported expression: ' + node.type) err.node = node throw err } // walk a provided object's prototypal hierarchy to retrieve an inherited object function objectForKey(object, key, primitives){ var proto = primitives.getPrototypeOf(object) if (!proto || hasOwnProperty(object, key)){ return object } else { return objectForKey(proto, key, primitives) } } function hasProperty(object, key, primitives){ var proto = primitives.getPrototypeOf(object) var hasOwn = hasOwnProperty(object, key) if (object[key] !== undefined){ return true } else if (!proto || hasOwn){ return hasOwn } else { return hasProperty(proto, key, primitives) } } function hasOwnProperty(object, key){ return Object.prototype.hasOwnProperty.call(object, key) } function propertyIsEnumerable(object, key){ return Object.prototype.propertyIsEnumerable.call(object, key) } // determine if we have write access to a property function canSetProperty(object, property, primitives){ if (property === '__proto__' || primitives.isPrimitive(object)){ return false } else if (object != null){ if (hasOwnProperty(object, property)){ if (propertyIsEnumerable(object, property)){ return true } else { return false } } else { return canSetProperty(primitives.getPrototypeOf(object), property, primitives) } } else { return true } } // generate a function with specified context function getFunction(body, params, parentContext){ return function(){ var context = Object.create(parentContext) if (this == global){ context['this'] = null } else { context['this'] = this } // normalize arguments array var args = Array.prototype.slice.call(arguments) context['arguments'] = arguments args.forEach(function(arg,idx){ var param = params[idx] if (param){ context[param] = arg } }) var result = evaluateAst(body, context) if (result instanceof ReturnValue){ return result.value } } } function finalValue(value){ if (value instanceof ReturnValue){ return value.value } return value } // get the name of an identifier function getName(identifier){ return identifier.name } // a ReturnValue struct for differentiating between expression result and return statement function ReturnValue(type, value){ this.type = type this.value = value } return module.exports; })({exports:{}}, __commonjs_global); var Function$1 = index.Function; var pathCache = new Cache(1000); // actions var APPEND = 0; var PUSH = 1; var INC_SUB_PATH_DEPTH = 2; var PUSH_SUB_PATH = 3; // states var BEFORE_PATH = 0; var IN_PATH = 1; var BEFORE_IDENT = 2; var IN_IDENT = 3; var IN_SUB_PATH = 4; var IN_SINGLE_QUOTE = 5; var IN_DOUBLE_QUOTE = 6; var AFTER_PATH = 7; var ERROR = 8; var pathStateMachine = []; pathStateMachine[BEFORE_PATH] = { 'ws': [BEFORE_PATH], 'ident': [IN_IDENT, APPEND], '[': [IN_SUB_PATH], 'eof': [AFTER_PATH] }; pathStateMachine[IN_PATH] = { 'ws': [IN_PATH], '.': [BEFORE_IDENT], '[': [IN_SUB_PATH], 'eof': [AFTER_PATH] }; pathStateMachine[BEFORE_IDENT] = { 'ws': [BEFORE_IDENT], 'ident': [IN_IDENT, APPEND] }; pathStateMachine[IN_IDENT] = { 'ident': [IN_IDENT, APPEND], '0': [IN_IDENT, APPEND], 'number': [IN_IDENT, APPEND], 'ws': [IN_PATH, PUSH], '.': [BEFORE_IDENT, PUSH], '[': [IN_SUB_PATH, PUSH], 'eof': [AFTER_PATH, PUSH] }; pathStateMachine[IN_SUB_PATH] = { "'": [IN_SINGLE_QUOTE, APPEND], '"': [IN_DOUBLE_QUOTE, APPEND], '[': [IN_SUB_PATH, INC_SUB_PATH_DEPTH], ']': [IN_PATH, PUSH_SUB_PATH], 'eof': ERROR, 'else': [IN_SUB_PATH, APPEND] }; pathStateMachine[IN_SINGLE_QUOTE] = { "'": [IN_SUB_PATH, APPEND], 'eof': ERROR, 'else': [IN_SINGLE_QUOTE, APPEND] }; pathStateMachine[IN_DOUBLE_QUOTE] = { '"': [IN_SUB_PATH, APPEND], 'eof': ERROR, 'else': [IN_DOUBLE_QUOTE, APPEND] }; /** * Determine the type of a character in a keypath. * * @param {Char} ch * @return {String} type */ function getPathCharType(ch) { if (ch === undefined) { return 'eof'; } var code = ch.charCodeAt(0); switch (code) { case 0x5B: // [ case 0x5D: // ] case 0x2E: // . case 0x22: // " case 0x27: // ' case 0x30: // 0 return ch; case 0x5F: // _ case 0x24: // $ return 'ident'; case 0x20: // Space case 0x09: // Tab case 0x0A: // Newline case 0x0D: // Return case 0xA0: // No-break space case 0xFEFF: // Byte Order Mark case 0x2028: // Line Separator case 0x2029: // Paragraph Separator return 'ws'; } // a-z, A-Z if (code >= 0x61 && code <= 0x7A || code >= 0x41 && code <= 0x5A) { return 'ident'; } // 1-9 if (code >= 0x31 && code <= 0x39) { return 'number'; } return 'else'; } /** * Format a subPath, return its plain form if it is * a literal string or number. Otherwise prepend the * dynamic indicator (*). * * @param {String} path * @return {String} */ function formatSubPath(path) { var trimmed = path.trim(); // invalid leading 0 if (path.charAt(0) === '0' && isNaN(path)) { return false; } return isLiteral(trimmed) ? stripQuotes(trimmed) : '*' + trimmed; } /** * Parse a string path into an array of segments * * @param {String} path * @return {Array|undefined} */ function parse(path) { var keys = []; var index = -1; var mode = BEFORE_PATH; var subPathDepth = 0; var c, newChar, key, type, transition, action, typeMap; var actions = []; actions[PUSH] = function () { if (key !== undefined) { keys.push(key); key = undefined; } }; actions[APPEND] = function () { if (key === undefined) { key = newChar; } else { key += newChar; } }; actions[INC_SUB_PATH_DEPTH] = function () { actions[APPEND](); subPathDepth++; }; actions[PUSH_SUB_PATH] = function () { if (subPathDepth > 0) { subPathDepth--; mode = IN_SUB_PATH; actions[APPEND](); } else { subPathDepth = 0; key = formatSubPath(key); if (key === false) { return false; } else { actions[PUSH](); } } }; function maybeUnescapeQuote() { var nextChar = path[index + 1]; if (mode === IN_SINGLE_QUOTE && nextChar === "'" || mode === IN_DOUBLE_QUOTE && nextChar === '"') { index++; newChar = '\\' + nextChar; actions[APPEND](); return true; } } while (mode != null) { index++; c = path[index]; if (c === '\\' && maybeUnescapeQuote()) { continue; } type = getPathCharType(c); typeMap = pathStateMachine[mode]; transition = typeMap[type] || typeMap['else'] || ERROR; if (transition === ERROR) { return; // parse error } mode = transition[0]; action = actions[transition[1]]; if (action) { newChar = transition[2]; newChar = newChar === undefined ? c : newChar; if (action() === false) { return; } } if (mode === AFTER_PATH) { keys.raw = path; return keys; } } } /** * External parse that check for a cache hit first * * @param {String} path * @return {Array|undefined} */ function parsePath(path) { var hit = pathCache.get(path); if (!hit) { hit = parse(path); if (hit) { pathCache.put(path, hit); } } return hit; } /** * Get from an object from a path string * * @param {Object} obj * @param {String} path */ function getPath(obj, path) { return parseExpression(path).get(obj); } /** * Warn against setting non-existent root path on a vm. */ var warnNonExistent; if (process.env.NODE_ENV !== 'production') { warnNonExistent = function (path) { warn('You are setting a non-existent path "' + path.raw + '" ' + 'on a vm instance. Consider pre-initializing the property ' + 'with the "data" option for more reliable reactivity ' + 'and better performance.'); }; } /** * Set on an object from a path * * @param {Object} obj * @param {String | Array} path * @param {*} val */ function setPath(obj, path, val) { var original = obj; if (typeof path === 'string') { path = parse(path); } if (!path || !isObject(obj)) { return false; } var last, key; for (var i = 0, l = path.length; i < l; i++) { last = obj; key = path[i]; if (key.charAt(0) === '*') { key = parseExpression(key.slice(1)).get.call(original, original); } if (i < l - 1) { obj = obj[key]; if (!isObject(obj)) { obj = {}; if (process.env.NODE_ENV !== 'production' && last._isVue) { warnNonExistent(path); } set(last, key, obj); } } else { if (isArray(obj)) { obj.$set(key, val); } else if (key in obj) { obj[key] = val; } else { if (process.env.NODE_ENV !== 'production' && obj._isVue) { warnNonExistent(path); } set(obj, key, val); } } } return true; } var path = Object.freeze({ parsePath: parsePath, getPath: getPath, setPath: setPath }); var expressionCache = new Cache(1000); var allowedKeywords = 'Math,Date,this,true,false,null,undefined,Infinity,NaN,' + 'isNaN,isFinite,decodeURI,decodeURIComponent,encodeURI,' + 'encodeURIComponent,parseInt,parseFloat'; var allowedKeywordsRE = new RegExp('^(' + allowedKeywords.replace(/,/g, '\\b|') + '\\b)'); // keywords that don't make sense inside expressions var improperKeywords = 'break,case,class,catch,const,continue,debugger,default,' + 'delete,do,else,export,extends,finally,for,function,if,' + 'import,in,instanceof,let,return,super,switch,throw,try,' + 'var,while,with,yield,enum,await,implements,package,' + 'protected,static,interface,private,public'; var improperKeywordsRE = new RegExp('^(' + improperKeywords.replace(/,/g, '\\b|') + '\\b)'); var wsRE = /\s/g; var newlineRE = /\n/g; var saveRE = /[\{,]\s*[\w\$_]+\s*:|('(?:[^'\\]|\\.)*'|"(?:[^"\\]|\\.)*"|`(?:[^`\\]|\\.)*\$\{|\}(?:[^`\\]|\\.)*`|`(?:[^`\\]|\\.)*`)|new |typeof |void /g; var restoreRE = /"(\d+)"/g; var pathTestRE = /^[A-Za-z_$][\w$]*(?:\.[A-Za-z_$][\w$]*|\['.*?'\]|\[".*?"\]|\[\d+\]|\[[A-Za-z_$][\w$]*\])*$/; var identRE = /[^\w$\.](?:[A-Za-z_$][\w$]*)/g; var booleanLiteralRE = /^(?:true|false)$/; /** * Save / Rewrite / Restore * * When rewriting paths found in an expression, it is * possible for the same letter sequences to be found in * strings and Object literal property keys. Therefore we * remove and store these parts in a temporary array, and * restore them after the path rewrite. */ var saved = []; /** * Save replacer * * The save regex can match two possible cases: * 1. An opening object literal * 2. A string * If matched as a plain string, we need to escape its * newlines, since the string needs to be preserved when * generating the function body. * * @param {String} str * @param {String} isString - str if matched as a string * @return {String} - placeholder with index */ function save(str, isString) { var i = saved.length; saved[i] = isString ? str.replace(newlineRE, '\\n') : str; return '"' + i + '"'; } /** * Path rewrite replacer * * @param {String} raw * @return {String} */ function rewrite(raw) { var c = raw.charAt(0); var path = raw.slice(1); if (allowedKeywordsRE.test(path)) { return raw; } else { path = path.indexOf('"') > -1 ? path.replace(restoreRE, restore) : path; return c + 'scope.' + path; } } /** * Restore replacer * * @param {String} str * @param {String} i - matched save index * @return {String} */ function restore(str, i) { return saved[i]; } /** * Rewrite an expression, prefixing all path accessors with * `scope.` and generate getter/setter functions. * * @param {String} exp * @return {Function} */ function compileGetter(exp) { if (improperKeywordsRE.test(exp)) { process.env.NODE_ENV !== 'production' && warn('Avoid using reserved keywords in expression: ' + exp); } // reset state saved.length = 0; // save strings and object literal keys var body = exp.replace(saveRE, save).replace(wsRE, ''); // rewrite all paths // pad 1 space here becaue the regex matches 1 extra char body = (' ' + body).replace(identRE, rewrite).replace(restoreRE, restore); return makeGetterFn(body); } /** * Build a getter function. Requires eval. * * We isolate the try/catch so it doesn't affect the * optimization of the parse function when it is not called. * * @param {String} body * @return {Function|undefined} */ function makeGetterFn(body) { try { var fn = index.Function('scope', 'Math', 'return ' + body); return function (scope) { return fn.call(this, scope, Math); }; } catch (e) { process.env.NODE_ENV !== 'production' && warn('Invalid expression. ' + 'Generated function body: ' + body); } } /** * Compile a setter function for the expression. * * @param {String} exp * @return {Function|undefined} */ function compileSetter(exp) { var path = parsePath(exp); if (path) { return function (scope, val) { setPath(scope, path, val); }; } else { process.env.NODE_ENV !== 'production' && warn('Invalid setter expression: ' + exp); } } /** * Parse an expression into re-written getter/setters. * * @param {String} exp * @param {Boolean} needSet * @return {Function} */ function parseExpression(exp, needSet) { exp = exp.trim(); // try cache var hit = expressionCache.get(exp); if (hit) { if (needSet && !hit.set) { hit.set = compileSetter(hit.exp); } return hit; } var res = { exp: exp }; res.get = isSimplePath(exp) && exp.indexOf('[') < 0 // optimized super simple getter ? makeGetterFn('scope.' + exp) // dynamic getter : compileGetter(exp); if (needSet) { res.set = compileSetter(exp); } expressionCache.put(exp, res); return res; } /** * Check if an expression is a simple path. * * @param {String} exp * @return {Boolean} */ function isSimplePath(exp) { return pathTestRE.test(exp) && // don't treat true/false as paths !booleanLiteralRE.test(exp) && // Math constants e.g. Math.PI, Math.E etc. exp.slice(0, 5) !== 'Math.'; } var expression = Object.freeze({ parseExpression: parseExpression, isSimplePath: isSimplePath }); // we have two separate queues: one for directive updates // and one for user watcher registered via $watch(). // we want to guarantee directive updates to be called // before user watchers so that when user watchers are // triggered, the DOM would have already been in updated // state. var queueIndex; var queue = []; var userQueue = []; var has = {}; var circular = {}; var waiting = false; var internalQueueDepleted = false; /** * Reset the batcher's state. */ function resetBatcherState() { queue = []; userQueue = []; has = {}; circular = {}; waiting = internalQueueDepleted = false; } /** * Flush both queues and run the watchers. */ function flushBatcherQueue() { runBatcherQueue(queue); internalQueueDepleted = true; runBatcherQueue(userQueue); // dev tool hook /* istanbul ignore if */ if (devtools && config.devtools) { devtools.emit('flush'); } resetBatcherState(); } /** * Run the watchers in a single queue. * * @param {Array} queue */ function runBatcherQueue(queue) { // do not cache length because more watchers might be pushed // as we run existing watchers for (queueIndex = 0; queueIndex < queue.length; queueIndex++) { var watcher = queue[queueIndex]; var id = watcher.id; has[id] = null; watcher.run(); // in dev build, check and stop circular updates. if (process.env.NODE_ENV !== 'production' && has[id] != null) { circular[id] = (circular[id] || 0) + 1; if (circular[id] > config._maxUpdateCount) { queue.splice(has[id], 1); warn('You may have an infinite update loop for watcher ' + 'with expression: ' + watcher.expression); } } } } /** * Push a watcher into the watcher queue. * Jobs with duplicate IDs will be skipped unless it's * pushed when the queue is being flushed. * * @param {Watcher} watcher * properties: * - {Number} id * - {Function} run */ function pushWatcher(watcher) { var id = watcher.id; if (has[id] == null) { if (internalQueueDepleted && !watcher.user) { // an internal watcher triggered by a user watcher... // let's run it immediately after current user watcher is done. userQueue.splice(queueIndex + 1, 0, watcher); } else { // push watcher into appropriate queue var q = watcher.user ? userQueue : queue; has[id] = q.length; q.push(watcher); // queue the flush if (!waiting) { waiting = true; nextTick(flushBatcherQueue); } } } } var uid$2 = 0; /** * A watcher parses an expression, collects dependencies, * and fires callback when the expression value changes. * This is used for both the $watch() api and directives. * * @param {Vue} vm * @param {String|Function} expOrFn * @param {Function} cb * @param {Object} options * - {Array} filters * - {Boolean} twoWay * - {Boolean} deep * - {Boolean} user * - {Boolean} sync * - {Boolean} lazy * - {Function} [preProcess] * - {Function} [postProcess] * @constructor */ function Watcher(vm, expOrFn, cb, options) { // mix in options if (options) { extend(this, options); } var isFn = typeof expOrFn === 'function'; this.vm = vm; vm._watchers.push(this); this.expression = expOrFn; this.cb = cb; this.id = ++uid$2; // uid for batching this.active = true; this.dirty = this.lazy; // for lazy watchers this.deps = []; this.newDeps = []; this.depIds = Object.create(null); this.newDepIds = null; this.prevError = null; // for async error stacks // parse expression for getter/setter if (isFn) { this.getter = expOrFn; this.setter = undefined; } else { var res = parseExpression(expOrFn, this.twoWay); this.getter = res.get; this.setter = res.set; } this.value = this.lazy ? undefined : this.get(); // state for avoiding false triggers for deep and Array // watchers during vm._digest() this.queued = this.shallow = false; } /** * Evaluate the getter, and re-collect dependencies. */ Watcher.prototype.get = function () { this.beforeGet(); var scope = this.scope || this.vm; var value; try { value = this.getter.call(scope, scope); } catch (e) { if (process.env.NODE_ENV !== 'production' && config.warnExpressionErrors) { warn('Error when evaluating expression "' + this.expression + '". ' + (config.debug ? '' : 'Turn on debug mode to see stack trace.'), e); } } // "touch" every property so they are all tracked as // dependencies for deep watching if (this.deep) { traverse(value); } if (this.preProcess) { value = this.preProcess(value); } if (this.filters) { value = scope._applyFilters(value, null, this.filters, false); } if (this.postProcess) { value = this.postProcess(value); } this.afterGet(); return value; }; /** * Set the corresponding value with the setter. * * @param {*} value */ Watcher.prototype.set = function (value) { var scope = this.scope || this.vm; if (this.filters) { value = scope._applyFilters(value, this.value, this.filters, true); } try { this.setter.call(scope, scope, value); } catch (e) { if (process.env.NODE_ENV !== 'production' && config.warnExpressionErrors) { warn('Error when evaluating setter "' + this.expression + '"', e); } } // two-way sync for v-for alias var forContext = scope.$forContext; if (forContext && forContext.alias === this.expression) { if (forContext.filters) { process.env.NODE_ENV !== 'production' && warn('It seems you are using two-way binding on ' + 'a v-for alias (' + this.expression + '), and the ' + 'v-for has filters. This will not work properly. ' + 'Either remove the filters or use an array of ' + 'objects and bind to object properties instead.'); return; } forContext._withLock(function () { if (scope.$key) { // original is an object forContext.rawValue[scope.$key] = value; } else { forContext.rawValue.$set(scope.$index, value); } }); } }; /** * Prepare for dependency collection. */ Watcher.prototype.beforeGet = function () { Dep.target = this; this.newDepIds = Object.create(null); this.newDeps.length = 0; }; /** * Add a dependency to this directive. * * @param {Dep} dep */ Watcher.prototype.addDep = function (dep) { var id = dep.id; if (!this.newDepIds[id]) { this.newDepIds[id] = true; this.newDeps.push(dep); if (!this.depIds[id]) { dep.addSub(this); } } }; /** * Clean up for dependency collection. */ Watcher.prototype.afterGet = function () { Dep.target = null; var i = this.deps.length; while (i--) { var dep = this.deps[i]; if (!this.newDepIds[dep.id]) { dep.removeSub(this); } } this.depIds = this.newDepIds; var tmp = this.deps; this.deps = this.newDeps; this.newDeps = tmp; }; /** * Subscriber interface. * Will be called when a dependency changes. * * @param {Boolean} shallow */ Watcher.prototype.update = function (shallow) { if (this.lazy) { this.dirty = true; } else if (this.sync || !config.async) { this.run(); } else { // if queued, only overwrite shallow with non-shallow, // but not the other way around. this.shallow = this.queued ? shallow ? this.shallow : false : !!shallow; this.queued = true; // record before-push error stack in debug mode /* istanbul ignore if */ if (process.env.NODE_ENV !== 'production' && config.debug) { this.prevError = new Error('[vue] async stack trace'); } pushWatcher(this); } }; /** * Batcher job interface. * Will be called by the batcher. */ Watcher.prototype.run = function () { 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; but only do so if this is a // non-shallow update (caused by a vm digest). (isObject(value) || this.deep) && !this.shallow) { // set new value var oldValue = this.value; this.value = value; // in debug + async mode, when a watcher callbacks // throws, we also throw the saved before-push error // so the full cross-tick stack trace is available. var prevError = this.prevError; /* istanbul ignore if */ if (process.env.NODE_ENV !== 'production' && config.debug && prevError) { this.prevError = null; try { this.cb.call(this.vm, value, oldValue); } catch (e) { nextTick(function () { throw prevError; }, 0); throw e; } } else { this.cb.call(this.vm, value, oldValue); } } this.queued = this.shallow = false; } }; /** * Evaluate the value of the watcher. * This only gets called for lazy watchers. */ Watcher.prototype.evaluate = function () { // avoid overwriting another watcher that is being // collected. var current = Dep.target; this.value = this.get(); this.dirty = false; Dep.target = current; }; /** * Depend on all deps collected by this watcher. */ Watcher.prototype.depend = function () { var i = this.deps.length; while (i--) { this.deps[i].depend(); } }; /** * Remove self from all dependencies' subcriber list. */ Watcher.prototype.teardown = function () { 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) { this.vm._watchers.$remove(this); } var i = this.deps.length; while (i--) { this.deps[i].removeSub(this); } this.active = false; this.vm = this.cb = this.value = null; } }; /** * Recrusively traverse an object to evoke all converted * getters, so that every nested property inside the object * is collected as a "deep" dependency. * * @param {*} val */ function traverse(val) { var i, keys; if (isArray(val)) { i = val.length; while (i--) traverse(val[i]); } else if (isObject(val)) { keys = Object.keys(val); i = keys.length; while (i--) traverse(val[keys[i]]); } } var text$1 = { bind: function bind() { this.attr = this.el.nodeType === 3 ? 'data' : 'textContent'; }, update: function update(value) { this.el[this.attr] = _toString(value); } }; var templateCache = new Cache(1000); var idSelectorCache = new Cache(1000); var map = { efault: [0, '', ''], legend: [1, '<fieldset>', '</fieldset>'], tr: [2, '<table><tbody>', '</tbody></table>'], col: [2, '<table><tbody></tbody><colgroup>', '</colgroup></table>'] }; map.td = map.th = [3, '<table><tbody><tr>', '</tr></tbody></table>']; map.option = map.optgroup = [1, '<select multiple="multiple">', '</select>']; map.thead = map.tbody = map.colgroup = map.caption = map.tfoot = [1, '<table>', '</table>']; map.g = map.defs = map.symbol = map.use = map.image = map.text = map.circle = map.ellipse = map.line = map.path = map.polygon = map.polyline = map.rect = [1, '<svg ' + 'xmlns="http://www.w3.org/2000/svg" ' + 'xmlns:xlink="http://www.w3.org/1999/xlink" ' + 'xmlns:ev="http://www.w3.org/2001/xml-events"' + 'version="1.1">', '</svg>']; /** * Check if a node is a supported template node with a * DocumentFragment content. * * @param {Node} node * @return {Boolean} */ function isRealTemplate(node) { return isTemplate(node) && isFragment(node.content); } var tagRE$1 = /<([\w:-]+)/; var entityRE = /&#?\w+?;/; /** * Convert a string template to a DocumentFragment. * Determines correct wrapping by tag types. Wrapping * strategy found in jQuery & component/domify. * * @param {String} templateString * @param {Boolean} raw * @return {DocumentFragment} */ function stringToFragment(templateString, raw) { // try a cache hit first var cacheKey = raw ? templateString : templateString.trim(); var hit = templateCache.get(cacheKey); if (hit) { return hit; } var frag = document.createDocumentFragment(); var tagMatch = templateString.match(tagRE$1); var entityMatch = entityRE.test(templateString); if (!tagMatch && !entityMatch) { // text only, return a single text node. frag.appendChild(document.createTextNode(templateString)); } else { var tag = tagMatch && tagMatch[1]; var wrap = map[tag] || map.efault; var depth = wrap[0]; var prefix = wrap[1]; var suffix = wrap[2]; var node = document.createElement('div'); node.innerHTML = prefix + templateString + suffix; while (depth--) { node = node.lastChild; } var child; /* eslint-disable no-cond-assign */ while (child = node.firstChild) { /* eslint-enable no-cond-assign */ frag.appendChild(child); } } if (!raw) { trimNode(frag); } templateCache.put(cacheKey, frag); return frag; } /** * Convert a template node to a DocumentFragment. * * @param {Node} node * @return {DocumentFragment} */ function nodeToFragment(node) { // if its a template tag and the browser supports it, // its content is already a document fragment. if (isRealTemplate(node)) { trimNode(node.content); return node.content; } // script template if (node.tagName === 'SCRIPT') { return stringToFragment(node.textContent); } // normal node, clone it to avoid mutating the original var clonedNode = cloneNode(node); var frag = document.createDocumentFragment(); var child; /* eslint-disable no-cond-assign */ while (child = clonedNode.firstChild) { /* eslint-enable no-cond-assign */ frag.appendChild(child); } trimNode(frag); return frag; } // Test for the presence of the Safari template cloning bug // https://bugs.webkit.org/showug.cgi?id=137755 var hasBrokenTemplate = (function () { /* istanbul ignore else */ if (inBrowser) { var a = document.createElement('div'); a.innerHTML = '<template>1</template>'; return !a.cloneNode(true).firstChild.innerHTML; } else { return false; } })(); // Test for IE10/11 textarea placeholder clone bug var hasTextareaCloneBug = (function () { /* istanbul ignore else */ if (inBrowser) { var t = document.createElement('textarea'); t.placeholder = 't'; return t.cloneNode(true).value === 't'; } else { return false; } })(); /** * 1. Deal with Safari cloning nested <template> bug by * manually cloning all template instances. * 2. Deal with IE10/11 textarea placeholder bug by setting * the correct value after cloning. * * @param {Element|DocumentFragment} node * @return {Element|DocumentFragment} */ function cloneNode(node) { /* istanbul ignore if */ if (!node.querySelectorAll) { return node.cloneNode(); } var res = node.cloneNode(true); var i, original, cloned; /* istanbul ignore if */ if (hasBrokenTemplate) { var tempClone = res; if (isRealTemplate(node)) { node = node.content; tempClone = res.content; } original = node.querySelectorAll('template'); if (original.length) { cloned = tempClone.querySelectorAll('template'); i = cloned.length; while (i--) { cloned[i].parentNode.replaceChild(cloneNode(original[i]), cloned[i]); } } } /* istanbul ignore if */ if (hasTextareaCloneBug) { if (node.tagName === 'TEXTAREA') { res.value = node.value; } else { original = node.querySelectorAll('textarea'); if (original.length) { cloned = res.querySelectorAll('textarea'); i = cloned.length; while (i--) { cloned[i].value = original[i].value; } } } } return res; } /** * Process the template option and normalizes it into a * a DocumentFragment that can be used as a partial or a * instance template. * * @param {*} template * Possible values include: * - DocumentFragment object * - Node object of type Template * - id selector: '#some-template-id' * - template string: '<div><span>{{msg}}</span></div>' * @param {Boolean} shouldClone * @param {Boolean} raw * inline HTML interpolation. Do not check for id * selector and keep whitespace in the string. * @return {DocumentFragment|undefined} */ function parseTemplate(template, shouldClone, raw) { var node, frag; // if the template is already a document fragment, // do nothing if (isFragment(template)) { trimNode(template); return shouldClone ? cloneNode(template) : template; } if (typeof template === 'string') { // id selector if (!raw && template.charAt(0) === '#') { // id selector can be cached too frag = idSelectorCache.get(template); if (!frag) { node = document.getElementById(template.slice(1)); if (node) { frag = nodeToFragment(node); // save selector to cache idSelectorCache.put(template, frag); } } } else { // normal string template frag = stringToFragment(template, raw); } } else if (template.nodeType) { // a direct node frag = nodeToFragment(template); } return frag && shouldClone ? cloneNode(frag) : frag; } var template = Object.freeze({ cloneNode: cloneNode, parseTemplate: parseTemplate }); var html = { bind: function bind() { // a comment node means this is a binding for // {{{ inline unescaped html }}} if (this.el.nodeType === 8) { // hold nodes this.nodes = []; // replace the placeholder with proper anchor this.anchor = createAnchor('v-html'); replace(this.el, this.anchor); } }, update: function update(value) { value = _toString(value); if (this.nodes) { this.swap(value); } else { this.el.innerHTML = value; } }, swap: function swap(value) { // remove old nodes var i = this.nodes.length; while (i--) { remove(this.nodes[i]); } // convert new value to a fragment // do not attempt to retrieve from id selector var frag = parseTemplate(value, true, true); // save a reference to these nodes so we can remove later this.nodes = toArray(frag.childNodes); before(frag, this.anchor); } }; /** * Abstraction for a partially-compiled fragment. * Can optionally compile content with a child scope. * * @param {Function} linker * @param {Vue} vm * @param {DocumentFragment} frag * @param {Vue} [host] * @param {Object} [scope] * @param {Fragment} [parentFrag] */ function Fragment(linker, vm, frag, host, scope, parentFrag) { this.children = []; this.childFrags = []; this.vm = vm; this.scope = scope; this.inserted = false; this.parentFrag = parentFrag; if (parentFrag) { parentFrag.childFrags.push(this); } this.unlink = linker(vm, frag, host, scope, this); var single = this.single = frag.childNodes.length === 1 && // do not go single mode if the only node is an anchor !frag.childNodes[0].__v_anchor; if (single) { this.node = frag.childNodes[0]; this.before = singleBefore; this.remove = singleRemove; } else { this.node = createAnchor('fragment-start'); this.end = createAnchor('fragment-end'); this.frag = frag; prepend(this.node, frag); frag.appendChild(this.end); this.before = multiBefore; this.remove = multiRemove; } this.node.__v_frag = this; } /** * Call attach/detach for all components contained within * this fragment. Also do so recursively for all child * fragments. * * @param {Function} hook */ Fragment.prototype.callHook = function (hook) { var i, l; for (i = 0, l = this.childFrags.length; i < l; i++) { this.childFrags[i].callHook(hook); } for (i = 0, l = this.children.length; i < l; i++) { hook(this.children[i]); } }; /** * Insert fragment before target, single node version * * @param {Node} target * @param {Boolean} withTransition */ function singleBefore(target, withTransition) { this.inserted = true; var method = withTransition !== false ? beforeWithTransition : before; method(this.node, target, this.vm); if (inDoc(this.node)) { this.callHook(attach); } } /** * Remove fragment, single node version */ function singleRemove() { this.inserted = false; var shouldCallRemove = inDoc(this.node); var self = this; this.beforeRemove(); removeWithTransition(this.node, this.vm, function () { if (shouldCallRemove) { self.callHook(detach); } self.destroy(); }); } /** * Insert fragment before target, multi-nodes version * * @param {Node} target * @param {Boolean} withTransition */ function multiBefore(target, withTransition) { this.inserted = true; var vm = this.vm; var method = withTransition !== false ? beforeWithTransition : before; mapNodeRange(this.node, this.end, function (node) { method(node, target, vm); }); if (inDoc(this.node)) { this.callHook(attach); } } /** * Remove fragment, multi-nodes version */ function multiRemove() { this.inserted = false; var self = this; var shouldCallRemove = inDoc(this.node); this.beforeRemove(); removeNodeRange(this.node, this.end, this.vm, this.frag, function () { if (shouldCallRemove) { self.callHook(detach); } self.destroy(); }); } /** * Prepare the fragment for removal. */ Fragment.prototype.beforeRemove = function () { var i, l; for (i = 0, l = this.childFrags.length; i < l; i++) { // call the same method recursively on child // fragments, depth-first this.childFrags[i].beforeRemove(false); } for (i = 0, l = this.children.length; i < l; i++) { // Call destroy for all contained instances, // with remove:false and defer:true. // Defer is necessary because we need to // keep the children to call detach hooks // on them. this.children[i].$destroy(false, true); } var dirs = this.unlink.dirs; for (i = 0, l = dirs.length; i < l; i++) { // disable the watchers on all the directives // so that the rendered content stays the same // during removal. dirs[i]._watcher && dirs[i]._watcher.teardown(); } }; /** * Destroy the fragment. */ Fragment.prototype.destroy = function () { if (this.parentFrag) { this.parentFrag.childFrags.$remove(this); } this.node.__v_frag = null; this.unlink(); }; /** * Call attach hook for a Vue instance. * * @param {Vue} child */ function attach(child) { if (!child._isAttached && inDoc(child.$el)) { child._callHook('attached'); } } /** * Call detach hook for a Vue instance. * * @param {Vue} child */ function detach(child) { if (child._isAttached && !inDoc(child.$el)) { child._callHook('detached'); } } var linkerCache = new Cache(5000); /** * A factory that can be used to create instances of a * fragment. Caches the compiled linker if possible. * * @param {Vue} vm * @param {Element|String} el */ function FragmentFactory(vm, el) { this.vm = vm; var template; var isString = typeof el === 'string'; if (isString || isTemplate(el)) { template = parseTemplate(el, true); } else { template = document.createDocumentFragment(); template.appendChild(el); } this.template = template; // linker can be cached, but only for components var linker; var cid = vm.constructor.cid; if (cid > 0) { var cacheId = cid + (isString ? el : getOuterHTML(el)); linker = linkerCache.get(cacheId); if (!linker) { linker = compile(template, vm.$options, true); linkerCache.put(cacheId, linker); } } else { linker = compile(template, vm.$options, true); } this.linker = linker; } /** * Create a fragment instance with given host and scope. * * @param {Vue} host * @param {Object} scope * @param {Fragment} parentFrag */ FragmentFactory.prototype.create = function (host, scope, parentFrag) { var frag = cloneNode(this.template); return new Fragment(this.linker, this.vm, frag, host, scope, parentFrag); }; var ON = 700; var MODEL = 800; var BIND = 850; var TRANSITION = 1100; var EL = 1500; var COMPONENT = 1500; var PARTIAL = 1750; var FOR = 2000; var IF = 2000; var SLOT = 2100; var uid$3 = 0; var vFor = { priority: FOR, terminal: true, params: ['track-by', 'stagger', 'enter-stagger', 'leave-stagger'], bind: function bind() { // support "item in/of items" syntax var inMatch = this.expression.match(/(.*) (?:in|of) (.*)/); if (inMatch) { var itMatch = inMatch[1].match(/\((.*),(.*)\)/); if (itMatch) { this.iterator = itMatch[1].trim(); this.alias = itMatch[2].trim(); } else { this.alias = inMatch[1].trim(); } this.expression = inMatch[2]; } if (!this.alias) { process.env.NODE_ENV !== 'production' && warn('Alias is required in v-for.'); return; } // uid as a cache identifier this.id = '__v-for__' + ++uid$3; // check if this is an option list, // so that we know if we need to update the <select>'s // v-model when the option list has changed. // because v-model has a lower priority than v-for, // the v-model is not bound here yet, so we have to // retrive it in the actual updateModel() function. var tag = this.el.tagName; this.isOption = (tag === 'OPTION' || tag === 'OPTGROUP') && this.el.parentNode.tagName === 'SELECT'; // setup anchor nodes this.start = createAnchor('v-for-start'); this.end = createAnchor('v-for-end'); replace(this.el, this.end); before(this.start, this.end); // cache this.cache = Object.create(null); // fragment factory this.factory = new FragmentFactory(this.vm, this.el); }, update: function update(data) { this.diff(data); this.updateRef(); this.updateModel(); }, /** * Diff, based on new data and old data, determine the * minimum amount of DOM manipulations needed to make the * DOM reflect the new data Array. * * The algorithm diffs the new data Array by storing a * hidden reference to an owner vm instance on previously * seen data. This allows us to achieve O(n) which is * better than a levenshtein distance based algorithm, * which is O(m * n). * * @param {Array} data */ diff: function diff(data) { // check if the Array was converted from an Object var item = data[0]; var convertedFromObject = this.fromObject = isObject(item) && hasOwn(item, '$key') && hasOwn(item, '$value'); var trackByKey = this.params.trackBy; var oldFrags = this.frags; var frags = this.frags = new Array(data.length); var alias = this.alias; var iterator = this.iterator; var start = this.start; var end = this.end; var inDocument = inDoc(start); var init = !oldFrags; var i, l, frag, key, value, primitive; // First pass, go through the new Array and fill up // the new frags array. If a piece of data has a cached // instance for it, we reuse it. Otherwise build a new // instance. for (i = 0, l = data.length; i < l; i++) { item = data[i]; key = convertedFromObject ? item.$key : null; value = convertedFromObject ? item.$value : item; primitive = !isObject(value); frag = !init && this.getCachedFrag(value, i, key); if (frag) { // reusable fragment frag.reused = true; // update $index frag.scope.$index = i; // update $key if (key) { frag.scope.$key = key; } // update iterator if (iterator) { frag.scope[iterator] = key !== null ? key : i; } // update data for track-by, object repeat & // primitive values. if (trackByKey || convertedFromObject || primitive) { frag.scope[alias] = value; } } else { // new isntance frag = this.create(value, alias, i, key); frag.fresh = !init; } frags[i] = frag; if (init) { frag.before(end); } } // we're done for the initial render. if (init) { return; } // Second pass, go through the old fragments and // destroy those who are not reused (and remove them // from cache) var removalIndex = 0; var totalRemoved = oldFrags.length - frags.length; // when removing a large number of fragments, watcher removal // turns out to be a perf bottleneck, so we batch the watcher // removals into a single filter call! this.vm._vForRemoving = true; for (i = 0, l = oldFrags.length; i < l; i++) { frag = oldFrags[i]; if (!frag.reused) { this.deleteCachedFrag(frag); this.remove(frag, removalIndex++, totalRemoved, inDocument); } } this.vm._vForRemoving = false; if (removalIndex) { this.vm._watchers = this.vm._watchers.filter(function (w) { return w.active; }); } // Final pass, move/insert new fragments into the // right place. var targetPrev, prevEl, currentPrev; var insertionIndex = 0; for (i = 0, l = frags.length; i < l; i++) { frag = frags[i]; // this is the frag that we should be after targetPrev = frags[i - 1]; prevEl = targetPrev ? targetPrev.staggerCb ? targetPrev.staggerAnchor : targetPrev.end || targetPrev.node : start; if (frag.reused && !frag.staggerCb) { currentPrev = findPrevFrag(frag, start, this.id); if (currentPrev !== targetPrev && (!currentPrev || // optimization for moving a single item. // thanks to suggestions by @livoras in #1807 findPrevFrag(currentPrev, start, this.id) !== targetPrev)) { this.move(frag, prevEl); } } else { // new instance, or still in stagger. // insert with updated stagger index. this.insert(frag, insertionIndex++, prevEl, inDocument); } frag.reused = frag.fresh = false; } }, /** * Create a new fragment instance. * * @param {*} value * @param {String} alias * @param {Number} index * @param {String} [key] * @return {Fragment} */ create: function create(value, alias, index, key) { var host = this._host; // create iteration scope var parentScope = this._scope || this.vm; var scope = Object.create(parentScope); // ref holder for the scope scope.$refs = Object.create(parentScope.$refs); scope.$els = Object.create(parentScope.$els); // make sure point $parent to parent scope scope.$parent = parentScope; // for two-way binding on alias scope.$forContext = this; // define scope properties defineReactive(scope, alias, value, true /* do not observe */); defineReactive(scope, '$index', index); if (key) { defineReactive(scope, '$key', key); } else if (scope.$key) { // avoid accidental fallback def(scope, '$key', null); } if (this.iterator) { defineReactive(scope, this.iterator, key !== null ? key : index); } var frag = this.factory.create(host, scope, this._frag); frag.forId = this.id; this.cacheFrag(value, frag, index, key); return frag; }, /** * Update the v-ref on owner vm. */ updateRef: function updateRef() { var ref = this.descriptor.ref; if (!ref) return; var hash = (this._scope || this.vm).$refs; var refs; if (!this.fromObject) { refs = this.frags.map(findVmFromFrag); } else { refs = {}; this.frags.forEach(function (frag) { refs[frag.scope.$key] = findVmFromFrag(frag); }); } hash[ref] = refs; }, /** * For option lists, update the containing v-model on * parent <select>. */ updateModel: function updateModel() { if (this.isOption) { var parent = this.start.parentNode; var model = parent && parent.__v_model; if (model) { model.forceUpdate(); } } }, /** * Insert a fragment. Handles staggering. * * @param {Fragment} frag * @param {Number} index * @param {Node} prevEl * @param {Boolean} inDocument */ insert: function insert(frag, index, prevEl, inDocument) { if (frag.staggerCb) { frag.staggerCb.cancel(); frag.staggerCb = null; } var staggerAmount = this.getStagger(frag, index, null, 'enter'); if (inDocument && staggerAmount) { // create an anchor and insert it synchronously, // so that we can resolve the correct order without // worrying about some elements not inserted yet var anchor = frag.staggerAnchor; if (!anchor) { anchor = frag.staggerAnchor = createAnchor('stagger-anchor'); anchor.__v_frag = frag; } after(anchor, prevEl); var op = frag.staggerCb = cancellable(function () { frag.staggerCb = null; frag.before(anchor); remove(anchor); }); setTimeout(op, staggerAmount); } else { frag.before(prevEl.nextSibling); } }, /** * Remove a fragment. Handles staggering. * * @param {Fragment} frag * @param {Number} index * @param {Number} total * @param {Boolean} inDocument */ remove: function remove(frag, index, total, inDocument) { if (frag.staggerCb) { frag.staggerCb.cancel(); frag.staggerCb = null; // it's not possible for the same frag to be removed // twice, so if we have a pending stagger callback, // it means this frag is queued for enter but removed // before its transition started. Since it is already // destroyed, we can just leave it in detached state. return; } var staggerAmount = this.getStagger(frag, index, total, 'leave'); if (inDocument && staggerAmount) { var op = frag.staggerCb = cancellable(function () { frag.staggerCb = null; frag.remove(); }); setTimeout(op, staggerAmount); } else { frag.remove(); } }, /** * Move a fragment to a new position. * Force no transition. * * @param {Fragment} frag * @param {Node} prevEl */ move: function move(frag, prevEl) { // fix a common issue with Sortable: // if prevEl doesn't have nextSibling, this means it's // been dragged after the end anchor. Just re-position // the end anchor to the end of the container. /* istanbul ignore if */ if (!prevEl.nextSibling) { this.end.parentNode.appendChild(this.end); } frag.before(prevEl.nextSibling, false); }, /** * Cache a fragment using track-by or the object key. * * @param {*} value * @param {Fragment} frag * @param {Number} index * @param {String} [key] */ cacheFrag: function cacheFrag(value, frag, index, key) { var trackByKey = this.params.trackBy; var cache = this.cache; var primitive = !isObject(value); var id; if (key || trackByKey || primitive) { id = trackByKey ? trackByKey === '$index' ? index : value[trackByKey] : key || value; if (!cache[id]) { cache[id] = frag; } else if (trackByKey !== '$index') { process.env.NODE_ENV !== 'production' && this.warnDuplicate(value); } } else { id = this.id; if (hasOwn(value, id)) { if (value[id] === null) { value[id] = frag; } else { process.env.NODE_ENV !== 'production' && this.warnDuplicate(value); } } else { def(value, id, frag); } } frag.raw = value; }, /** * Get a cached fragment from the value/index/key * * @param {*} value * @param {Number} index * @param {String} key * @return {Fragment} */ getCachedFrag: function getCachedFrag(value, index, key) { var trackByKey = this.params.trackBy; var primitive = !isObject(value); var frag; if (key || trackByKey || primitive) { var id = trackByKey ? trackByKey === '$index' ? index : value[trackByKey] : key || value; frag = this.cache[id]; } else { frag = value[this.id]; } if (frag && (frag.reused || frag.fresh)) { process.env.NODE_ENV !== 'production' && this.warnDuplicate(value); } return frag; }, /** * Delete a fragment from cache. * * @param {Fragment} frag */ deleteCachedFrag: function deleteCachedFrag(frag) { var value = frag.raw; var trackByKey = this.params.trackBy; var scope = frag.scope; var index = scope.$index; // fix #948: avoid accidentally fall through to // a parent repeater which happens to have $key. var key = hasOwn(scope, '$key') && scope.$key; var primitive = !isObject(value); if (trackByKey || key || primitive) { var id = trackByKey ? trackByKey === '$index' ? index : value[trackByKey] : key || value; this.cache[id] = null; } else { value[this.id] = null; frag.raw = null; } }, /** * Get the stagger amount for an insertion/removal. * * @param {Fragment} frag * @param {Number} index * @param {Number} total * @param {String} type */ getStagger: function getStagger(frag, index, total, type) { type = type + 'Stagger'; var trans = frag.node.__v_trans; var hooks = trans && trans.hooks; var hook = hooks && (hooks[type] || hooks.stagger); return hook ? hook.call(frag, index, total) : index * parseInt(this.params[type] || this.params.stagger, 10); }, /** * Pre-process the value before piping it through the * filters. This is passed to and called by the watcher. */ _preProcess: function _preProcess(value) { // regardless of type, store the un-filtered raw value. this.rawValue = value; return value; }, /** * Post-process the value after it has been piped through * the filters. This is passed to and called by the watcher. * * It is necessary for this to be called during the * wathcer's dependency collection phase because we want * the v-for to update when the source Object is mutated. */ _postProcess: function _postProcess(value) { if (isArray(value)) { return value; } else if (isPlainObject(value)) { // convert plain object to array. var keys = Object.keys(value); var i = keys.length; var res = new Array(i); var key; while (i--) { key = keys[i]; res[i] = { $key: key, $value: value[key] }; } return res; } else { if (typeof value === 'number' && !isNaN(value)) { value = range(value); } return value || []; } }, unbind: function unbind() { if (this.descriptor.ref) { (this._scope || this.vm).$refs[this.descriptor.ref] = null; } if (this.frags) { var i = this.frags.length; var frag; while (i--) { frag = this.frags[i]; this.deleteCachedFrag(frag); frag.destroy(); } } } }; /** * Helper to find the previous element that is a fragment * anchor. This is necessary because a destroyed frag's * element could still be lingering in the DOM before its * leaving transition finishes, but its inserted flag * should have been set to false so we can skip them. * * If this is a block repeat, we want to make sure we only * return frag that is bound to this v-for. (see #929) * * @param {Fragment} frag * @param {Comment|Text} anchor * @param {String} id * @return {Fragment} */ function findPrevFrag(frag, anchor, id) { var el = frag.node.previousSibling; /* istanbul ignore if */ if (!el) return; frag = el.__v_frag; while ((!frag || frag.forId !== id || !frag.inserted) && el !== anchor) { el = el.previousSibling; /* istanbul ignore if */ if (!el) return; frag = el.__v_frag; } return frag; } /** * Find a vm from a fragment. * * @param {Fragment} frag * @return {Vue|undefined} */ function findVmFromFrag(frag) { var node = frag.node; // handle multi-node frag if (frag.end) { while (!node.__vue__ && node !== frag.end && node.nextSibling) { node = node.nextSibling; } } return node.__vue__; } /** * Create a range array from given number. * * @param {Number} n * @return {Array} */ function range(n) { var i = -1; var ret = new Array(Math.floor(n)); while (++i < n) { ret[i] = i; } return ret; } if (process.env.NODE_ENV !== 'production') { vFor.warnDuplicate = function (value) { warn('Duplicate value found in v-for="' + this.descriptor.raw + '": ' + JSON.stringify(value) + '. Use track-by="$index" if ' + 'you are expecting duplicate values.'); }; } var vIf = { priority: IF, terminal: true, bind: function bind() { var el = this.el; if (!el.__vue__) { // check else block var next = el.nextElementSibling; if (next && getAttr(next, 'v-else') !== null) { remove(next); this.elseEl = next; } // check main block this.anchor = createAnchor('v-if'); replace(el, this.anchor); } else { process.env.NODE_ENV !== 'production' && warn('v-if="' + this.expression + '" cannot be ' + 'used on an instance root element.'); this.invalid = true; } }, update: function update(value) { if (this.invalid) return; if (value) { if (!this.frag) { this.insert(); } } else { this.remove(); } }, insert: function insert() { if (this.elseFrag) { this.elseFrag.remove(); this.elseFrag = null; } // lazy init factory if (!this.factory) { this.factory = new FragmentFactory(this.vm, this.el); } this.frag = this.factory.create(this._host, this._scope, this._frag); this.frag.before(this.anchor); }, remove: function remove() { if (this.frag) { this.frag.remove(); this.frag = null; } if (this.elseEl && !this.elseFrag) { if (!this.elseFactory) { this.elseFactory = new FragmentFactory(this.elseEl._context || this.vm, this.elseEl); } this.elseFrag = this.elseFactory.create(this._host, this._scope, this._frag); this.elseFrag.before(this.anchor); } }, unbind: function unbind() { if (this.frag) { this.frag.destroy(); } if (this.elseFrag) { this.elseFrag.destroy(); } } }; var show = { bind: function bind() { // check else block var next = this.el.nextElementSibling; if (next && getAttr(next, 'v-else') !== null) { this.elseEl = next; } }, update: function update(value) { this.apply(this.el, value); if (this.elseEl) { this.apply(this.elseEl, !value); } }, apply: function apply(el, value) { if (inDoc(el)) { applyTransition(el, value ? 1 : -1, toggle, this.vm); } else { toggle(); } function toggle() { el.style.display = value ? '' : 'none'; } } }; var text$2 = { bind: function bind() { var self = this; var el = this.el; var isRange = el.type === 'range'; var lazy = this.params.lazy; var number = this.params.number; var debounce = this.params.debounce; // handle composition events. // http://blog.evanyou.me/2014/01/03/composition-event/ // skip this for Android because it handles composition // events quite differently. Android doesn't trigger // composition events for language input methods e.g. // Chinese, but instead triggers them for spelling // suggestions... (see Discussion/#162) var composing = false; if (!isAndroid && !isRange) { this.on('compositionstart', function () { composing = true; }); this.on('compositionend', function () { composing = false; // in IE11 the "compositionend" event fires AFTER // the "input" event, so the input handler is blocked // at the end... have to call it here. // // #1327: in lazy mode this is unecessary. if (!lazy) { self.listener(); } }); } // prevent messing with the input when user is typing, // and force update on blur. this.focused = false; if (!isRange && !lazy) { this.on('focus', function () { self.focused = true; }); this.on('blur', function () { self.focused = false; // do not sync value after fragment removal (#2017) if (!self._frag || self._frag.inserted) { self.rawListener(); } }); } // Now attach the main listener this.listener = this.rawListener = function () { if (composing || !self._bound) { return; } var val = number || isRange ? toNumber(el.value) : el.value; self.set(val); // force update on next tick to avoid lock & same value // also only update when user is not typing nextTick(function () { if (self._bound && !self.focused) { self.update(self._watcher.value); } }); }; // apply debounce if (debounce) { this.listener = _debounce(this.listener, debounce); } // Support jQuery events, since jQuery.trigger() doesn't // trigger native events in some cases and some plugins // rely on $.trigger() // // We want to make sure if a listener is attached using // jQuery, it is also removed with jQuery, that's why // we do the check for each directive instance and // store that check result on itself. This also allows // easier test coverage control by unsetting the global // jQuery variable in tests. this.hasjQuery = typeof jQuery === 'function'; if (this.hasjQuery) { var method = jQuery.fn.on ? 'on' : 'bind'; jQuery(el)[method]('change', this.rawListener); if (!lazy) { jQuery(el)[method]('input', this.listener); } } else { this.on('change', this.rawListener); if (!lazy) { this.on('input', this.listener); } } // IE9 doesn't fire input event on backspace/del/cut if (!lazy && isIE9) { this.on('cut', function () { nextTick(self.listener); }); this.on('keyup', function (e) { if (e.keyCode === 46 || e.keyCode === 8) { self.listener(); } }); } // set initial value if present if (el.hasAttribute('value') || el.tagName === 'TEXTAREA' && el.value.trim()) { this.afterBind = this.listener; } }, update: function update(value) { this.el.value = _toString(value); }, unbind: function unbind() { var el = this.el; if (this.hasjQuery) { var method = jQuery.fn.off ? 'off' : 'unbind'; jQuery(el)[method]('change', this.listener); jQuery(el)[method]('input', this.listener); } } }; var radio = { bind: function bind() { var self = this; var el = this.el; this.getValue = function () { // value overwrite via v-bind:value if (el.hasOwnProperty('_value')) { return el._value; } var val = el.value; if (self.params.number) { val = toNumber(val); } return val; }; this.listener = function () { self.set(self.getValue()); }; this.on('change', this.listener); if (el.hasAttribute('checked')) { this.afterBind = this.listener; } }, update: function update(value) { this.el.checked = looseEqual(value, this.getValue()); } }; var select = { bind: function bind() { var self = this; var el = this.el; // method to force update DOM using latest value. this.forceUpdate = function () { if (self._watcher) { self.update(self._watcher.get()); } }; // check if this is a multiple select var multiple = this.multiple = el.hasAttribute('multiple'); // attach listener this.listener = function () { var value = getValue(el, multiple); value = self.params.number ? isArray(value) ? value.map(toNumber) : toNumber(value) : value; self.set(value); }; this.on('change', this.listener); // if has initial value, set afterBind var initValue = getValue(el, multiple, true); if (multiple && initValue.length || !multiple && initValue !== null) { this.afterBind = this.listener; } // All major browsers except Firefox resets // selectedIndex with value -1 to 0 when the element // is appended to a new parent, therefore we have to // force a DOM update whenever that happens... this.vm.$on('hook:attached', this.forceUpdate); }, update: function update(value) { var el = this.el; el.selectedIndex = -1; var multi = this.multiple && isArray(value); var options = el.options; var i = options.length; var op, val; while (i--) { op = options[i]; val = op.hasOwnProperty('_value') ? op._value : op.value; /* eslint-disable eqeqeq */ op.selected = multi ? indexOf$1(value, val) > -1 : looseEqual(value, val); /* eslint-enable eqeqeq */ } }, unbind: function unbind() { /* istanbul ignore next */ this.vm.$off('hook:attached', this.forceUpdate); } }; /** * Get select value * * @param {SelectElement} el * @param {Boolean} multi * @param {Boolean} init * @return {Array|*} */ function getValue(el, multi, init) { var res = multi ? [] : null; var op, val, selected; for (var i = 0, l = el.options.length; i < l; i++) { op = el.options[i]; selected = init ? op.hasAttribute('selected') : op.selected; if (selected) { val = op.hasOwnProperty('_value') ? op._value : op.value; if (multi) { res.push(val); } else { return val; } } } return res; } /** * Native Array.indexOf uses strict equal, but in this * case we need to match string/numbers with custom equal. * * @param {Array} arr * @param {*} val */ function indexOf$1(arr, val) { var i = arr.length; while (i--) { if (looseEqual(arr[i], val)) { return i; } } return -1; } var checkbox = { bind: function bind() { var self = this; var el = this.el; this.getValue = function () { return el.hasOwnProperty('_value') ? el._value : self.params.number ? toNumber(el.value) : el.value; }; function getBooleanValue() { var val = el.checked; if (val && el.hasOwnProperty('_trueValue')) { return el._trueValue; } if (!val && el.hasOwnProperty('_falseValue')) { return el._falseValue; } return val; } this.listener = function () { var model = self._watcher.value; if (isArray(model)) { var val = self.getValue(); if (el.checked) { if (indexOf(model, val) < 0) { model.push(val); } } else { model.$remove(val); } } else { self.set(getBooleanValue()); } }; this.on('change', this.listener); if (el.hasAttribute('checked')) { this.afterBind = this.listener; } }, update: function update(value) { var el = this.el; if (isArray(value)) { el.checked = indexOf(value, this.getValue()) > -1; } else { if (el.hasOwnProperty('_trueValue')) { el.checked = looseEqual(value, el._trueValue); } else { el.checked = !!value; } } } }; var handlers = { text: text$2, radio: radio, select: select, checkbox: checkbox }; var model = { priority: MODEL, twoWay: true, handlers: handlers, params: ['lazy', 'number', 'debounce'], /** * Possible elements: * <select> * <textarea> * <input type="*"> * - text * - checkbox * - radio * - number */ bind: function bind() { // friendly warning... this.checkFilters(); if (this.hasRead && !this.hasWrite) { process.env.NODE_ENV !== 'production' && warn('It seems you are using a read-only filter with ' + 'v-model. You might want to use a two-way filter ' + 'to ensure correct behavior.'); } var el = this.el; var tag = el.tagName; var handler; if (tag === 'INPUT') { handler = handlers[el.type] || handlers.text; } else if (tag === 'SELECT') { handler = handlers.select; } else if (tag === 'TEXTAREA') { handler = handlers.text; } else { process.env.NODE_ENV !== 'production' && warn('v-model does not support element type: ' + tag); return; } el.__v_model = this; handler.bind.call(this); this.update = handler.update; this._unbind = handler.unbind; }, /** * Check read/write filter stats. */ checkFilters: function checkFilters() { var filters = this.filters; if (!filters) return; var i = filters.length; while (i--) { var filter = resolveAsset(this.vm.$options, 'filters', filters[i].name); if (typeof filter === 'function' || filter.read) { this.hasRead = true; } if (filter.write) { this.hasWrite = true; } } }, unbind: function unbind() { this.el.__v_model = null; this._unbind && this._unbind(); } }; // keyCode aliases var keyCodes = { esc: 27, tab: 9, enter: 13, space: 32, 'delete': [8, 46], up: 38, left: 37, right: 39, down: 40 }; function keyFilter(handler, keys) { var codes = keys.map(function (key) { var charCode = key.charCodeAt(0); if (charCode > 47 && charCode < 58) { return parseInt(key, 10); } if (key.length === 1) { charCode = key.toUpperCase().charCodeAt(0); if (charCode > 64 && charCode < 91) { return charCode; } } return keyCodes[key]; }); codes = [].concat.apply([], codes); return function keyHandler(e) { if (codes.indexOf(e.keyCode) > -1) { return handler.call(this, e); } }; } function stopFilter(handler) { return function stopHandler(e) { e.stopPropagation(); return handler.call(this, e); }; } function preventFilter(handler) { return function preventHandler(e) { e.preventDefault(); return handler.call(this, e); }; } function selfFilter(handler) { return function selfHandler(e) { if (e.target === e.currentTarget) { return handler.call(this, e); } }; } var on$1 = { priority: ON, acceptStatement: true, keyCodes: keyCodes, bind: function bind() { // deal with iframes if (this.el.tagName === 'IFRAME' && this.arg !== 'load') { var self = this; this.iframeBind = function () { on(self.el.contentWindow, self.arg, self.handler, self.modifiers.capture); }; this.on('load', this.iframeBind); } }, update: function update(handler) { // stub a noop for v-on with no value, // e.g. @mousedown.prevent if (!this.descriptor.raw) { handler = function () {}; } if (typeof handler !== 'function') { process.env.NODE_ENV !== 'production' && warn('v-on:' + this.arg + '="' + this.expression + '" expects a function value, ' + 'got ' + handler); return; } // apply modifiers if (this.modifiers.stop) { handler = stopFilter(handler); } if (this.modifiers.prevent) { handler = preventFilter(handler); } if (this.modifiers.self) { handler = selfFilter(handler); } // key filter var keys = Object.keys(this.modifiers).filter(function (key) { return key !== 'stop' && key !== 'prevent' && key !== 'self'; }); if (keys.length) { handler = keyFilter(handler, keys); } this.reset(); this.handler = handler; if (this.iframeBind) { this.iframeBind(); } else { on(this.el, this.arg, this.handler, this.modifiers.capture); } }, reset: function reset() { var el = this.iframeBind ? this.el.contentWindow : this.el; if (this.handler) { off(el, this.arg, this.handler); } }, unbind: function unbind() { this.reset(); } }; var prefixes = ['-webkit-', '-moz-', '-ms-']; var camelPrefixes = ['Webkit', 'Moz', 'ms']; var importantRE = /!important;?$/; var propCache = Object.create(null); var testEl = null; var style = { deep: true, update: function update(value) { if (typeof value === 'string') { this.el.style.cssText = value; } else if (isArray(value)) { this.handleObject(value.reduce(extend, {})); } else { this.handleObject(value || {}); } }, handleObject: function handleObject(value) { // cache object styles so that only changed props // are actually updated. var cache = this.cache || (this.cache = {}); var name, val; for (name in cache) { if (!(name in value)) { this.handleSingle(name, null); delete cache[name]; } } for (name in value) { val = value[name]; if (val !== cache[name]) { cache[name] = val; this.handleSingle(name, val); } } }, handleSingle: function handleSingle(prop, value) { prop = normalize(prop); if (!prop) return; // unsupported prop // cast possible numbers/booleans into strings if (value != null) value += ''; if (value) { var isImportant = importantRE.test(value) ? 'important' : ''; if (isImportant) { value = value.replace(importantRE, '').trim(); } this.el.style.setProperty(prop, value, isImportant); } else { this.el.style.removeProperty(prop); } } }; /** * Normalize a CSS property name. * - cache result * - auto prefix * - camelCase -> dash-case * * @param {String} prop * @return {String} */ function normalize(prop) { if (propCache[prop]) { return propCache[prop]; } var res = prefix(prop); propCache[prop] = propCache[res] = res; return res; } /** * Auto detect the appropriate prefix for a CSS property. * https://gist.github.com/paulirish/523692 * * @param {String} prop * @return {String} */ function prefix(prop) { prop = hyphenate(prop); var camel = camelize(prop); var upper = camel.charAt(0).toUpperCase() + camel.slice(1); if (!testEl) { testEl = document.createElement('div'); } var i = prefixes.length; var prefixed; while (i--) { prefixed = camelPrefixes[i] + upper; if (prefixed in testEl.style) { return prefixes[i] + prop; } } if (camel in testEl.style) { return prop; } } // xlink var xlinkNS = 'http://www.w3.org/1999/xlink'; var xlinkRE = /^xlink:/; // check for attributes that prohibit interpolations var disallowedInterpAttrRE = /^v-|^:|^@|^(?:is|transition|transition-mode|debounce|track-by|stagger|enter-stagger|leave-stagger)$/; // these attributes should also set their corresponding properties // because they only affect the initial state of the element var attrWithPropsRE = /^(?:value|checked|selected|muted)$/; // these attributes expect enumrated values of "true" or "false" // but are not boolean attributes var enumeratedAttrRE = /^(?:draggable|contenteditable|spellcheck)$/; // these attributes should set a hidden property for // binding v-model to object values var modelProps = { value: '_value', 'true-value': '_trueValue', 'false-value': '_falseValue' }; var bind$1 = { priority: BIND, bind: function bind() { var attr = this.arg; var tag = this.el.tagName; // should be deep watch on object mode if (!attr) { this.deep = true; } // handle interpolation bindings var descriptor = this.descriptor; var tokens = descriptor.interp; if (tokens) { // handle interpolations with one-time tokens if (descriptor.hasOneTime) { this.expression = tokensToExp(tokens, this._scope || this.vm); } // only allow binding on native attributes if (disallowedInterpAttrRE.test(attr) || attr === 'name' && (tag === 'PARTIAL' || tag === 'SLOT')) { process.env.NODE_ENV !== 'production' && warn(attr + '="' + descriptor.raw + '": ' + 'attribute interpolation is not allowed in Vue.js ' + 'directives and special attributes.'); this.el.removeAttribute(attr); this.invalid = true; } /* istanbul ignore if */ if (process.env.NODE_ENV !== 'production') { var raw = attr + '="' + descriptor.raw + '": '; // warn src if (attr === 'src') { warn(raw + 'interpolation in "src" attribute will cause ' + 'a 404 request. Use v-bind:src instead.'); } // warn style if (attr === 'style') { warn(raw + 'interpolation in "style" attribute will cause ' + 'the attribute to be discarded in Internet Explorer. ' + 'Use v-bind:style instead.'); } } } }, update: function update(value) { if (this.invalid) { return; } var attr = this.arg; if (this.arg) { this.handleSingle(attr, value); } else { this.handleObject(value || {}); } }, // share object handler with v-bind:class handleObject: style.handleObject, handleSingle: function handleSingle(attr, value) { var el = this.el; var interp = this.descriptor.interp; if (this.modifiers.camel) { attr = camelize(attr); } if (!interp && attrWithPropsRE.test(attr) && attr in el) { el[attr] = attr === 'value' ? value == null // IE9 will set input.value to "null" for null... ? '' : value : value; } // set model props var modelProp = modelProps[attr]; if (!interp && modelProp) { el[modelProp] = value; // update v-model if present var model = el.__v_model; if (model) { model.listener(); } } // do not set value attribute for textarea if (attr === 'value' && el.tagName === 'TEXTAREA') { el.removeAttribute(attr); return; } // update attribute if (enumeratedAttrRE.test(attr)) { el.setAttribute(attr, value ? 'true' : 'false'); } else if (value != null && value !== false) { if (attr === 'class') { // handle edge case #1960: // class interpolation should not overwrite Vue transition class if (el.__v_trans) { value += ' ' + el.__v_trans.id + '-transition'; } setClass(el, value); } else if (xlinkRE.test(attr)) { el.setAttributeNS(xlinkNS, attr, value === true ? '' : value); } else { el.setAttribute(attr, value === true ? '' : value); } } else { el.removeAttribute(attr); } } }; var el = { priority: EL, bind: function bind() { /* istanbul ignore if */ if (!this.arg) { return; } var id = this.id = camelize(this.arg); var refs = (this._scope || this.vm).$els; if (hasOwn(refs, id)) { refs[id] = this.el; } else { defineReactive(refs, id, this.el); } }, unbind: function unbind() { var refs = (this._scope || this.vm).$els; if (refs[this.id] === this.el) { refs[this.id] = null; } } }; var ref = { bind: function bind() { process.env.NODE_ENV !== 'production' && warn('v-ref:' + this.arg + ' must be used on a child ' + 'component. Found on <' + this.el.tagName.toLowerCase() + '>.'); } }; var cloak = { bind: function bind() { var el = this.el; this.vm.$once('pre-hook:compiled', function () { el.removeAttribute('v-cloak'); }); } }; // must export plain object var directives = { text: text$1, html: html, 'for': vFor, 'if': vIf, show: show, model: model, on: on$1, bind: bind$1, el: el, ref: ref, cloak: cloak }; var vClass = { deep: true, update: function update(value) { if (value && typeof value === 'string') { this.handleObject(stringToObject(value)); } else if (isPlainObject(value)) { this.handleObject(value); } else if (isArray(value)) { this.handleArray(value); } else { this.cleanup(); } }, handleObject: function handleObject(value) { this.cleanup(value); this.prevKeys = Object.keys(value); setObjectClasses(this.el, value); }, handleArray: function handleArray(value) { this.cleanup(value); for (var i = 0, l = value.length; i < l; i++) { var val = value[i]; if (val && isPlainObject(val)) { setObjectClasses(this.el, val); } else if (val && typeof val === 'string') { addClass(this.el, val); } } this.prevKeys = value.slice(); }, cleanup: function cleanup(value) { if (this.prevKeys) { var i = this.prevKeys.length; while (i--) { var key = this.prevKeys[i]; if (!key) continue; if (isPlainObject(key)) { var keys = Object.keys(key); for (var k = 0; k < keys.length; k++) { removeClass(this.el, keys[k]); } } else { removeClass(this.el, key); } } } } }; function setObjectClasses(el, obj) { var keys = Object.keys(obj); for (var i = 0, l = keys.length; i < l; i++) { var key = keys[i]; if (obj[key]) { addClass(el, key); } } } function stringToObject(value) { var res = {}; var keys = value.trim().split(/\s+/); var i = keys.length; while (i--) { res[keys[i]] = true; } return res; } var component = { priority: COMPONENT, params: ['keep-alive', 'transition-mode', 'inline-template'], /** * Setup. Two possible usages: * * - static: * <comp> or <div v-component="comp"> * * - dynamic: * <component :is="view"> */ bind: function bind() { if (!this.el.__vue__) { // keep-alive cache this.keepAlive = this.params.keepAlive; if (this.keepAlive) { this.cache = {}; } // check inline-template if (this.params.inlineTemplate) { // extract inline template as a DocumentFragment this.inlineTemplate = extractContent(this.el, true); } // component resolution related state this.pendingComponentCb = this.Component = null; // transition related state this.pendingRemovals = 0; this.pendingRemovalCb = null; // create a ref anchor this.anchor = createAnchor('v-component'); replace(this.el, this.anchor); // remove is attribute. // this is removed during compilation, but because compilation is // cached, when the component is used elsewhere this attribute // will remain at link time. this.el.removeAttribute('is'); // remove ref, same as above if (this.descriptor.ref) { this.el.removeAttribute('v-ref:' + hyphenate(this.descriptor.ref)); } // if static, build right now. if (this.literal) { this.setComponent(this.expression); } } else { process.env.NODE_ENV !== 'production' && warn('cannot mount component "' + this.expression + '" ' + 'on already mounted element: ' + this.el); } }, /** * Public update, called by the watcher in the dynamic * literal scenario, e.g. <component :is="view"> */ update: function update(value) { if (!this.literal) { this.setComponent(value); } }, /** * Switch dynamic components. May resolve the component * asynchronously, and perform transition based on * specified transition mode. Accepts a few additional * arguments specifically for vue-router. * * The callback is called when the full transition is * finished. * * @param {String} value * @param {Function} [cb] */ setComponent: function setComponent(value, cb) { this.invalidatePending(); if (!value) { // just remove current this.unbuild(true); this.remove(this.childVM, cb); this.childVM = null; } else { var self = this; this.resolveComponent(value, function () { self.mountComponent(cb); }); } }, /** * Resolve the component constructor to use when creating * the child vm. * * @param {String|Function} value * @param {Function} cb */ resolveComponent: function resolveComponent(value, cb) { var self = this; this.pendingComponentCb = cancellable(function (Component) { self.ComponentName = Component.options.name || (typeof value === 'string' ? value : null); self.Component = Component; cb(); }); this.vm._resolveComponent(value, this.pendingComponentCb); }, /** * Create a new instance using the current constructor and * replace the existing instance. This method doesn't care * whether the new component and the old one are actually * the same. * * @param {Function} [cb] */ mountComponent: function mountComponent(cb) { // actual mount this.unbuild(true); var self = this; var activateHooks = this.Component.options.activate; var cached = this.getCached(); var newComponent = this.build(); if (activateHooks && !cached) { this.waitingFor = newComponent; callActivateHooks(activateHooks, newComponent, function () { if (self.waitingFor !== newComponent) { return; } self.waitingFor = null; self.transition(newComponent, cb); }); } else { // update ref for kept-alive component if (cached) { newComponent._updateRef(); } this.transition(newComponent, cb); } }, /** * When the component changes or unbinds before an async * constructor is resolved, we need to invalidate its * pending callback. */ invalidatePending: function invalidatePending() { if (this.pendingComponentCb) { this.pendingComponentCb.cancel(); this.pendingComponentCb = null; } }, /** * Instantiate/insert a new child vm. * If keep alive and has cached instance, insert that * instance; otherwise build a new one and cache it. * * @param {Object} [extraOptions] * @return {Vue} - the created instance */ build: function build(extraOptions) { var cached = this.getCached(); if (cached) { return cached; } if (this.Component) { // default options var options = { name: this.ComponentName, el: cloneNode(this.el), template: this.inlineTemplate, // make sure to add the child with correct parent // if this is a transcluded component, its parent // should be the transclusion host. parent: this._host || this.vm, // if no inline-template, then the compiled // linker can be cached for better performance. _linkerCachable: !this.inlineTemplate, _ref: this.descriptor.ref, _asComponent: true, _isRouterView: this._isRouterView, // if this is a transcluded component, context // will be the common parent vm of this instance // and its host. _context: this.vm, // if this is inside an inline v-for, the scope // will be the intermediate scope created for this // repeat fragment. this is used for linking props // and container directives. _scope: this._scope, // pass in the owner fragment of this component. // this is necessary so that the fragment can keep // track of its contained components in order to // call attach/detach hooks for them. _frag: this._frag }; // extra options // in 1.0.0 this is used by vue-router only /* istanbul ignore if */ if (extraOptions) { extend(options, extraOptions); } var child = new this.Component(options); if (this.keepAlive) { this.cache[this.Component.cid] = child; } /* istanbul ignore if */ if (process.env.NODE_ENV !== 'production' && this.el.hasAttribute('transition') && child._isFragment) { warn('Transitions will not work on a fragment instance. ' + 'Template: ' + child.$options.template); } return child; } }, /** * Try to get a cached instance of the current component. * * @return {Vue|undefined} */ getCached: function getCached() { return this.keepAlive && this.cache[this.Component.cid]; }, /** * Teardown the current child, but defers cleanup so * that we can separate the destroy and removal steps. * * @param {Boolean} defer */ unbuild: function unbuild(defer) { if (this.waitingFor) { this.waitingFor.$destroy(); this.waitingFor = null; } var child = this.childVM; if (!child || this.keepAlive) { if (child) { // remove ref child._inactive = true; child._updateRef(true); } return; } // the sole purpose of `deferCleanup` is so that we can // "deactivate" the vm right now and perform DOM removal // later. child.$destroy(false, defer); }, /** * Remove current destroyed child and manually do * the cleanup after removal. * * @param {Function} cb */ remove: function remove(child, cb) { var keepAlive = this.keepAlive; if (child) { // we may have a component switch when a previous // component is still being transitioned out. // we want to trigger only one lastest insertion cb // when the existing transition finishes. (#1119) this.pendingRemovals++; this.pendingRemovalCb = cb; var self = this; child.$remove(function () { self.pendingRemovals--; if (!keepAlive) child._cleanup(); if (!self.pendingRemovals && self.pendingRemovalCb) { self.pendingRemovalCb(); self.pendingRemovalCb = null; } }); } else if (cb) { cb(); } }, /** * Actually swap the components, depending on the * transition mode. Defaults to simultaneous. * * @param {Vue} target * @param {Function} [cb] */ transition: function transition(target, cb) { var self = this; var current = this.childVM; // for devtool inspection if (current) current._inactive = true; target._inactive = false; this.childVM = target; switch (self.params.transitionMode) { case 'in-out': target.$before(self.anchor, function () { self.remove(current, cb); }); break; case 'out-in': self.remove(current, function () { target.$before(self.anchor, cb); }); break; default: self.remove(current); target.$before(self.anchor, cb); } }, /** * Unbind. */ unbind: function unbind() { this.invalidatePending(); // Do not defer cleanup when unbinding this.unbuild(); // destroy all keep-alive cached instances if (this.cache) { for (var key in this.cache) { this.cache[key].$destroy(); } this.cache = null; } } }; /** * Call activate hooks in order (asynchronous) * * @param {Array} hooks * @param {Vue} vm * @param {Function} cb */ function callActivateHooks(hooks, vm, cb) { var total = hooks.length; var called = 0; hooks[0].call(vm, next); function next() { if (++called >= total) { cb(); } else { hooks[called].call(vm, next); } } } var propBindingModes = config._propBindingModes; var empty = {}; // regexes var identRE$1 = /^[$_a-zA-Z]+[\w$]*$/; var settablePathRE = /^[A-Za-z_$][\w$]*(\.[A-Za-z_$][\w$]*|\[[^\[\]]+\])*$/; /** * Compile props on a root element and return * a props link function. * * @param {Element|DocumentFragment} el * @param {Array} propOptions * @return {Function} propsLinkFn */ function compileProps(el, propOptions) { var props = []; var names = Object.keys(propOptions); var i = names.length; var options, name, attr, value, path, parsed, prop; while (i--) { name = names[i]; options = propOptions[name] || empty; if (process.env.NODE_ENV !== 'production' && name === '$data') { warn('Do not use $data as prop.'); continue; } // props could contain dashes, which will be // interpreted as minus calculations by the parser // so we need to camelize the path here path = camelize(name); if (!identRE$1.test(path)) { process.env.NODE_ENV !== 'production' && warn('Invalid prop key: "' + name + '". Prop keys ' + 'must be valid identifiers.'); continue; } prop = { name: name, path: path, options: options, mode: propBindingModes.ONE_WAY, raw: null }; attr = hyphenate(name); // first check dynamic version if ((value = getBindAttr(el, attr)) === null) { if ((value = getBindAttr(el, attr + '.sync')) !== null) { prop.mode = propBindingModes.TWO_WAY; } else if ((value = getBindAttr(el, attr + '.once')) !== null) { prop.mode = propBindingModes.ONE_TIME; } } if (value !== null) { // has dynamic binding! prop.raw = value; parsed = parseDirective(value); value = parsed.expression; prop.filters = parsed.filters; // check binding type if (isLiteral(value) && !parsed.filters) { // for expressions containing literal numbers and // booleans, there's no need to setup a prop binding, // so we can optimize them as a one-time set. prop.optimizedLiteral = true; } else { prop.dynamic = true; // check non-settable path for two-way bindings if (process.env.NODE_ENV !== 'production' && prop.mode === propBindingModes.TWO_WAY && !settablePathRE.test(value)) { prop.mode = propBindingModes.ONE_WAY; warn('Cannot bind two-way prop with non-settable ' + 'parent path: ' + value); } } prop.parentPath = value; // warn required two-way if (process.env.NODE_ENV !== 'production' && options.twoWay && prop.mode !== propBindingModes.TWO_WAY) { warn('Prop "' + name + '" expects a two-way binding type.'); } } else if ((value = getAttr(el, attr)) !== null) { // has literal binding! prop.raw = value; } else if (process.env.NODE_ENV !== 'production') { // check possible camelCase prop usage var lowerCaseName = path.toLowerCase(); value = /[A-Z\-]/.test(name) && (el.getAttribute(lowerCaseName) || el.getAttribute(':' + lowerCaseName) || el.getAttribute('v-bind:' + lowerCaseName) || el.getAttribute(':' + lowerCaseName + '.once') || el.getAttribute('v-bind:' + lowerCaseName + '.once') || el.getAttribute(':' + lowerCaseName + '.sync') || el.getAttribute('v-bind:' + lowerCaseName + '.sync')); if (value) { warn('Possible usage error for prop `' + lowerCaseName + '` - ' + 'did you mean `' + attr + '`? HTML is case-insensitive, remember to use ' + 'kebab-case for props in templates.'); } else if (options.required) { // warn missing required warn('Missing required prop: ' + name); } } // push prop props.push(prop); } return makePropsLinkFn(props); } /** * Build a function that applies props to a vm. * * @param {Array} props * @return {Function} propsLinkFn */ function makePropsLinkFn(props) { return function propsLinkFn(vm, scope) { // store resolved props info vm._props = {}; var i = props.length; var prop, path, options, value, raw; while (i--) { prop = props[i]; raw = prop.raw; path = prop.path; options = prop.options; vm._props[path] = prop; if (raw === null) { // initialize absent prop initProp(vm, prop, undefined); } else if (prop.dynamic) { // dynamic prop if (prop.mode === propBindingModes.ONE_TIME) { // one time binding value = (scope || vm._context || vm).$get(prop.parentPath); initProp(vm, prop, value); } else { if (vm._context) { // dynamic binding vm._bindDir({ name: 'prop', def: propDef, prop: prop }, null, null, scope); // el, host, scope } else { // root instance initProp(vm, prop, vm.$get(prop.parentPath)); } } } else if (prop.optimizedLiteral) { // optimized literal, cast it and just set once var stripped = stripQuotes(raw); value = stripped === raw ? toBoolean(toNumber(raw)) : stripped; initProp(vm, prop, value); } else { // string literal, but we need to cater for // Boolean props with no value, or with same // literal value (e.g. disabled="disabled") // see https://github.com/vuejs/vue-loader/issues/182 value = options.type === Boolean && (raw === '' || raw === hyphenate(prop.name)) ? true : raw; initProp(vm, prop, value); } } }; } /** * Set a prop's initial value on a vm and its data object. * * @param {Vue} vm * @param {Object} prop * @param {*} value */ function initProp(vm, prop, value) { var key = prop.path; value = coerceProp(prop, value); if (value === undefined) { value = getPropDefaultValue(vm, prop.options); } if (assertProp(prop, value)) { var doNotObserve = // if the passed down prop was already converted, then // subsequent sets should also be converted, because the user // may mutate the prop binding in the child component (#2549) !(value && value.__ob__) && ( // otherwise we can skip observation for props that are either // literal or points to a simple path (non-derived values) !prop.dynamic || isSimplePath(prop.raw)); defineReactive(vm, key, value, doNotObserve); } } /** * Get the default value of a prop. * * @param {Vue} vm * @param {Object} options * @return {*} */ function getPropDefaultValue(vm, options) { // no default, return undefined if (!hasOwn(options, 'default')) { // absent boolean value defaults to false return options.type === Boolean ? false : undefined; } var def = options['default']; // warn against non-factory defaults for Object & Array if (isObject(def)) { process.env.NODE_ENV !== 'production' && warn('Object/Array as default prop values will be shared ' + 'across multiple instances. Use a factory function ' + 'to return the default value instead.'); } // call factory function for non-Function types return typeof def === 'function' && options.type !== Function ? def.call(vm) : def; } /** * Assert whether a prop is valid. * * @param {Object} prop * @param {*} value */ function assertProp(prop, value) { if (!prop.options.required && ( // non-required prop.raw === null || // abscent value == null) // null or undefined ) { return true; } var options = prop.options; var type = options.type; var valid = true; var expectedType; if (type) { if (type === String) { expectedType = 'string'; valid = typeof value === expectedType; } else if (type === Number) { expectedType = 'number'; valid = typeof value === 'number'; } else if (type === Boolean) { expectedType = 'boolean'; valid = typeof value === 'boolean'; } else if (type === Function) { expectedType = 'function'; valid = typeof value === 'function'; } else if (type === Object) { expectedType = 'object'; valid = isPlainObject(value); } else if (type === Array) { expectedType = 'array'; valid = isArray(value); } else { valid = value instanceof type; } } if (!valid) { process.env.NODE_ENV !== 'production' && warn('Invalid prop: type check failed for ' + prop.path + '="' + prop.raw + '".' + ' Expected ' + formatType(expectedType) + ', got ' + formatValue(value) + '.'); return false; } var validator = options.validator; if (validator) { if (!validator(value)) { process.env.NODE_ENV !== 'production' && warn('Invalid prop: custom validator check failed for ' + prop.path + '="' + prop.raw + '"'); return false; } } return true; } /** * Force parsing value with coerce option. * * @param {*} value * @param {Object} options * @return {*} */ function coerceProp(prop, value) { var coerce = prop.options.coerce; if (!coerce) { return value; } // coerce is a function return coerce(value); } function formatType(val) { return val ? val.charAt(0).toUpperCase() + val.slice(1) : 'custom type'; } function formatValue(val) { return Object.prototype.toString.call(val).slice(8, -1); } var bindingModes = config._propBindingModes; var propDef = { bind: function bind() { var child = this.vm; var parent = child._context; // passed in from compiler directly var prop = this.descriptor.prop; var childKey = prop.path; var parentKey = prop.parentPath; var twoWay = prop.mode === bindingModes.TWO_WAY; var parentWatcher = this.parentWatcher = new Watcher(parent, parentKey, function (val) { val = coerceProp(prop, val); if (assertProp(prop, val)) { child[childKey] = val; } }, { twoWay: twoWay, filters: prop.filters, // important: props need to be observed on the // v-for scope if present scope: this._scope }); // set the child initial value. initProp(child, prop, parentWatcher.value); // setup two-way binding if (twoWay) { // important: defer the child watcher creation until // the created hook (after data observation) var self = this; child.$once('pre-hook:created', function () { self.childWatcher = new Watcher(child, childKey, function (val) { parentWatcher.set(val); }, { // ensure sync upward before parent sync down. // this is necessary in cases e.g. the child // mutates a prop array, then replaces it. (#1683) sync: true }); }); } }, unbind: function unbind() { this.parentWatcher.teardown(); if (this.childWatcher) { this.childWatcher.teardown(); } } }; var queue$1 = []; var queued = false; /** * Push a job into the queue. * * @param {Function} job */ function pushJob(job) { queue$1.push(job); if (!queued) { queued = true; nextTick(flush); } } /** * Flush the queue, and do one forced reflow before * triggering transitions. */ function flush() { // Force layout var f = document.documentElement.offsetHeight; for (var i = 0; i < queue$1.length; i++) { queue$1[i](); } queue$1 = []; queued = false; // dummy return, so js linters don't complain about // unused variable f return f; } var TYPE_TRANSITION = 'transition'; var TYPE_ANIMATION = 'animation'; var transDurationProp = transitionProp + 'Duration'; var animDurationProp = animationProp + 'Duration'; /** * If a just-entered element is applied the * leave class while its enter transition hasn't started yet, * and the transitioned property has the same value for both * enter/leave, then the leave transition will be skipped and * the transitionend event never fires. This function ensures * its callback to be called after a transition has started * by waiting for double raf. * * It falls back to setTimeout on devices that support CSS * transitions but not raf (e.g. Android 4.2 browser) - since * these environments are usually slow, we are giving it a * relatively large timeout. */ var raf = inBrowser && window.requestAnimationFrame; var waitForTransitionStart = raf /* istanbul ignore next */ ? function (fn) { raf(function () { raf(fn); }); } : function (fn) { setTimeout(fn, 50); }; /** * A Transition object that encapsulates the state and logic * of the transition. * * @param {Element} el * @param {String} id * @param {Object} hooks * @param {Vue} vm */ function Transition(el, id, hooks, vm) { this.id = id; this.el = el; this.enterClass = hooks && hooks.enterClass || id + '-enter'; this.leaveClass = hooks && hooks.leaveClass || id + '-leave'; this.hooks = hooks; this.vm = vm; // async state this.pendingCssEvent = this.pendingCssCb = this.cancel = this.pendingJsCb = this.op = this.cb = null; this.justEntered = false; this.entered = this.left = false; this.typeCache = {}; // check css transition type this.type = hooks && hooks.type; /* istanbul ignore if */ if (process.env.NODE_ENV !== 'production') { if (this.type && this.type !== TYPE_TRANSITION && this.type !== TYPE_ANIMATION) { warn('invalid CSS transition type for transition="' + this.id + '": ' + this.type); } } // bind var self = this;['enterNextTick', 'enterDone', 'leaveNextTick', 'leaveDone'].forEach(function (m) { self[m] = bind(self[m], self); }); } var p$1 = Transition.prototype; /** * Start an entering transition. * * 1. enter transition triggered * 2. call beforeEnter hook * 3. add enter class * 4. insert/show element * 5. call enter hook (with possible explicit js callback) * 6. reflow * 7. based on transition type: * - transition: * remove class now, wait for transitionend, * then done if there's no explicit js callback. * - animation: * wait for animationend, remove class, * then done if there's no explicit js callback. * - no css transition: * done now if there's no explicit js callback. * 8. wait for either done or js callback, then call * afterEnter hook. * * @param {Function} op - insert/show the element * @param {Function} [cb] */ p$1.enter = function (op, cb) { this.cancelPending(); this.callHook('beforeEnter'); this.cb = cb; addClass(this.el, this.enterClass); op(); this.entered = false; this.callHookWithCb('enter'); if (this.entered) { return; // user called done synchronously. } this.cancel = this.hooks && this.hooks.enterCancelled; pushJob(this.enterNextTick); }; /** * The "nextTick" phase of an entering transition, which is * to be pushed into a queue and executed after a reflow so * that removing the class can trigger a CSS transition. */ p$1.enterNextTick = function () { var _this = this; // prevent transition skipping this.justEntered = true; waitForTransitionStart(function () { _this.justEntered = false; }); var enterDone = this.enterDone; var type = this.getCssTransitionType(this.enterClass); if (!this.pendingJsCb) { if (type === TYPE_TRANSITION) { // trigger transition by removing enter class now removeClass(this.el, this.enterClass); this.setupCssCb(transitionEndEvent, enterDone); } else if (type === TYPE_ANIMATION) { this.setupCssCb(animationEndEvent, enterDone); } else { enterDone(); } } else if (type === TYPE_TRANSITION) { removeClass(this.el, this.enterClass); } }; /** * The "cleanup" phase of an entering transition. */ p$1.enterDone = function () { this.entered = true; this.cancel = this.pendingJsCb = null; removeClass(this.el, this.enterClass); this.callHook('afterEnter'); if (this.cb) this.cb(); }; /** * Start a leaving transition. * * 1. leave transition triggered. * 2. call beforeLeave hook * 3. add leave class (trigger css transition) * 4. call leave hook (with possible explicit js callback) * 5. reflow if no explicit js callback is provided * 6. based on transition type: * - transition or animation: * wait for end event, remove class, then done if * there's no explicit js callback. * - no css transition: * done if there's no explicit js callback. * 7. wait for either done or js callback, then call * afterLeave hook. * * @param {Function} op - remove/hide the element * @param {Function} [cb] */ p$1.leave = function (op, cb) { this.cancelPending(); this.callHook('beforeLeave'); this.op = op; this.cb = cb; addClass(this.el, this.leaveClass); this.left = false; this.callHookWithCb('leave'); if (this.left) { return; // user called done synchronously. } this.cancel = this.hooks && this.hooks.leaveCancelled; // only need to handle leaveDone if // 1. the transition is already done (synchronously called // by the user, which causes this.op set to null) // 2. there's no explicit js callback if (this.op && !this.pendingJsCb) { // if a CSS transition leaves immediately after enter, // the transitionend event never fires. therefore we // detect such cases and end the leave immediately. if (this.justEntered) { this.leaveDone(); } else { pushJob(this.leaveNextTick); } } }; /** * The "nextTick" phase of a leaving transition. */ p$1.leaveNextTick = function () { var type = this.getCssTransitionType(this.leaveClass); if (type) { var event = type === TYPE_TRANSITION ? transitionEndEvent : animationEndEvent; this.setupCssCb(event, this.leaveDone); } else { this.leaveDone(); } }; /** * The "cleanup" phase of a leaving transition. */ p$1.leaveDone = function () { this.left = true; this.cancel = this.pendingJsCb = null; this.op(); removeClass(this.el, this.leaveClass); this.callHook('afterLeave'); if (this.cb) this.cb(); this.op = null; }; /** * Cancel any pending callbacks from a previously running * but not finished transition. */ p$1.cancelPending = function () { this.op = this.cb = null; var hasPending = false; if (this.pendingCssCb) { hasPending = true; off(this.el, this.pendingCssEvent, this.pendingCssCb); this.pendingCssEvent = this.pendingCssCb = null; } if (this.pendingJsCb) { hasPending = true; this.pendingJsCb.cancel(); this.pendingJsCb = null; } if (hasPending) { removeClass(this.el, this.enterClass); removeClass(this.el, this.leaveClass); } if (this.cancel) { this.cancel.call(this.vm, this.el); this.cancel = null; } }; /** * Call a user-provided synchronous hook function. * * @param {String} type */ p$1.callHook = function (type) { if (this.hooks && this.hooks[type]) { this.hooks[type].call(this.vm, this.el); } }; /** * Call a user-provided, potentially-async hook function. * We check for the length of arguments to see if the hook * expects a `done` callback. If true, the transition's end * will be determined by when the user calls that callback; * otherwise, the end is determined by the CSS transition or * animation. * * @param {String} type */ p$1.callHookWithCb = function (type) { var hook = this.hooks && this.hooks[type]; if (hook) { if (hook.length > 1) { this.pendingJsCb = cancellable(this[type + 'Done']); } hook.call(this.vm, this.el, this.pendingJsCb); } }; /** * Get an element's transition type based on the * calculated styles. * * @param {String} className * @return {Number} */ p$1.getCssTransitionType = function (className) { /* istanbul ignore if */ if (!transitionEndEvent || // skip CSS transitions if page is not visible - // this solves the issue of transitionend events not // firing until the page is visible again. // pageVisibility API is supported in IE10+, same as // CSS transitions. document.hidden || // explicit js-only transition this.hooks && this.hooks.css === false || // element is hidden isHidden(this.el)) { return; } var type = this.type || this.typeCache[className]; if (type) return type; var inlineStyles = this.el.style; var computedStyles = window.getComputedStyle(this.el); var transDuration = inlineStyles[transDurationProp] || computedStyles[transDurationProp]; if (transDuration && transDuration !== '0s') { type = TYPE_TRANSITION; } else { var animDuration = inlineStyles[animDurationProp] || computedStyles[animDurationProp]; if (animDuration && animDuration !== '0s') { type = TYPE_ANIMATION; } } if (type) { this.typeCache[className] = type; } return type; }; /** * Setup a CSS transitionend/animationend callback. * * @param {String} event * @param {Function} cb */ p$1.setupCssCb = function (event, cb) { this.pendingCssEvent = event; var self = this; var el = this.el; var onEnd = this.pendingCssCb = function (e) { if (e.target === el) { off(el, event, onEnd); self.pendingCssEvent = self.pendingCssCb = null; if (!self.pendingJsCb && cb) { cb(); } } }; on(el, event, onEnd); }; /** * Check if an element is hidden - in that case we can just * skip the transition alltogether. * * @param {Element} el * @return {Boolean} */ function isHidden(el) { if (/svg$/.test(el.namespaceURI)) { // SVG elements do not have offset(Width|Height) // so we need to check the client rect var rect = el.getBoundingClientRect(); return !(rect.width || rect.height); } else { return !(el.offsetWidth || el.offsetHeight || el.getClientRects().length); } } var transition$1 = { priority: TRANSITION, update: function update(id, oldId) { var el = this.el; // resolve on owner vm var hooks = resolveAsset(this.vm.$options, 'transitions', id); id = id || 'v'; el.__v_trans = new Transition(el, id, hooks, this.vm); if (oldId) { removeClass(el, oldId + '-transition'); } addClass(el, id + '-transition'); } }; var internalDirectives = { style: style, 'class': vClass, component: component, prop: propDef, transition: transition$1 }; // special binding prefixes var bindRE = /^v-bind:|^:/; var onRE = /^v-on:|^@/; var dirAttrRE = /^v-([^:]+)(?:$|:(.*)$)/; var modifierRE = /\.[^\.]+/g; var transitionRE = /^(v-bind:|:)?transition$/; // default directive priority var DEFAULT_PRIORITY = 1000; var DEFAULT_TERMINAL_PRIORITY = 2000; /** * Compile a template and return a reusable composite link * function, which recursively contains more link functions * inside. This top level compile function would normally * be called on instance root nodes, but can also be used * for partial compilation if the partial argument is true. * * The returned composite link function, when called, will * return an unlink function that tearsdown all directives * created during the linking phase. * * @param {Element|DocumentFragment} el * @param {Object} options * @param {Boolean} partial * @return {Function} */ function compile(el, options, partial) { // link function for the node itself. var nodeLinkFn = partial || !options._asComponent ? compileNode(el, options) : null; // link function for the childNodes var childLinkFn = !(nodeLinkFn && nodeLinkFn.terminal) && el.tagName !== 'SCRIPT' && el.hasChildNodes() ? compileNodeList(el.childNodes, options) : null; /** * A composite linker function to be called on a already * compiled piece of DOM, which instantiates all directive * instances. * * @param {Vue} vm * @param {Element|DocumentFragment} el * @param {Vue} [host] - host vm of transcluded content * @param {Object} [scope] - v-for scope * @param {Fragment} [frag] - link context fragment * @return {Function|undefined} */ return function compositeLinkFn(vm, el, host, scope, frag) { // cache childNodes before linking parent, fix #657 var childNodes = toArray(el.childNodes); // link var dirs = linkAndCapture(function compositeLinkCapturer() { if (nodeLinkFn) nodeLinkFn(vm, el, host, scope, frag); if (childLinkFn) childLinkFn(vm, childNodes, host, scope, frag); }, vm); return makeUnlinkFn(vm, dirs); }; } /** * Apply a linker to a vm/element pair and capture the * directives created during the process. * * @param {Function} linker * @param {Vue} vm */ function linkAndCapture(linker, vm) { /* istanbul ignore if */ if (process.env.NODE_ENV === 'production') { // reset directives before every capture in production // mode, so that when unlinking we don't need to splice // them out (which turns out to be a perf hit). // they are kept in development mode because they are // useful for Vue's own tests. vm._directives = []; } var originalDirCount = vm._directives.length; linker(); var dirs = vm._directives.slice(originalDirCount); dirs.sort(directiveComparator); for (var i = 0, l = dirs.length; i < l; i++) { dirs[i]._bind(); } return dirs; } /** * Directive priority sort comparator * * @param {Object} a * @param {Object} b */ function directiveComparator(a, b) { a = a.descriptor.def.priority || DEFAULT_PRIORITY; b = b.descriptor.def.priority || DEFAULT_PRIORITY; return a > b ? -1 : a === b ? 0 : 1; } /** * Linker functions return an unlink function that * tearsdown all directives instances generated during * the process. * * We create unlink functions with only the necessary * information to avoid retaining additional closures. * * @param {Vue} vm * @param {Array} dirs * @param {Vue} [context] * @param {Array} [contextDirs] * @return {Function} */ function makeUnlinkFn(vm, dirs, context, contextDirs) { function unlink(destroying) { teardownDirs(vm, dirs, destroying); if (context && contextDirs) { teardownDirs(context, contextDirs); } } // expose linked directives unlink.dirs = dirs; return unlink; } /** * Teardown partial linked directives. * * @param {Vue} vm * @param {Array} dirs * @param {Boolean} destroying */ function teardownDirs(vm, dirs, destroying) { var i = dirs.length; while (i--) { dirs[i]._teardown(); if (process.env.NODE_ENV !== 'production' && !destroying) { vm._directives.$remove(dirs[i]); } } } /** * Compile link props on an instance. * * @param {Vue} vm * @param {Element} el * @param {Object} props * @param {Object} [scope] * @return {Function} */ function compileAndLinkProps(vm, el, props, scope) { var propsLinkFn = compileProps(el, props); var propDirs = linkAndCapture(function () { propsLinkFn(vm, scope); }, vm); return makeUnlinkFn(vm, propDirs); } /** * Compile the root element of an instance. * * 1. attrs on context container (context scope) * 2. attrs on the component template root node, if * replace:true (child scope) * * If this is a fragment instance, we only need to compile 1. * * @param {Element} el * @param {Object} options * @param {Object} contextOptions * @return {Function} */ function compileRoot(el, options, contextOptions) { var containerAttrs = options._containerAttrs; var replacerAttrs = options._replacerAttrs; var contextLinkFn, replacerLinkFn; // only need to compile other attributes for // non-fragment instances if (el.nodeType !== 11) { // for components, container and replacer need to be // compiled separately and linked in different scopes. if (options._asComponent) { // 2. container attributes if (containerAttrs && contextOptions) { contextLinkFn = compileDirectives(containerAttrs, contextOptions); } if (replacerAttrs) { // 3. replacer attributes replacerLinkFn = compileDirectives(replacerAttrs, options); } } else { // non-component, just compile as a normal element. replacerLinkFn = compileDirectives(el.attributes, options); } } else if (process.env.NODE_ENV !== 'production' && containerAttrs) { // warn container directives for fragment instances var names = containerAttrs.filter(function (attr) { // allow vue-loader/vueify scoped css attributes return attr.name.indexOf('_v-') < 0 && // allow event listeners !onRE.test(attr.name) && // allow slots attr.name !== 'slot'; }).map(function (attr) { return '"' + attr.name + '"'; }); if (names.length) { var plural = names.length > 1; warn('Attribute' + (plural ? 's ' : ' ') + names.join(', ') + (plural ? ' are' : ' is') + ' ignored on component ' + '<' + options.el.tagName.toLowerCase() + '> because ' + 'the component is a fragment instance: ' + 'http://vuejs.org/guide/components.html#Fragment_Instance'); } } options._containerAttrs = options._replacerAttrs = null; return function rootLinkFn(vm, el, scope) { // link context scope dirs var context = vm._context; var contextDirs; if (context && contextLinkFn) { contextDirs = linkAndCapture(function () { contextLinkFn(context, el, null, scope); }, context); } // link self var selfDirs = linkAndCapture(function () { if (replacerLinkFn) replacerLinkFn(vm, el); }, vm); // return the unlink function that tearsdown context // container directives. return makeUnlinkFn(vm, selfDirs, context, contextDirs); }; } /** * Compile a node and return a nodeLinkFn based on the * node type. * * @param {Node} node * @param {Object} options * @return {Function|null} */ function compileNode(node, options) { var type = node.nodeType; if (type === 1 && node.tagName !== 'SCRIPT') { return compileElement(node, options); } else if (type === 3 && node.data.trim()) { return compileTextNode(node, options); } else { return null; } } /** * Compile an element and return a nodeLinkFn. * * @param {Element} el * @param {Object} options * @return {Function|null} */ function compileElement(el, options) { // preprocess textareas. // textarea treats its text content as the initial value. // just bind it as an attr directive for value. if (el.tagName === 'TEXTAREA') { var tokens = parseText(el.value); if (tokens) { el.setAttribute(':value', tokensToExp(tokens)); el.value = ''; } } var linkFn; var hasAttrs = el.hasAttributes(); var attrs = hasAttrs && toArray(el.attributes); // check terminal directives (for & if) if (hasAttrs) { linkFn = checkTerminalDirectives(el, attrs, options); } // check element directives if (!linkFn) { linkFn = checkElementDirectives(el, options); } // check component if (!linkFn) { linkFn = checkComponent(el, options); } // normal directives if (!linkFn && hasAttrs) { linkFn = compileDirectives(attrs, options); } return linkFn; } /** * Compile a textNode and return a nodeLinkFn. * * @param {TextNode} node * @param {Object} options * @return {Function|null} textNodeLinkFn */ function compileTextNode(node, options) { // skip marked text nodes if (node._skip) { return removeText; } var tokens = parseText(node.wholeText); if (!tokens) { return null; } // mark adjacent text nodes as skipped, // because we are using node.wholeText to compile // all adjacent text nodes together. This fixes // issues in IE where sometimes it splits up a single // text node into multiple ones. var next = node.nextSibling; while (next && next.nodeType === 3) { next._skip = true; next = next.nextSibling; } var frag = document.createDocumentFragment(); var el, token; for (var i = 0, l = tokens.length; i < l; i++) { token = tokens[i]; el = token.tag ? processTextToken(token, options) : document.createTextNode(token.value); frag.appendChild(el); } return makeTextNodeLinkFn(tokens, frag, options); } /** * Linker for an skipped text node. * * @param {Vue} vm * @param {Text} node */ function removeText(vm, node) { remove(node); } /** * Process a single text token. * * @param {Object} token * @param {Object} options * @return {Node} */ function processTextToken(token, options) { var el; if (token.oneTime) { el = document.createTextNode(token.value); } else { if (token.html) { el = document.createComment('v-html'); setTokenType('html'); } else { // IE will clean up empty textNodes during // frag.cloneNode(true), so we have to give it // something here... el = document.createTextNode(' '); setTokenType('text'); } } function setTokenType(type) { if (token.descriptor) return; var parsed = parseDirective(token.value); token.descriptor = { name: type, def: directives[type], expression: parsed.expression, filters: parsed.filters }; } return el; } /** * Build a function that processes a textNode. * * @param {Array<Object>} tokens * @param {DocumentFragment} frag */ function makeTextNodeLinkFn(tokens, frag) { return function textNodeLinkFn(vm, el, host, scope) { var fragClone = frag.cloneNode(true); var childNodes = toArray(fragClone.childNodes); var token, value, node; for (var i = 0, l = tokens.length; i < l; i++) { token = tokens[i]; value = token.value; if (token.tag) { node = childNodes[i]; if (token.oneTime) { value = (scope || vm).$eval(value); if (token.html) { replace(node, parseTemplate(value, true)); } else { node.data = value; } } else { vm._bindDir(token.descriptor, node, host, scope); } } } replace(el, fragClone); }; } /** * Compile a node list and return a childLinkFn. * * @param {NodeList} nodeList * @param {Object} options * @return {Function|undefined} */ function compileNodeList(nodeList, options) { var linkFns = []; var nodeLinkFn, childLinkFn, node; for (var i = 0, l = nodeList.length; i < l; i++) { node = nodeList[i]; nodeLinkFn = compileNode(node, options); childLinkFn = !(nodeLinkFn && nodeLinkFn.terminal) && node.tagName !== 'SCRIPT' && node.hasChildNodes() ? compileNodeList(node.childNodes, options) : null; linkFns.push(nodeLinkFn, childLinkFn); } return linkFns.length ? makeChildLinkFn(linkFns) : null; } /** * Make a child link function for a node's childNodes. * * @param {Array<Function>} linkFns * @return {Function} childLinkFn */ function makeChildLinkFn(linkFns) { return function childLinkFn(vm, nodes, host, scope, frag) { var node, nodeLinkFn, childrenLinkFn; for (var i = 0, n = 0, l = linkFns.length; i < l; n++) { node = nodes[n]; nodeLinkFn = linkFns[i++]; childrenLinkFn = linkFns[i++]; // cache childNodes before linking parent, fix #657 var childNodes = toArray(node.childNodes); if (nodeLinkFn) { nodeLinkFn(vm, node, host, scope, frag); } if (childrenLinkFn) { childrenLinkFn(vm, childNodes, host, scope, frag); } } }; } /** * Check for element directives (custom elements that should * be resovled as terminal directives). * * @param {Element} el * @param {Object} options */ function checkElementDirectives(el, options) { var tag = el.tagName.toLowerCase(); if (commonTagRE.test(tag)) { return; } var def = resolveAsset(options, 'elementDirectives', tag); if (def) { return makeTerminalNodeLinkFn(el, tag, '', options, def); } } /** * Check if an element is a component. If yes, return * a component link function. * * @param {Element} el * @param {Object} options * @return {Function|undefined} */ function checkComponent(el, options) { var component = checkComponentAttr(el, options); if (component) { var ref = findRef(el); var descriptor = { name: 'component', ref: ref, expression: component.id, def: internalDirectives.component, modifiers: { literal: !component.dynamic } }; var componentLinkFn = function componentLinkFn(vm, el, host, scope, frag) { if (ref) { defineReactive((scope || vm).$refs, ref, null); } vm._bindDir(descriptor, el, host, scope, frag); }; componentLinkFn.terminal = true; return componentLinkFn; } } /** * Check an element for terminal directives in fixed order. * If it finds one, return a terminal link function. * * @param {Element} el * @param {Array} attrs * @param {Object} options * @return {Function} terminalLinkFn */ function checkTerminalDirectives(el, attrs, options) { // skip v-pre if (getAttr(el, 'v-pre') !== null) { return skip; } // skip v-else block, but only if following v-if if (el.hasAttribute('v-else')) { var prev = el.previousElementSibling; if (prev && prev.hasAttribute('v-if')) { return skip; } } var attr, name, value, matched, dirName, arg, def, termDef; for (var i = 0, j = attrs.length; i < j; i++) { attr = attrs[i]; if (matched = attr.name.match(dirAttrRE)) { def = resolveAsset(options, 'directives', matched[1]); if (def && def.terminal) { if (!termDef || (def.priority || DEFAULT_TERMINAL_PRIORITY) > termDef.priority) { termDef = def; name = attr.name; value = attr.value; dirName = matched[1]; arg = matched[2]; } } } } if (termDef) { return makeTerminalNodeLinkFn(el, dirName, value, options, termDef, name, arg); } } function skip() {} skip.terminal = true; /** * Build a node link function for a terminal directive. * A terminal link function terminates the current * compilation recursion and handles compilation of the * subtree in the directive. * * @param {Element} el * @param {String} dirName * @param {String} value * @param {Object} options * @param {Object} def * @param {String} [attrName] * @param {String} [arg] * @return {Function} terminalLinkFn */ function makeTerminalNodeLinkFn(el, dirName, value, options, def, attrName, arg) { var parsed = parseDirective(value); var descriptor = { name: dirName, expression: parsed.expression, filters: parsed.filters, raw: value, rawName: attrName, def: def }; if (attrName) { descriptor.rawName = attrName; descriptor.modifiers = parseModifiers(attrName); } if (arg) { descriptor.arg = arg.replace(modifierRE, ''); } // check ref for v-for and router-view if (dirName === 'for' || dirName === 'router-view') { descriptor.ref = findRef(el); } var fn = function terminalNodeLinkFn(vm, el, host, scope, frag) { if (descriptor.ref) { defineReactive((scope || vm).$refs, descriptor.ref, null); } vm._bindDir(descriptor, el, host, scope, frag); }; fn.terminal = true; return fn; } /** * Compile the directives on an element and return a linker. * * @param {Array|NamedNodeMap} attrs * @param {Object} options * @return {Function} */ function compileDirectives(attrs, options) { var i = attrs.length; var dirs = []; var attr, name, value, rawName, rawValue, dirName, arg, modifiers, dirDef, tokens, matched; while (i--) { attr = attrs[i]; name = rawName = attr.name; value = rawValue = attr.value; tokens = parseText(value); // reset arg arg = null; // check modifiers modifiers = parseModifiers(name); name = name.replace(modifierRE, ''); // attribute interpolations if (tokens) { value = tokensToExp(tokens); arg = name; pushDir('bind', directives.bind, tokens); // warn against mixing mustaches with v-bind if (process.env.NODE_ENV !== 'production') { if (name === 'class' && Array.prototype.some.call(attrs, function (attr) { return attr.name === ':class' || attr.name === 'v-bind:class'; })) { warn('class="' + rawValue + '": Do not mix mustache interpolation ' + 'and v-bind for "class" on the same element. Use one or the other.'); } } } else // special attribute: transition if (transitionRE.test(name)) { modifiers.literal = !bindRE.test(name); pushDir('transition', internalDirectives.transition); } else // event handlers if (onRE.test(name)) { arg = name.replace(onRE, ''); pushDir('on', directives.on); } else // attribute bindings if (bindRE.test(name)) { dirName = name.replace(bindRE, ''); if (dirName === 'style' || dirName === 'class') { pushDir(dirName, internalDirectives[dirName]); } else { arg = dirName; pushDir('bind', directives.bind); } } else // normal directives if (matched = name.match(dirAttrRE)) { dirName = matched[1]; arg = matched[2]; // skip v-else (when used with v-show) if (dirName === 'else') { continue; } dirDef = resolveAsset(options, 'directives', dirName); if (process.env.NODE_ENV !== 'production') { assertAsset(dirDef, 'directive', dirName); } if (dirDef) { pushDir(dirName, dirDef); } } } /** * Push a directive. * * @param {String} dirName * @param {Object|Function} def * @param {Array} [interpTokens] */ function pushDir(dirName, def, interpTokens) { var hasOneTimeToken = interpTokens && hasOneTime(interpTokens); var parsed = !hasOneTimeToken && parseDirective(value); dirs.push({ name: dirName, attr: rawName, raw: rawValue, def: def, arg: arg, modifiers: modifiers, // conversion from interpolation strings with one-time token // to expression is differed until directive bind time so that we // have access to the actual vm context for one-time bindings. expression: parsed && parsed.expression, filters: parsed && parsed.filters, interp: interpTokens, hasOneTime: hasOneTimeToken }); } if (dirs.length) { return makeNodeLinkFn(dirs); } } /** * Parse modifiers from directive attribute name. * * @param {String} name * @return {Object} */ function parseModifiers(name) { var res = Object.create(null); var match = name.match(modifierRE); if (match) { var i = match.length; while (i--) { res[match[i].slice(1)] = true; } } return res; } /** * Build a link function for all directives on a single node. * * @param {Array} directives * @return {Function} directivesLinkFn */ function makeNodeLinkFn(directives) { return function nodeLinkFn(vm, el, host, scope, frag) { // reverse apply because it's sorted low to high var i = directives.length; while (i--) { vm._bindDir(directives[i], el, host, scope, frag); } }; } /** * Check if an interpolation string contains one-time tokens. * * @param {Array} tokens * @return {Boolean} */ function hasOneTime(tokens) { var i = tokens.length; while (i--) { if (tokens[i].oneTime) return true; } } var specialCharRE = /[^\w\-:\.]/; /** * Process an element or a DocumentFragment based on a * instance option object. This allows us to transclude * a template node/fragment before the instance is created, * so the processed fragment can then be cloned and reused * in v-for. * * @param {Element} el * @param {Object} options * @return {Element|DocumentFragment} */ function transclude(el, options) { // extract container attributes to pass them down // to compiler, because they need to be compiled in // parent scope. we are mutating the options object here // assuming the same object will be used for compile // right after this. if (options) { options._containerAttrs = extractAttrs(el); } // for template tags, what we want is its content as // a documentFragment (for fragment instances) if (isTemplate(el)) { el = parseTemplate(el); } if (options) { if (options._asComponent && !options.template) { options.template = '<slot></slot>'; } if (options.template) { options._content = extractContent(el); el = transcludeTemplate(el, options); } } if (isFragment(el)) { // anchors for fragment instance // passing in `persist: true` to avoid them being // discarded by IE during template cloning prepend(createAnchor('v-start', true), el); el.appendChild(createAnchor('v-end', true)); } return el; } /** * Process the template option. * If the replace option is true this will swap the $el. * * @param {Element} el * @param {Object} options * @return {Element|DocumentFragment} */ function transcludeTemplate(el, options) { var template = options.template; var frag = parseTemplate(template, true); if (frag) { var replacer = frag.firstChild; var tag = replacer.tagName && replacer.tagName.toLowerCase(); if (options.replace) { /* istanbul ignore if */ if (el === document.body) { process.env.NODE_ENV !== 'production' && warn('You are mounting an instance with a template to ' + '<body>. This will replace <body> entirely. You ' + 'should probably use `replace: false` here.'); } // there are many cases where the instance must // become a fragment instance: basically anything that // can create more than 1 root nodes. if ( // multi-children template frag.childNodes.length > 1 || // non-element template replacer.nodeType !== 1 || // single nested component tag === 'component' || resolveAsset(options, 'components', tag) || hasBindAttr(replacer, 'is') || // element directive resolveAsset(options, 'elementDirectives', tag) || // for block replacer.hasAttribute('v-for') || // if block replacer.hasAttribute('v-if')) { return frag; } else { options._replacerAttrs = extractAttrs(replacer); mergeAttrs(el, replacer); return replacer; } } else { el.appendChild(frag); return el; } } else { process.env.NODE_ENV !== 'production' && warn('Invalid template option: ' + template); } } /** * Helper to extract a component container's attributes * into a plain object array. * * @param {Element} el * @return {Array} */ function extractAttrs(el) { if (el.nodeType === 1 && el.hasAttributes()) { return toArray(el.attributes); } } /** * Merge the attributes of two elements, and make sure * the class names are merged properly. * * @param {Element} from * @param {Element} to */ function mergeAttrs(from, to) { var attrs = from.attributes; var i = attrs.length; var name, value; while (i--) { name = attrs[i].name; value = attrs[i].value; if (!to.hasAttribute(name) && !specialCharRE.test(name)) { to.setAttribute(name, value); } else if (name === 'class' && !parseText(value)) { value.trim().split(/\s+/).forEach(function (cls) { addClass(to, cls); }); } } } /** * Scan and determine slot content distribution. * We do this during transclusion instead at compile time so that * the distribution is decoupled from the compilation order of * the slots. * * @param {Element|DocumentFragment} template * @param {Element} content * @param {Vue} vm */ function resolveSlots(vm, content) { if (!content) { return; } var contents = vm._slotContents = Object.create(null); var el, name; for (var i = 0, l = content.children.length; i < l; i++) { el = content.children[i]; /* eslint-disable no-cond-assign */ if (name = el.getAttribute('slot')) { (contents[name] || (contents[name] = [])).push(el); } /* eslint-enable no-cond-assign */ if (process.env.NODE_ENV !== 'production' && getBindAttr(el, 'slot')) { warn('The "slot" attribute must be static.'); } } for (name in contents) { contents[name] = extractFragment(contents[name], content); } if (content.hasChildNodes()) { contents['default'] = extractFragment(content.childNodes, content); } } /** * Extract qualified content nodes from a node list. * * @param {NodeList} nodes * @return {DocumentFragment} */ function extractFragment(nodes, parent) { var frag = document.createDocumentFragment(); nodes = toArray(nodes); for (var i = 0, l = nodes.length; i < l; i++) { var node = nodes[i]; if (isTemplate(node) && !node.hasAttribute('v-if') && !node.hasAttribute('v-for')) { parent.removeChild(node); node = parseTemplate(node); } frag.appendChild(node); } return frag; } var compiler = Object.freeze({ compile: compile, compileAndLinkProps: compileAndLinkProps, compileRoot: compileRoot, transclude: transclude, resolveSlots: resolveSlots }); function stateMixin (Vue) { /** * Accessor for `$data` property, since setting $data * requires observing the new object and updating * proxied properties. */ Object.defineProperty(Vue.prototype, '$data', { get: function get() { return this._data; }, set: function set(newData) { if (newData !== this._data) { this._setData(newData); } } }); /** * Setup the scope of an instance, which contains: * - observed data * - computed properties * - user methods * - meta properties */ Vue.prototype._initState = function () { this._initProps(); this._initMeta(); this._initMethods(); this._initData(); this._initComputed(); }; /** * Initialize props. */ Vue.prototype._initProps = function () { var options = this.$options; var el = options.el; var props = options.props; if (props && !el) { process.env.NODE_ENV !== 'production' && warn('Props will not be compiled if no `el` option is ' + 'provided at instantiation.'); } // make sure to convert string selectors into element now el = options.el = query(el); this._propsUnlinkFn = el && el.nodeType === 1 && props // props must be linked in proper scope if inside v-for ? compileAndLinkProps(this, el, props, this._scope) : null; }; /** * Initialize the data. */ Vue.prototype._initData = function () { var dataFn = this.$options.data; var data = this._data = dataFn ? dataFn() : {}; if (!isPlainObject(data)) { data = {}; process.env.NODE_ENV !== 'production' && warn('data functions should return an object.'); } var props = this._props; var runtimeData = this._runtimeData ? typeof this._runtimeData === 'function' ? this._runtimeData() : this._runtimeData : null; // proxy data on instance var keys = Object.keys(data); var i, key; i = keys.length; while (i--) { key = keys[i]; // there are two scenarios where we can proxy a data key: // 1. it's not already defined as a prop // 2. it's provided via a instantiation option AND there are no // template prop present if (!props || !hasOwn(props, key) || runtimeData && hasOwn(runtimeData, key) && props[key].raw === null) { this._proxy(key); } else if (process.env.NODE_ENV !== 'production') { warn('Data field "' + key + '" is already defined ' + 'as a prop. Use prop default value instead.'); } } // observe data observe(data, this); }; /** * Swap the instance's $data. Called in $data's setter. * * @param {Object} newData */ Vue.prototype._setData = function (newData) { newData = newData || {}; var oldData = this._data; this._data = newData; var keys, key, i; // unproxy keys not present in new data keys = Object.keys(oldData); i = keys.length; while (i--) { key = keys[i]; if (!(key in newData)) { this._unproxy(key); } } // proxy keys not already proxied, // and trigger change for changed values keys = Object.keys(newData); i = keys.length; while (i--) { key = keys[i]; if (!hasOwn(this, key)) { // new property this._proxy(key); } } oldData.__ob__.removeVm(this); observe(newData, this); this._digest(); }; /** * Proxy a property, so that * vm.prop === vm._data.prop * * @param {String} key */ Vue.prototype._proxy = function (key) { if (!isReserved(key)) { // need to store ref to self here // because these getter/setters might // be called by child scopes via // prototype inheritance. var self = this; Object.defineProperty(self, key, { configurable: true, enumerable: true, get: function proxyGetter() { return self._data[key]; }, set: function proxySetter(val) { self._data[key] = val; } }); } }; /** * Unproxy a property. * * @param {String} key */ Vue.prototype._unproxy = function (key) { if (!isReserved(key)) { delete this[key]; } }; /** * Force update on every watcher in scope. */ Vue.prototype._digest = function () { for (var i = 0, l = this._watchers.length; i < l; i++) { this._watchers[i].update(true); // shallow updates } }; /** * Setup computed properties. They are essentially * special getter/setters */ function noop() {} Vue.prototype._initComputed = function () { var computed = this.$options.computed; if (computed) { for (var key in computed) { var userDef = computed[key]; var def = { enumerable: true, configurable: true }; if (typeof userDef === 'function') { def.get = makeComputedGetter(userDef, this); def.set = noop; } else { def.get = userDef.get ? userDef.cache !== false ? makeComputedGetter(userDef.get, this) : bind(userDef.get, this) : noop; def.set = userDef.set ? bind(userDef.set, this) : noop; } Object.defineProperty(this, key, def); } } }; function makeComputedGetter(getter, owner) { var watcher = new Watcher(owner, getter, null, { lazy: true }); return function computedGetter() { if (watcher.dirty) { watcher.evaluate(); } if (Dep.target) { watcher.depend(); } return watcher.value; }; } /** * Setup instance methods. Methods must be bound to the * instance since they might be passed down as a prop to * child components. */ Vue.prototype._initMethods = function () { var methods = this.$options.methods; if (methods) { for (var key in methods) { this[key] = bind(methods[key], this); } } }; /** * Initialize meta information like $index, $key & $value. */ Vue.prototype._initMeta = function () { var metas = this.$options._meta; if (metas) { for (var key in metas) { defineReactive(this, key, metas[key]); } } }; } var eventRE = /^v-on:|^@/; function eventsMixin (Vue) { /** * Setup the instance's option events & watchers. * If the value is a string, we pull it from the * instance's methods by name. */ Vue.prototype._initEvents = function () { var options = this.$options; if (options._asComponent) { registerComponentEvents(this, options.el); } registerCallbacks(this, '$on', options.events); registerCallbacks(this, '$watch', options.watch); }; /** * Register v-on events on a child component * * @param {Vue} vm * @param {Element} el */ function registerComponentEvents(vm, el) { var attrs = el.attributes; var name, handler; for (var i = 0, l = attrs.length; i < l; i++) { name = attrs[i].name; if (eventRE.test(name)) { name = name.replace(eventRE, ''); handler = (vm._scope || vm._context).$eval(attrs[i].value, true); if (typeof handler === 'function') { handler._fromParent = true; vm.$on(name.replace(eventRE), handler); } else if (process.env.NODE_ENV !== 'production') { warn('v-on:' + name + '="' + attrs[i].value + '"' + (vm.$options.name ? ' on component <' + vm.$options.name + '>' : '') + ' expects a function value, got ' + handler); } } } } /** * Register callbacks for option events and watchers. * * @param {Vue} vm * @param {String} action * @param {Object} hash */ function registerCallbacks(vm, action, hash) { if (!hash) return; var handlers, key, i, j; for (key in hash) { handlers = hash[key]; if (isArray(handlers)) { for (i = 0, j = handlers.length; i < j; i++) { register(vm, action, key, handlers[i]); } } else { register(vm, action, key, handlers); } } } /** * Helper to register an event/watch callback. * * @param {Vue} vm * @param {String} action * @param {String} key * @param {Function|String|Object} handler * @param {Object} [options] */ function register(vm, action, key, handler, options) { var type = typeof handler; if (type === 'function') { vm[action](key, handler, options); } else if (type === 'string') { var methods = vm.$options.methods; var method = methods && methods[handler]; if (method) { vm[action](key, method, options); } else { process.env.NODE_ENV !== 'production' && warn('Unknown method: "' + handler + '" when ' + 'registering callback for ' + action + ': "' + key + '".'); } } else if (handler && type === 'object') { register(vm, action, key, handler.handler, handler); } } /** * Setup recursive attached/detached calls */ Vue.prototype._initDOMHooks = function () { this.$on('hook:attached', onAttached); this.$on('hook:detached', onDetached); }; /** * Callback to recursively call attached hook on children */ function onAttached() { if (!this._isAttached) { this._isAttached = true; this.$children.forEach(callAttach); } } /** * Iterator to call attached hook * * @param {Vue} child */ function callAttach(child) { if (!child._isAttached && inDoc(child.$el)) { child._callHook('attached'); } } /** * Callback to recursively call detached hook on children */ function onDetached() { if (this._isAttached) { this._isAttached = false; this.$children.forEach(callDetach); } } /** * Iterator to call detached hook * * @param {Vue} child */ function callDetach(child) { if (child._isAttached && !inDoc(child.$el)) { child._callHook('detached'); } } /** * Trigger all handlers for a hook * * @param {String} hook */ Vue.prototype._callHook = function (hook) { this.$emit('pre-hook:' + hook); var handlers = this.$options[hook]; if (handlers) { for (var i = 0, j = handlers.length; i < j; i++) { handlers[i].call(this); } } this.$emit('hook:' + hook); }; } function noop() {} /** * A directive links a DOM element with a piece of data, * which is the result of evaluating an expression. * It registers a watcher with the expression and calls * the DOM update function when a change is triggered. * * @param {Object} descriptor * - {String} name * - {Object} def * - {String} expression * - {Array<Object>} [filters] * - {Object} [modifiers] * - {Boolean} literal * - {String} attr * - {String} arg * - {String} raw * - {String} [ref] * - {Array<Object>} [interp] * - {Boolean} [hasOneTime] * @param {Vue} vm * @param {Node} el * @param {Vue} [host] - transclusion host component * @param {Object} [scope] - v-for scope * @param {Fragment} [frag] - owner fragment * @constructor */ function Directive(descriptor, vm, el, host, scope, frag) { this.vm = vm; this.el = el; // copy descriptor properties this.descriptor = descriptor; this.name = descriptor.name; this.expression = descriptor.expression; this.arg = descriptor.arg; this.modifiers = descriptor.modifiers; this.filters = descriptor.filters; this.literal = this.modifiers && this.modifiers.literal; // private this._locked = false; this._bound = false; this._listeners = null; // link context this._host = host; this._scope = scope; this._frag = frag; // store directives on node in dev mode if (process.env.NODE_ENV !== 'production' && this.el) { this.el._vue_directives = this.el._vue_directives || []; this.el._vue_directives.push(this); } } /** * Initialize the directive, mixin definition properties, * setup the watcher, call definition bind() and update() * if present. */ Directive.prototype._bind = function () { var name = this.name; var descriptor = this.descriptor; // remove attribute if ((name !== 'cloak' || this.vm._isCompiled) && this.el && this.el.removeAttribute) { var attr = descriptor.attr || 'v-' + name; this.el.removeAttribute(attr); } // copy def properties var def = descriptor.def; if (typeof def === 'function') { this.update = def; } else { extend(this, def); } // setup directive params this._setupParams(); // initial bind if (this.bind) { this.bind(); } this._bound = true; if (this.literal) { this.update && this.update(descriptor.raw); } else if ((this.expression || this.modifiers) && (this.update || this.twoWay) && !this._checkStatement()) { // wrapped updater for context var dir = this; if (this.update) { this._update = function (val, oldVal) { if (!dir._locked) { dir.update(val, oldVal); } }; } else { this._update = noop; } var preProcess = this._preProcess ? bind(this._preProcess, this) : null; var postProcess = this._postProcess ? bind(this._postProcess, this) : null; var watcher = this._watcher = new Watcher(this.vm, this.expression, this._update, // callback { filters: this.filters, twoWay: this.twoWay, deep: this.deep, preProcess: preProcess, postProcess: postProcess, scope: this._scope }); // v-model with inital inline value need to sync back to // model instead of update to DOM on init. They would // set the afterBind hook to indicate that. if (this.afterBind) { this.afterBind(); } else if (this.update) { this.update(watcher.value); } } }; /** * Setup all param attributes, e.g. track-by, * transition-mode, etc... */ Directive.prototype._setupParams = function () { if (!this.params) { return; } var params = this.params; // swap the params array with a fresh object. this.params = Object.create(null); var i = params.length; var key, val, mappedKey; while (i--) { key = params[i]; mappedKey = camelize(key); val = getBindAttr(this.el, key); if (val != null) { // dynamic this._setupParamWatcher(mappedKey, val); } else { // static val = getAttr(this.el, key); if (val != null) { this.params[mappedKey] = val === '' ? true : val; } } } }; /** * Setup a watcher for a dynamic param. * * @param {String} key * @param {String} expression */ Directive.prototype._setupParamWatcher = function (key, expression) { var self = this; var called = false; var unwatch = (this._scope || this.vm).$watch(expression, function (val, oldVal) { self.params[key] = val; // since we are in immediate mode, // only call the param change callbacks if this is not the first update. if (called) { var cb = self.paramWatchers && self.paramWatchers[key]; if (cb) { cb.call(self, val, oldVal); } } else { called = true; } }, { immediate: true, user: false });(this._paramUnwatchFns || (this._paramUnwatchFns = [])).push(unwatch); }; /** * Check if the directive is a function caller * and if the expression is a callable one. If both true, * we wrap up the expression and use it as the event * handler. * * e.g. on-click="a++" * * @return {Boolean} */ Directive.prototype._checkStatement = function () { var expression = this.expression; if (expression && this.acceptStatement && !isSimplePath(expression)) { var fn = parseExpression(expression).get; var scope = this._scope || this.vm; var handler = function handler(e) { scope.$event = e; fn.call(scope, scope); scope.$event = null; }; if (this.filters) { handler = scope._applyFilters(handler, null, this.filters); } this.update(handler); return true; } }; /** * Set the corresponding value with the setter. * This should only be used in two-way directives * e.g. v-model. * * @param {*} value * @public */ Directive.prototype.set = function (value) { /* istanbul ignore else */ if (this.twoWay) { this._withLock(function () { this._watcher.set(value); }); } else if (process.env.NODE_ENV !== 'production') { warn('Directive.set() can only be used inside twoWay' + 'directives.'); } }; /** * Execute a function while preventing that function from * triggering updates on this directive instance. * * @param {Function} fn */ Directive.prototype._withLock = function (fn) { var self = this; self._locked = true; fn.call(self); nextTick(function () { self._locked = false; }); }; /** * Convenience method that attaches a DOM event listener * to the directive element and autometically tears it down * during unbind. * * @param {String} event * @param {Function} handler * @param {Boolean} [useCapture] */ Directive.prototype.on = function (event, handler, useCapture) { on(this.el, event, handler, useCapture);(this._listeners || (this._listeners = [])).push([event, handler]); }; /** * Teardown the watcher and call unbind. */ Directive.prototype._teardown = function () { if (this._bound) { this._bound = false; if (this.unbind) { this.unbind(); } if (this._watcher) { this._watcher.teardown(); } var listeners = this._listeners; var i; if (listeners) { i = listeners.length; while (i--) { off(this.el, listeners[i][0], listeners[i][1]); } } var unwatchFns = this._paramUnwatchFns; if (unwatchFns) { i = unwatchFns.length; while (i--) { unwatchFns[i](); } } if (process.env.NODE_ENV !== 'production' && this.el) { this.el._vue_directives.$remove(this); } this.vm = this.el = this._watcher = this._listeners = null; } }; function lifecycleMixin (Vue) { /** * Update v-ref for component. * * @param {Boolean} remove */ Vue.prototype._updateRef = function (remove) { var ref = this.$options._ref; if (ref) { var refs = (this._scope || this._context).$refs; if (remove) { if (refs[ref] === this) { refs[ref] = null; } } else { refs[ref] = this; } } }; /** * Transclude, compile and link element. * * If a pre-compiled linker is available, that means the * passed in element will be pre-transcluded and compiled * as well - all we need to do is to call the linker. * * Otherwise we need to call transclude/compile/link here. * * @param {Element} el */ Vue.prototype._compile = function (el) { var options = this.$options; // transclude and init element // transclude can potentially replace original // so we need to keep reference; this step also injects // the template and caches the original attributes // on the container node and replacer node. var original = el; el = transclude(el, options); this._initElement(el); // handle v-pre on root node (#2026) if (el.nodeType === 1 && getAttr(el, 'v-pre') !== null) { return; } // root is always compiled per-instance, because // container attrs and props can be different every time. var contextOptions = this._context && this._context.$options; var rootLinker = compileRoot(el, options, contextOptions); // resolve slot distribution resolveSlots(this, options._content); // compile and link the rest var contentLinkFn; var ctor = this.constructor; // component compilation can be cached // as long as it's not using inline-template if (options._linkerCachable) { contentLinkFn = ctor.linker; if (!contentLinkFn) { contentLinkFn = ctor.linker = compile(el, options); } } // link phase // make sure to link root with prop scope! var rootUnlinkFn = rootLinker(this, el, this._scope); var contentUnlinkFn = contentLinkFn ? contentLinkFn(this, el) : compile(el, options)(this, el); // register composite unlink function // to be called during instance destruction this._unlinkFn = function () { rootUnlinkFn(); // passing destroying: true to avoid searching and // splicing the directives contentUnlinkFn(true); }; // finally replace original if (options.replace) { replace(original, el); } this._isCompiled = true; this._callHook('compiled'); }; /** * Initialize instance element. Called in the public * $mount() method. * * @param {Element} el */ Vue.prototype._initElement = function (el) { if (isFragment(el)) { this._isFragment = true; this.$el = this._fragmentStart = el.firstChild; this._fragmentEnd = el.lastChild; // set persisted text anchors to empty if (this._fragmentStart.nodeType === 3) { this._fragmentStart.data = this._fragmentEnd.data = ''; } this._fragment = el; } else { this.$el = el; } this.$el.__vue__ = this; this._callHook('beforeCompile'); }; /** * Create and bind a directive to an element. * * @param {Object} descriptor - parsed directive descriptor * @param {Node} node - target node * @param {Vue} [host] - transclusion host component * @param {Object} [scope] - v-for scope * @param {Fragment} [frag] - owner fragment */ Vue.prototype._bindDir = function (descriptor, node, host, scope, frag) { this._directives.push(new Directive(descriptor, this, node, host, scope, frag)); }; /** * Teardown an instance, unobserves the data, unbind all the * directives, turn off all the event listeners, etc. * * @param {Boolean} remove - whether to remove the DOM node. * @param {Boolean} deferCleanup - if true, defer cleanup to * be called later */ Vue.prototype._destroy = function (remove, deferCleanup) { if (this._isBeingDestroyed) { if (!deferCleanup) { this._cleanup(); } return; } var destroyReady; var pendingRemoval; var self = this; // Cleanup should be called either synchronously or asynchronoysly as // callback of this.$remove(), or if remove and deferCleanup are false. // In any case it should be called after all other removing, unbinding and // turning of is done var cleanupIfPossible = function cleanupIfPossible() { if (destroyReady && !pendingRemoval && !deferCleanup) { self._cleanup(); } }; // remove DOM element if (remove && this.$el) { pendingRemoval = true; this.$remove(function () { pendingRemoval = false; cleanupIfPossible(); }); } this._callHook('beforeDestroy'); this._isBeingDestroyed = true; var i; // remove self from parent. only necessary // if parent is not being destroyed as well. var parent = this.$parent; if (parent && !parent._isBeingDestroyed) { parent.$children.$remove(this); // unregister ref (remove: true) this._updateRef(true); } // destroy all children. i = this.$children.length; while (i--) { this.$children[i].$destroy(); } // teardown props if (this._propsUnlinkFn) { this._propsUnlinkFn(); } // teardown all directives. this also tearsdown all // directive-owned watchers. if (this._unlinkFn) { this._unlinkFn(); } i = this._watchers.length; while (i--) { this._watchers[i].teardown(); } // remove reference to self on $el if (this.$el) { this.$el.__vue__ = null; } destroyReady = true; cleanupIfPossible(); }; /** * Clean up to ensure garbage collection. * This is called after the leave transition if there * is any. */ Vue.prototype._cleanup = function () { if (this._isDestroyed) { return; } // remove self from owner fragment // do it in cleanup so that we can call $destroy with // defer right when a fragment is about to be removed. if (this._frag) { this._frag.children.$remove(this); } // remove reference from data ob // frozen object may not have observer. if (this._data.__ob__) { this._data.__ob__.removeVm(this); } // Clean up references to private properties and other // instances. preserve reference to _data so that proxy // accessors still work. The only potential side effect // here is that mutating the instance after it's destroyed // may affect the state of other components that are still // observing the same object, but that seems to be a // reasonable responsibility for the user rather than // always throwing an error on them. this.$el = this.$parent = this.$root = this.$children = this._watchers = this._context = this._scope = this._directives = null; // call the last hook... this._isDestroyed = true; this._callHook('destroyed'); // turn off all instance listeners. this.$off(); }; } function miscMixin (Vue) { /** * Apply a list of filter (descriptors) to a value. * Using plain for loops here because this will be called in * the getter of any watcher with filters so it is very * performance sensitive. * * @param {*} value * @param {*} [oldValue] * @param {Array} filters * @param {Boolean} write * @return {*} */ Vue.prototype._applyFilters = function (value, oldValue, filters, write) { var filter, fn, args, arg, offset, i, l, j, k; for (i = 0, l = filters.length; i < l; i++) { filter = filters[write ? l - i - 1 : i]; fn = resolveAsset(this.$options, 'filters', filter.name); if (process.env.NODE_ENV !== 'production') { assertAsset(fn, 'filter', filter.name); } if (!fn) continue; fn = write ? fn.write : fn.read || fn; if (typeof fn !== 'function') continue; args = write ? [value, oldValue] : [value]; offset = write ? 2 : 1; if (filter.args) { for (j = 0, k = filter.args.length; j < k; j++) { arg = filter.args[j]; args[j + offset] = arg.dynamic ? this.$get(arg.value) : arg.value; } } value = fn.apply(this, args); } return value; }; /** * Resolve a component, depending on whether the component * is defined normally or using an async factory function. * Resolves synchronously if already resolved, otherwise * resolves asynchronously and caches the resolved * constructor on the factory. * * @param {String|Function} value * @param {Function} cb */ Vue.prototype._resolveComponent = function (value, cb) { var factory; if (typeof value === 'function') { factory = value; } else { factory = resolveAsset(this.$options, 'components', value); if (process.env.NODE_ENV !== 'production') { assertAsset(factory, 'component', value); } } if (!factory) { return; } // async component factory if (!factory.options) { if (factory.resolved) { // cached cb(factory.resolved); } else if (factory.requested) { // pool callbacks factory.pendingCallbacks.push(cb); } else { factory.requested = true; var cbs = factory.pendingCallbacks = [cb]; factory.call(this, function resolve(res) { if (isPlainObject(res)) { res = Vue.extend(res); } // cache resolved factory.resolved = res; // invoke callbacks for (var i = 0, l = cbs.length; i < l; i++) { cbs[i](res); } }, function reject(reason) { process.env.NODE_ENV !== 'production' && warn('Failed to resolve async component' + (typeof value === 'string' ? ': ' + value : '') + '. ' + (reason ? '\nReason: ' + reason : '')); }); } } else { // normal component cb(factory); } }; } var filterRE$1 = /[^|]\|[^|]/; function dataAPI (Vue) { /** * Get the value from an expression on this vm. * * @param {String} exp * @param {Boolean} [asStatement] * @return {*} */ Vue.prototype.$get = function (exp, asStatement) { var res = parseExpression(exp); if (res) { if (asStatement && !isSimplePath(exp)) { var self = this; return function statementHandler() { self.$arguments = toArray(arguments); var result = res.get.call(self, self); self.$arguments = null; return result; }; } else { try { return res.get.call(this, this); } catch (e) {} } } }; /** * Set the value from an expression on this vm. * The expression must be a valid left-hand * expression in an assignment. * * @param {String} exp * @param {*} val */ Vue.prototype.$set = function (exp, val) { var res = parseExpression(exp, true); if (res && res.set) { res.set.call(this, this, val); } }; /** * Delete a property on the VM * * @param {String} key */ Vue.prototype.$delete = function (key) { del(this._data, key); }; /** * Watch an expression, trigger callback when its * value changes. * * @param {String|Function} expOrFn * @param {Function} cb * @param {Object} [options] * - {Boolean} deep * - {Boolean} immediate * @return {Function} - unwatchFn */ Vue.prototype.$watch = function (expOrFn, cb, options) { var vm = this; var parsed; if (typeof expOrFn === 'string') { parsed = parseDirective(expOrFn); expOrFn = parsed.expression; } var watcher = new Watcher(vm, expOrFn, cb, { deep: options && options.deep, sync: options && options.sync, filters: parsed && parsed.filters, user: !options || options.user !== false }); if (options && options.immediate) { cb.call(vm, watcher.value); } return function unwatchFn() { watcher.teardown(); }; }; /** * Evaluate a text directive, including filters. * * @param {String} text * @param {Boolean} [asStatement] * @return {String} */ Vue.prototype.$eval = function (text, asStatement) { // check for filters. if (filterRE$1.test(text)) { var dir = parseDirective(text); // the filter regex check might give false positive // for pipes inside strings, so it's possible that // we don't get any filters here var val = this.$get(dir.expression, asStatement); return dir.filters ? this._applyFilters(val, null, dir.filters) : val; } else { // no filter return this.$get(text, asStatement); } }; /** * Interpolate a piece of template text. * * @param {String} text * @return {String} */ Vue.prototype.$interpolate = function (text) { var tokens = parseText(text); var vm = this; if (tokens) { if (tokens.length === 1) { return vm.$eval(tokens[0].value) + ''; } else { return tokens.map(function (token) { return token.tag ? vm.$eval(token.value) : token.value; }).join(''); } } else { return text; } }; /** * Log instance data as a plain JS object * so that it is easier to inspect in console. * This method assumes console is available. * * @param {String} [path] */ Vue.prototype.$log = function (path) { var data = path ? getPath(this._data, path) : this._data; if (data) { data = clean(data); } // include computed fields if (!path) { var key; for (key in this.$options.computed) { data[key] = clean(this[key]); } if (this._props) { for (key in this._props) { data[key] = clean(this[key]); } } } console.log(data); }; /** * "clean" a getter/setter converted object into a plain * object copy. * * @param {Object} - obj * @return {Object} */ function clean(obj) { return JSON.parse(JSON.stringify(obj)); } } function domAPI (Vue) { /** * Convenience on-instance nextTick. The callback is * auto-bound to the instance, and this avoids component * modules having to rely on the global Vue. * * @param {Function} fn */ Vue.prototype.$nextTick = function (fn) { nextTick(fn, this); }; /** * Append instance to target * * @param {Node} target * @param {Function} [cb] * @param {Boolean} [withTransition] - defaults to true */ Vue.prototype.$appendTo = function (target, cb, withTransition) { return insert(this, target, cb, withTransition, append, appendWithTransition); }; /** * Prepend instance to target * * @param {Node} target * @param {Function} [cb] * @param {Boolean} [withTransition] - defaults to true */ Vue.prototype.$prependTo = function (target, cb, withTransition) { target = query(target); if (target.hasChildNodes()) { this.$before(target.firstChild, cb, withTransition); } else { this.$appendTo(target, cb, withTransition); } return this; }; /** * Insert instance before target * * @param {Node} target * @param {Function} [cb] * @param {Boolean} [withTransition] - defaults to true */ Vue.prototype.$before = function (target, cb, withTransition) { return insert(this, target, cb, withTransition, beforeWithCb, beforeWithTransition); }; /** * Insert instance after target * * @param {Node} target * @param {Function} [cb] * @param {Boolean} [withTransition] - defaults to true */ Vue.prototype.$after = function (target, cb, withTransition) { target = query(target); if (target.nextSibling) { this.$before(target.nextSibling, cb, withTransition); } else { this.$appendTo(target.parentNode, cb, withTransition); } return this; }; /** * Remove instance from DOM * * @param {Function} [cb] * @param {Boolean} [withTransition] - defaults to true */ Vue.prototype.$remove = function (cb, withTransition) { if (!this.$el.parentNode) { return cb && cb(); } var inDocument = this._isAttached && inDoc(this.$el); // if we are not in document, no need to check // for transitions if (!inDocument) withTransition = false; var self = this; var realCb = function realCb() { if (inDocument) self._callHook('detached'); if (cb) cb(); }; if (this._isFragment) { removeNodeRange(this._fragmentStart, this._fragmentEnd, this, this._fragment, realCb); } else { var op = withTransition === false ? removeWithCb : removeWithTransition; op(this.$el, this, realCb); } return this; }; /** * Shared DOM insertion function. * * @param {Vue} vm * @param {Element} target * @param {Function} [cb] * @param {Boolean} [withTransition] * @param {Function} op1 - op for non-transition insert * @param {Function} op2 - op for transition insert * @return vm */ function insert(vm, target, cb, withTransition, op1, op2) { target = query(target); var targetIsDetached = !inDoc(target); var op = withTransition === false || targetIsDetached ? op1 : op2; var shouldCallHook = !targetIsDetached && !vm._isAttached && !inDoc(vm.$el); if (vm._isFragment) { mapNodeRange(vm._fragmentStart, vm._fragmentEnd, function (node) { op(node, target, vm); }); cb && cb(); } else { op(vm.$el, target, vm, cb); } if (shouldCallHook) { vm._callHook('attached'); } return vm; } /** * Check for selectors * * @param {String|Element} el */ function query(el) { return typeof el === 'string' ? document.querySelector(el) : el; } /** * Append operation that takes a callback. * * @param {Node} el * @param {Node} target * @param {Vue} vm - unused * @param {Function} [cb] */ function append(el, target, vm, cb) { target.appendChild(el); if (cb) cb(); } /** * InsertBefore operation that takes a callback. * * @param {Node} el * @param {Node} target * @param {Vue} vm - unused * @param {Function} [cb] */ function beforeWithCb(el, target, vm, cb) { before(el, target); if (cb) cb(); } /** * Remove operation that takes a callback. * * @param {Node} el * @param {Vue} vm - unused * @param {Function} [cb] */ function removeWithCb(el, vm, cb) { remove(el); if (cb) cb(); } } function eventsAPI (Vue) { /** * Listen on the given `event` with `fn`. * * @param {String} event * @param {Function} fn */ Vue.prototype.$on = function (event, fn) { (this._events[event] || (this._events[event] = [])).push(fn); modifyListenerCount(this, event, 1); return this; }; /** * Adds an `event` listener that will be invoked a single * time then automatically removed. * * @param {String} event * @param {Function} fn */ Vue.prototype.$once = function (event, fn) { var self = this; function on() { self.$off(event, on); fn.apply(this, arguments); } on.fn = fn; this.$on(event, on); return this; }; /** * Remove the given callback for `event` or all * registered callbacks. * * @param {String} event * @param {Function} fn */ Vue.prototype.$off = function (event, fn) { var cbs; // all if (!arguments.length) { if (this.$parent) { for (event in this._events) { cbs = this._events[event]; if (cbs) { modifyListenerCount(this, event, -cbs.length); } } } this._events = {}; return this; } // specific event cbs = this._events[event]; if (!cbs) { return this; } if (arguments.length === 1) { modifyListenerCount(this, event, -cbs.length); this._events[event] = null; return this; } // specific handler var cb; var i = cbs.length; while (i--) { cb = cbs[i]; if (cb === fn || cb.fn === fn) { modifyListenerCount(this, event, -1); cbs.splice(i, 1); break; } } return this; }; /** * Trigger an event on self. * * @param {String|Object} event * @return {Boolean} shouldPropagate */ Vue.prototype.$emit = function (event) { var isSource = typeof event === 'string'; event = isSource ? event : event.name; var cbs = this._events[event]; var shouldPropagate = isSource || !cbs; if (cbs) { cbs = cbs.length > 1 ? toArray(cbs) : cbs; // this is a somewhat hacky solution to the question raised // in #2102: for an inline component listener like <comp @test="doThis">, // the propagation handling is somewhat broken. Therefore we // need to treat these inline callbacks differently. var hasParentCbs = isSource && cbs.some(function (cb) { return cb._fromParent; }); if (hasParentCbs) { shouldPropagate = false; } var args = toArray(arguments, 1); for (var i = 0, l = cbs.length; i < l; i++) { var cb = cbs[i]; var res = cb.apply(this, args); if (res === true && (!hasParentCbs || cb._fromParent)) { shouldPropagate = true; } } } return shouldPropagate; }; /** * Recursively broadcast an event to all children instances. * * @param {String|Object} event * @param {...*} additional arguments */ Vue.prototype.$broadcast = function (event) { var isSource = typeof event === 'string'; event = isSource ? event : event.name; // if no child has registered for this event, // then there's no need to broadcast. if (!this._eventsCount[event]) return; var children = this.$children; var args = toArray(arguments); if (isSource) { // use object event to indicate non-source emit // on children args[0] = { name: event, source: this }; } for (var i = 0, l = children.length; i < l; i++) { var child = children[i]; var shouldPropagate = child.$emit.apply(child, args); if (shouldPropagate) { child.$broadcast.apply(child, args); } } return this; }; /** * Recursively propagate an event up the parent chain. * * @param {String} event * @param {...*} additional arguments */ Vue.prototype.$dispatch = function (event) { var shouldPropagate = this.$emit.apply(this, arguments); if (!shouldPropagate) return; var parent = this.$parent; var args = toArray(arguments); // use object event to indicate non-source emit // on parents args[0] = { name: event, source: this }; while (parent) { shouldPropagate = parent.$emit.apply(parent, args); parent = shouldPropagate ? parent.$parent : null; } return this; }; /** * Modify the listener counts on all parents. * This bookkeeping allows $broadcast to return early when * no child has listened to a certain event. * * @param {Vue} vm * @param {String} event * @param {Number} count */ var hookRE = /^hook:/; function modifyListenerCount(vm, event, count) { var parent = vm.$parent; // hooks do not get broadcasted so no need // to do bookkeeping for them if (!parent || !count || hookRE.test(event)) return; while (parent) { parent._eventsCount[event] = (parent._eventsCount[event] || 0) + count; parent = parent.$parent; } } } function lifecycleAPI (Vue) { /** * Set instance target element and kick off the compilation * process. The passed in `el` can be a selector string, an * existing Element, or a DocumentFragment (for block * instances). * * @param {Element|DocumentFragment|string} el * @public */ Vue.prototype.$mount = function (el) { if (this._isCompiled) { process.env.NODE_ENV !== 'production' && warn('$mount() should be called only once.'); return; } el = query(el); if (!el) { el = document.createElement('div'); } this._compile(el); this._initDOMHooks(); if (inDoc(this.$el)) { this._callHook('attached'); ready.call(this); } else { this.$once('hook:attached', ready); } return this; }; /** * Mark an instance as ready. */ function ready() { this._isAttached = true; this._isReady = true; this._callHook('ready'); } /** * Teardown the instance, simply delegate to the internal * _destroy. * * @param {Boolean} remove * @param {Boolean} deferCleanup */ Vue.prototype.$destroy = function (remove, deferCleanup) { this._destroy(remove, deferCleanup); }; /** * Partially compile a piece of DOM and return a * decompile function. * * @param {Element|DocumentFragment} el * @param {Vue} [host] * @param {Object} [scope] * @param {Fragment} [frag] * @return {Function} */ Vue.prototype.$compile = function (el, host, scope, frag) { return compile(el, this.$options, true)(this, el, host, scope, frag); }; } /** * The exposed Vue constructor. * * API conventions: * - public API methods/properties are prefixed with `$` * - internal methods/properties are prefixed with `_` * - non-prefixed properties are assumed to be proxied user * data. * * @constructor * @param {Object} [options] * @public */ function Vue(options) { this._init(options); } // install internals initMixin(Vue); stateMixin(Vue); eventsMixin(Vue); lifecycleMixin(Vue); miscMixin(Vue); // install instance APIs dataAPI(Vue); domAPI(Vue); eventsAPI(Vue); lifecycleAPI(Vue); var slot = { priority: SLOT, params: ['name'], bind: function bind() { // this was resolved during component transclusion var name = this.params.name || 'default'; var content = this.vm._slotContents && this.vm._slotContents[name]; if (!content || !content.hasChildNodes()) { this.fallback(); } else { this.compile(content.cloneNode(true), this.vm._context, this.vm); } }, compile: function compile(content, context, host) { if (content && context) { if (this.el.hasChildNodes() && content.childNodes.length === 1 && content.childNodes[0].nodeType === 1 && content.childNodes[0].hasAttribute('v-if')) { // if the inserted slot has v-if // inject fallback content as the v-else var elseBlock = document.createElement('template'); elseBlock.setAttribute('v-else', ''); elseBlock.innerHTML = this.el.innerHTML; // the else block should be compiled in child scope elseBlock._context = this.vm; content.appendChild(elseBlock); } var scope = host ? host._scope : this._scope; this.unlink = context.$compile(content, host, scope, this._frag); } if (content) { replace(this.el, content); } else { remove(this.el); } }, fallback: function fallback() { this.compile(extractContent(this.el, true), this.vm); }, unbind: function unbind() { if (this.unlink) { this.unlink(); } } }; var partial = { priority: PARTIAL, params: ['name'], // watch changes to name for dynamic partials paramWatchers: { name: function name(value) { vIf.remove.call(this); if (value) { this.insert(value); } } }, bind: function bind() { this.anchor = createAnchor('v-partial'); replace(this.el, this.anchor); this.insert(this.params.name); }, insert: function insert(id) { var partial = resolveAsset(this.vm.$options, 'partials', id); if (process.env.NODE_ENV !== 'production') { assertAsset(partial, 'partial', id); } if (partial) { this.factory = new FragmentFactory(this.vm, partial); vIf.insert.call(this); } }, unbind: function unbind() { if (this.frag) { this.frag.destroy(); } } }; var elementDirectives = { slot: slot, partial: partial }; var convertArray = vFor._postProcess; /** * Limit filter for arrays * * @param {Number} n * @param {Number} offset (Decimal expected) */ function limitBy(arr, n, offset) { offset = offset ? parseInt(offset, 10) : 0; n = toNumber(n); return typeof n === 'number' ? arr.slice(offset, offset + n) : arr; } /** * Filter filter for arrays * * @param {String} search * @param {String} [delimiter] * @param {String} ...dataKeys */ function filterBy(arr, search, delimiter) { arr = convertArray(arr); if (search == null) { return arr; } if (typeof search === 'function') { return arr.filter(search); } // cast to lowercase string search = ('' + search).toLowerCase(); // allow optional `in` delimiter // because why not var n = delimiter === 'in' ? 3 : 2; // extract and flatten keys var keys = toArray(arguments, n).reduce(function (prev, cur) { return prev.concat(cur); }, []); var res = []; var item, key, val, j; for (var i = 0, l = arr.length; i < l; i++) { item = arr[i]; val = item && item.$value || item; j = keys.length; if (j) { while (j--) { key = keys[j]; if (key === '$key' && contains(item.$key, search) || contains(getPath(val, key), search)) { res.push(item); break; } } } else if (contains(item, search)) { res.push(item); } } return res; } /** * Filter filter for arrays * * @param {String} sortKey * @param {String} reverse */ function orderBy(arr, sortKey, reverse) { arr = convertArray(arr); if (!sortKey) { return arr; } var order = reverse && reverse < 0 ? -1 : 1; // sort on a copy to avoid mutating original array return arr.slice().sort(function (a, b) { if (sortKey !== '$key') { if (isObject(a) && '$value' in a) a = a.$value; if (isObject(b) && '$value' in b) b = b.$value; } a = isObject(a) ? getPath(a, sortKey) : a; b = isObject(b) ? getPath(b, sortKey) : b; return a === b ? 0 : a > b ? order : -order; }); } /** * String contain helper * * @param {*} val * @param {String} search */ function contains(val, search) { var i; if (isPlainObject(val)) { var keys = Object.keys(val); i = keys.length; while (i--) { if (contains(val[keys[i]], search)) { return true; } } } else if (isArray(val)) { i = val.length; while (i--) { if (contains(val[i], search)) { return true; } } } else if (val != null) { return val.toString().toLowerCase().indexOf(search) > -1; } } var digitsRE = /(\d{3})(?=\d)/g; // asset collections must be a plain object. var filters = { orderBy: orderBy, filterBy: filterBy, limitBy: limitBy, /** * Stringify value. * * @param {Number} indent */ json: { read: function read(value, indent) { return typeof value === 'string' ? value : JSON.stringify(value, null, Number(indent) || 2); }, write: function write(value) { try { return JSON.parse(value); } catch (e) { return value; } } }, /** * 'abc' => 'Abc' */ capitalize: function capitalize(value) { if (!value && value !== 0) return ''; value = value.toString(); return value.charAt(0).toUpperCase() + value.slice(1); }, /** * 'abc' => 'ABC' */ uppercase: function uppercase(value) { return value || value === 0 ? value.toString().toUpperCase() : ''; }, /** * 'AbC' => 'abc' */ lowercase: function lowercase(value) { return value || value === 0 ? value.toString().toLowerCase() : ''; }, /** * 12345 => $12,345.00 * * @param {String} sign */ currency: function currency(value, _currency) { value = parseFloat(value); if (!isFinite(value) || !value && value !== 0) return ''; _currency = _currency != null ? _currency : '$'; var stringified = Math.abs(value).toFixed(2); var _int = stringified.slice(0, -3); var i = _int.length % 3; var head = i > 0 ? _int.slice(0, i) + (_int.length > 3 ? ',' : '') : ''; var _float = stringified.slice(-3); var sign = value < 0 ? '-' : ''; return sign + _currency + head + _int.slice(i).replace(digitsRE, '$1,') + _float; }, /** * 'item' => 'items' * * @params * an array of strings corresponding to * the single, double, triple ... forms of the word to * be pluralized. When the number to be pluralized * exceeds the length of the args, it will use the last * entry in the array. * * e.g. ['single', 'double', 'triple', 'multiple'] */ pluralize: function pluralize(value) { var args = toArray(arguments, 1); return args.length > 1 ? args[value % 10 - 1] || args[args.length - 1] : args[0] + (value === 1 ? '' : 's'); }, /** * Debounce a handler function. * * @param {Function} handler * @param {Number} delay = 300 * @return {Function} */ debounce: function debounce(handler, delay) { if (!handler) return; if (!delay) { delay = 300; } return _debounce(handler, delay); } }; function installGlobalAPI (Vue) { /** * Vue and every constructor that extends Vue has an * associated options object, which can be accessed during * compilation steps as `this.constructor.options`. * * These can be seen as the default options of every * Vue instance. */ Vue.options = { directives: directives, elementDirectives: elementDirectives, filters: filters, transitions: {}, components: {}, partials: {}, replace: true }; /** * Expose useful internals */ Vue.util = util; Vue.config = config; Vue.set = set; Vue['delete'] = del; Vue.nextTick = nextTick; /** * The following are exposed for advanced usage / plugins */ Vue.compiler = compiler; Vue.FragmentFactory = FragmentFactory; Vue.internalDirectives = internalDirectives; Vue.parsers = { path: path, text: text, template: template, directive: directive, expression: expression }; /** * 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 * * @param {Object} extendOptions */ 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.'); name = null; } } var Sub = function VueComponent(options) { Vue.call(this, 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; } // cache constructor if (isFirstExtend) { extendOptions._Ctor = Sub; } return Sub; }; /** * Plugin system * * @param {Object} plugin */ 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; }; /** * Apply a global mixin by merging it into the default * options. */ Vue.mixin = function (mixin) { Vue.options = mergeOptions(Vue.options, mixin); }; /** * Create asset registration methods with the following * signature: * * @param {String} id * @param {*} definition */ 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' && (commonTagRE.test(id) || reservedTagRE.test(id))) { warn('Do not use built-in or reserved HTML elements as component ' + 'id: ' + id); } } if (type === 'component' && isPlainObject(definition)) { definition.name = id; definition = Vue.extend(definition); } this.options[type + 's'][id] = definition; return definition; } }; }); // expose internal transition API extend(Vue.transition, transition); } installGlobalAPI(Vue); Vue.version = '1.0.19-csp'; // devtools global hook /* istanbul ignore next */ if (config.devtools) { if (devtools) { devtools.emit('init', Vue); } 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'); } } module.exports = Vue;
Lab8/app.js
prpatel/react-workshop-day1
import React from 'react'; import ReactDOM from 'react-dom'; import moment from 'moment'; import Bootstrap from 'react-bootstrap'; import Jumbotron from 'react-bootstrap/lib/Jumbotron'; import Panel from 'react-bootstrap/lib/Panel'; import Input from 'react-bootstrap/lib/Input'; import Label from 'react-bootstrap/lib/Label'; class LunchApp extends React.Component { render() { var now = new Date(); var formattedDate = moment(now).format('MMMM Do YYYY'); return ( <div> <Panel> <h2>Options for lunch for {formattedDate}:</h2> <LunchOptionsPanel lunchData={this.props.lunchChoices}> </LunchOptionsPanel> </Panel> </div> ); } } class LunchOptionsPanel extends React.Component { constructor(props) { super(props); this.state = {selectedLunch: 'Nothing selected'}; this.handleClick = this.handleClick.bind(this); } handleClick(event) { // may need to use innerText for older IE this.setState({ selectedLunch: event.target.textContent }); } render() { let clickHandler = this.handleClick; let lunchOptions = this.props.lunchData.map(function(c,i) { return <h3 key={i} onClick={clickHandler}><Label>{c}</Label></h3>; }); return ( <div> <Panel header="Please select one" bsStyle="info"> {lunchOptions} </Panel> <SelectedLunchPanel selectedLunch={this.state.selectedLunch}></SelectedLunchPanel> </div> ); } } class SelectedLunchPanel extends React.Component { constructor(props) { super(props); this.updateInstructions = this.updateInstructions.bind(this); this.state = { instructions: '' }; } render() { return ( <div> <Panel header="You've picked" bsStyle="warning"> <Label>{this.props.selectedLunch}</Label> <p>Special Instructions: </p> </Panel> </div> ); } } var lunchChoices = ['Chicken', 'Fish', 'Vegetarian']; ReactDOM.render( <LunchApp lunchChoices={lunchChoices}/>, document.getElementById('root') );
src/client/components/kiosk/Setup/KioskSetup.component.js
DBCDK/content-first
import React from 'react'; import T from '../../base/T'; import Button from '../../base/Button'; import Toolbar from '../../base/Toolbar'; import Banner from '../../base/Banner'; import Input from '../../base/Input'; import Text from '../../base/Text'; import Heading from '../../base/Heading'; import Kiosk from '../../base/Kiosk/Kiosk'; import './KioskSetup.css'; export default class KioskSetup extends React.Component { state = {branchKey: null}; render() { return ( <div className="KioskSetup"> <Banner title={T({component: 'kioskSetup', name: 'title'})} className="fixed-width-col-md" /> <Kiosk render={({kiosk, start, loadKiosk}) => { return ( <div className="KioskSetup__container col-centered"> <Input placeholder={T({ component: 'kioskSetup', name: 'placeholderBranchKey' })} onChange={e => this.setState({branchKey: e.target.value})} value={ this.state.branchKey === null ? kiosk.branchKey || '' : this.state.branchKey } data-cy="input-client-id" > <T component="kioskSetup" name="labelBranchKey" /> </Input> <Button className="submit-button" type="quaternary" onClick={() => loadKiosk({branchKey: this.state.branchKey})} data-cy="kiosk-settings-submit" disabled={ !this.state.branchKey || this.state.branchKey === kiosk.branchKey } > <T component="kioskSetup" name="submit" /> </Button> {kiosk.error && this.state.branchKey === kiosk.branchKey && ( <Text className="error" variant="error" align="right" data-cy="kiosk-error-msg" > {kiosk.error} </Text> )} {kiosk.configuration && ( <React.Fragment> {/* <Divider variant="thin" /> */} <Heading className="ready-header" Tag="h1" type="lead"> <T component="kioskSetup" name="readyHeader" /> </Heading> <div className="attributes"> {Object.entries(kiosk.configuration).map(([key, val]) => { return ( <div className="attribute-row" key={`${key}-${val}`}> <Text className="key" variant="weight-semibold"> {key} </Text> <Text className="val">{val}</Text> </div> ); })} </div> <Toolbar> <Button type="secondary" onClick={start} align="left" data-cy="kiosk-start-btn" > <T component="kioskSetup" name="startKiosk" /> </Button> </Toolbar> </React.Fragment> )} </div> ); }} /> </div> ); } }
static/src/components/Footer.js
Termnator/mikebot
// @flow import React from 'react'; import numeral from 'numeral'; import * as StatsActions from '../actions/StatsActions'; import * as ShareActions from '../actions/ShareActions'; import ShareStore from '../stores/ShareStore'; import Constants from '../Constants'; const Footer = React.createClass({ render() { const {count, changeCount, showStatsPanel, statsHasBeenShown} = this.props; let statsBtnClasses = 'crossfade'; if (statsHasBeenShown) { if (showStatsPanel) { statsBtnClasses += ' two'; } else { statsBtnClasses += ' two-reverse'; } } let statsBtn2Classes = 'crossfade'; if (statsHasBeenShown) { if (showStatsPanel) { statsBtn2Classes += ' three'; } else { statsBtn2Classes += ' three-reverse'; } } let toolTip = 'Click for more Stats'; if (showStatsPanel) { toolTip = ''; } return ( <div className="footer"> <div className="airhorn-count"> <div className="stats-toggler" onClick={StatsActions.toggleStatsPanel}> <div className="airhorn-count-content"> <img src={Constants.Image.AIRHORN_COUNTER} /> <div className="count-text"> <div className={`count ${changeCount ? 'count-big' : ''}`}> {numeral(count).format('0,0')} </div> <div className="and-counting">and counting</div> </div> </div> <div className="stats-btn"> <img src={Constants.Image.ICON_CLOSE} className={statsBtn2Classes} onClick={StatsActions.hideStatsPanel} /> <img src={Constants.Image.ICON_ABOUT} className={statsBtnClasses} data-tip={toolTip} /> </div> </div> </div> <div className="main-text"> <span className="normal-text"> Open sourced by the team at Discord. Contribute yourself on&nbsp; </span> <a href={Constants.GITHUB_URL}>GitHub</a> <a href={Constants.GITHUB_URL} className="arrow">&nbsp;➔</a> </div> <div className="social"> <img src={Constants.Image.ICON_TWITTER} onClick={ShareActions.withTwitter} /> <img src={Constants.Image.ICON_FACEBOOK} onClick={ShareActions.withFacebook} /> </div> </div> ); } }); export default Footer;
src/layouts/layout-2-1.js
nazaninreihani/binary-next-gen
import React from 'react'; export default (components, className, onClick) => ( <div className={className + ' vertical'} onClick={onClick}> {components[0]} {components[1]} </div> );
misc/tabledrag.js
boringtao/mythopoet
(function ($) { /** * Drag and drop table rows with field manipulation. * * Using the drupal_add_tabledrag() function, any table with weights or parent * relationships may be made into draggable tables. Columns containing a field * may optionally be hidden, providing a better user experience. * * Created tableDrag instances may be modified with custom behaviors by * overriding the .onDrag, .onDrop, .row.onSwap, and .row.onIndent methods. * See blocks.js for an example of adding additional functionality to tableDrag. */ Drupal.behaviors.tableDrag = { attach: function (context, settings) { for (var base in settings.tableDrag) { $('#' + base, context).once('tabledrag', function () { // Create the new tableDrag instance. Save in the Drupal variable // to allow other scripts access to the object. Drupal.tableDrag[base] = new Drupal.tableDrag(this, settings.tableDrag[base]); }); } } }; /** * Constructor for the tableDrag object. Provides table and field manipulation. * * @param table * DOM object for the table to be made draggable. * @param tableSettings * Settings for the table added via drupal_add_dragtable(). */ Drupal.tableDrag = function (table, tableSettings) { var self = this; // Required object variables. this.table = table; this.tableSettings = tableSettings; this.dragObject = null; // Used to hold information about a current drag operation. this.rowObject = null; // Provides operations for row manipulation. this.oldRowElement = null; // Remember the previous element. this.oldY = 0; // Used to determine up or down direction from last mouse move. this.changed = false; // Whether anything in the entire table has changed. this.maxDepth = 0; // Maximum amount of allowed parenting. this.rtl = $(this.table).css('direction') == 'rtl' ? -1 : 1; // Direction of the table. // Configure the scroll settings. this.scrollSettings = { amount: 4, interval: 50, trigger: 70 }; this.scrollInterval = null; this.scrollY = 0; this.windowHeight = 0; // Check this table's settings to see if there are parent relationships in // this table. For efficiency, large sections of code can be skipped if we // don't need to track horizontal movement and indentations. this.indentEnabled = false; for (var group in tableSettings) { for (var n in tableSettings[group]) { if (tableSettings[group][n].relationship == 'parent') { this.indentEnabled = true; } if (tableSettings[group][n].limit > 0) { this.maxDepth = tableSettings[group][n].limit; } } } if (this.indentEnabled) { this.indentCount = 1; // Total width of indents, set in makeDraggable. // Find the width of indentations to measure mouse movements against. // Because the table doesn't need to start with any indentations, we // manually append 2 indentations in the first draggable row, measure // the offset, then remove. var indent = Drupal.theme('tableDragIndentation'); var testRow = $('<tr/>').addClass('draggable').appendTo(table); var testCell = $('<td/>').appendTo(testRow).prepend(indent).prepend(indent); this.indentAmount = $('.indentation', testCell).get(1).offsetLeft - $('.indentation', testCell).get(0).offsetLeft; testRow.remove(); } // Make each applicable row draggable. // Match immediate children of the parent element to allow nesting. $('> tr.draggable, > tbody > tr.draggable', table).each(function () { self.makeDraggable(this); }); // Add a link before the table for users to show or hide weight columns. $(table).before($('<a href="#" class="tabledrag-toggle-weight"></a>') .attr('title', Drupal.t('Re-order rows by numerical weight instead of dragging.')) .click(function () { if ($.cookie('Drupal.tableDrag.showWeight') == 1) { self.hideColumns(); } else { self.showColumns(); } return false; }) .wrap('<div class="tabledrag-toggle-weight-wrapper"></div>') .parent() ); // Initialize the specified columns (for example, weight or parent columns) // to show or hide according to user preference. This aids accessibility // so that, e.g., screen reader users can choose to enter weight values and // manipulate form elements directly, rather than using drag-and-drop.. self.initColumns(); // Add mouse bindings to the document. The self variable is passed along // as event handlers do not have direct access to the tableDrag object. $(document).bind('mousemove', function (event) { return self.dragRow(event, self); }); $(document).bind('mouseup', function (event) { return self.dropRow(event, self); }); }; /** * Initialize columns containing form elements to be hidden by default, * according to the settings for this tableDrag instance. * * Identify and mark each cell with a CSS class so we can easily toggle * show/hide it. Finally, hide columns if user does not have a * 'Drupal.tableDrag.showWeight' cookie. */ Drupal.tableDrag.prototype.initColumns = function () { for (var group in this.tableSettings) { // Find the first field in this group. for (var d in this.tableSettings[group]) { var field = $('.' + this.tableSettings[group][d].target + ':first', this.table); if (field.length && this.tableSettings[group][d].hidden) { var hidden = this.tableSettings[group][d].hidden; var cell = field.closest('td'); break; } } // Mark the column containing this field so it can be hidden. if (hidden && cell[0]) { // Add 1 to our indexes. The nth-child selector is 1 based, not 0 based. // Match immediate children of the parent element to allow nesting. var columnIndex = $('> td', cell.parent()).index(cell.get(0)) + 1; $('> thead > tr, > tbody > tr, > tr', this.table).each(function () { // Get the columnIndex and adjust for any colspans in this row. var index = columnIndex; var cells = $(this).children(); cells.each(function (n) { if (n < index && this.colSpan && this.colSpan > 1) { index -= this.colSpan - 1; } }); if (index > 0) { cell = cells.filter(':nth-child(' + index + ')'); if (cell[0].colSpan && cell[0].colSpan > 1) { // If this cell has a colspan, mark it so we can reduce the colspan. cell.addClass('tabledrag-has-colspan'); } else { // Mark this cell so we can hide it. cell.addClass('tabledrag-hide'); } } }); } } // Now hide cells and reduce colspans unless cookie indicates previous choice. // Set a cookie if it is not already present. if ($.cookie('Drupal.tableDrag.showWeight') === null) { $.cookie('Drupal.tableDrag.showWeight', 0, { path: Drupal.settings.basePath, // The cookie expires in one year. expires: 365 }); this.hideColumns(); } // Check cookie value and show/hide weight columns accordingly. else { if ($.cookie('Drupal.tableDrag.showWeight') == 1) { this.showColumns(); } else { this.hideColumns(); } } }; /** * Hide the columns containing weight/parent form elements. * Undo showColumns(). */ Drupal.tableDrag.prototype.hideColumns = function () { // Hide weight/parent cells and headers. $('.tabledrag-hide', 'table.tabledrag-processed').css('display', 'none'); // Show TableDrag handles. $('.tabledrag-handle', 'table.tabledrag-processed').css('display', ''); // Reduce the colspan of any effected multi-span columns. $('.tabledrag-has-colspan', 'table.tabledrag-processed').each(function () { this.colSpan = this.colSpan - 1; }); // Change link text. $('.tabledrag-toggle-weight').text(Drupal.t('Show row weights')); // Change cookie. $.cookie('Drupal.tableDrag.showWeight', 0, { path: Drupal.settings.basePath, // The cookie expires in one year. expires: 365 }); // Trigger an event to allow other scripts to react to this display change. $('table.tabledrag-processed').trigger('columnschange', 'hide'); }; /** * Show the columns containing weight/parent form elements * Undo hideColumns(). */ Drupal.tableDrag.prototype.showColumns = function () { // Show weight/parent cells and headers. $('.tabledrag-hide', 'table.tabledrag-processed').css('display', ''); // Hide TableDrag handles. $('.tabledrag-handle', 'table.tabledrag-processed').css('display', 'none'); // Increase the colspan for any columns where it was previously reduced. $('.tabledrag-has-colspan', 'table.tabledrag-processed').each(function () { this.colSpan = this.colSpan + 1; }); // Change link text. $('.tabledrag-toggle-weight').text(Drupal.t('Hide row weights')); // Change cookie. $.cookie('Drupal.tableDrag.showWeight', 1, { path: Drupal.settings.basePath, // The cookie expires in one year. expires: 365 }); // Trigger an event to allow other scripts to react to this display change. $('table.tabledrag-processed').trigger('columnschange', 'show'); }; /** * Find the target used within a particular row and group. */ Drupal.tableDrag.prototype.rowSettings = function (group, row) { var field = $('.' + group, row); for (var delta in this.tableSettings[group]) { var targetClass = this.tableSettings[group][delta].target; if (field.is('.' + targetClass)) { // Return a copy of the row settings. var rowSettings = {}; for (var n in this.tableSettings[group][delta]) { rowSettings[n] = this.tableSettings[group][delta][n]; } return rowSettings; } } }; /** * Take an item and add event handlers to make it become draggable. */ Drupal.tableDrag.prototype.makeDraggable = function (item) { var self = this; // Create the handle. var handle = $('<a href="#" class="tabledrag-handle"><div class="handle">&nbsp;</div></a>').attr('title', Drupal.t('Drag to re-order')); // Insert the handle after indentations (if any). if ($('td:first .indentation:last', item).length) { $('td:first .indentation:last', item).after(handle); // Update the total width of indentation in this entire table. self.indentCount = Math.max($('.indentation', item).length, self.indentCount); } else { $('td:first', item).prepend(handle); } // Add hover action for the handle. handle.hover(function () { self.dragObject == null ? $(this).addClass('tabledrag-handle-hover') : null; }, function () { self.dragObject == null ? $(this).removeClass('tabledrag-handle-hover') : null; }); // Add the mousedown action for the handle. handle.mousedown(function (event) { // Create a new dragObject recording the event information. self.dragObject = {}; self.dragObject.initMouseOffset = self.getMouseOffset(item, event); self.dragObject.initMouseCoords = self.mouseCoords(event); if (self.indentEnabled) { self.dragObject.indentMousePos = self.dragObject.initMouseCoords; } // If there's a lingering row object from the keyboard, remove its focus. if (self.rowObject) { $('a.tabledrag-handle', self.rowObject.element).blur(); } // Create a new rowObject for manipulation of this row. self.rowObject = new self.row(item, 'mouse', self.indentEnabled, self.maxDepth, true); // Save the position of the table. self.table.topY = $(self.table).offset().top; self.table.bottomY = self.table.topY + self.table.offsetHeight; // Add classes to the handle and row. $(this).addClass('tabledrag-handle-hover'); $(item).addClass('drag'); // Set the document to use the move cursor during drag. $('body').addClass('drag'); if (self.oldRowElement) { $(self.oldRowElement).removeClass('drag-previous'); } // Hack for IE6 that flickers uncontrollably if select lists are moved. if (navigator.userAgent.indexOf('MSIE 6.') != -1) { $('select', this.table).css('display', 'none'); } // Hack for Konqueror, prevent the blur handler from firing. // Konqueror always gives links focus, even after returning false on mousedown. self.safeBlur = false; // Call optional placeholder function. self.onDrag(); return false; }); // Prevent the anchor tag from jumping us to the top of the page. handle.click(function () { return false; }); // Similar to the hover event, add a class when the handle is focused. handle.focus(function () { $(this).addClass('tabledrag-handle-hover'); self.safeBlur = true; }); // Remove the handle class on blur and fire the same function as a mouseup. handle.blur(function (event) { $(this).removeClass('tabledrag-handle-hover'); if (self.rowObject && self.safeBlur) { self.dropRow(event, self); } }); // Add arrow-key support to the handle. handle.keydown(function (event) { // If a rowObject doesn't yet exist and this isn't the tab key. if (event.keyCode != 9 && !self.rowObject) { self.rowObject = new self.row(item, 'keyboard', self.indentEnabled, self.maxDepth, true); } var keyChange = false; switch (event.keyCode) { case 37: // Left arrow. case 63234: // Safari left arrow. keyChange = true; self.rowObject.indent(-1 * self.rtl); break; case 38: // Up arrow. case 63232: // Safari up arrow. var previousRow = $(self.rowObject.element).prev('tr').get(0); while (previousRow && $(previousRow).is(':hidden')) { previousRow = $(previousRow).prev('tr').get(0); } if (previousRow) { self.safeBlur = false; // Do not allow the onBlur cleanup. self.rowObject.direction = 'up'; keyChange = true; if ($(item).is('.tabledrag-root')) { // Swap with the previous top-level row. var groupHeight = 0; while (previousRow && $('.indentation', previousRow).length) { previousRow = $(previousRow).prev('tr').get(0); groupHeight += $(previousRow).is(':hidden') ? 0 : previousRow.offsetHeight; } if (previousRow) { self.rowObject.swap('before', previousRow); // No need to check for indentation, 0 is the only valid one. window.scrollBy(0, -groupHeight); } } else if (self.table.tBodies[0].rows[0] != previousRow || $(previousRow).is('.draggable')) { // Swap with the previous row (unless previous row is the first one // and undraggable). self.rowObject.swap('before', previousRow); self.rowObject.interval = null; self.rowObject.indent(0); window.scrollBy(0, -parseInt(item.offsetHeight, 10)); } handle.get(0).focus(); // Regain focus after the DOM manipulation. } break; case 39: // Right arrow. case 63235: // Safari right arrow. keyChange = true; self.rowObject.indent(1 * self.rtl); break; case 40: // Down arrow. case 63233: // Safari down arrow. var nextRow = $(self.rowObject.group).filter(':last').next('tr').get(0); while (nextRow && $(nextRow).is(':hidden')) { nextRow = $(nextRow).next('tr').get(0); } if (nextRow) { self.safeBlur = false; // Do not allow the onBlur cleanup. self.rowObject.direction = 'down'; keyChange = true; if ($(item).is('.tabledrag-root')) { // Swap with the next group (necessarily a top-level one). var groupHeight = 0; var nextGroup = new self.row(nextRow, 'keyboard', self.indentEnabled, self.maxDepth, false); if (nextGroup) { $(nextGroup.group).each(function () { groupHeight += $(this).is(':hidden') ? 0 : this.offsetHeight; }); var nextGroupRow = $(nextGroup.group).filter(':last').get(0); self.rowObject.swap('after', nextGroupRow); // No need to check for indentation, 0 is the only valid one. window.scrollBy(0, parseInt(groupHeight, 10)); } } else { // Swap with the next row. self.rowObject.swap('after', nextRow); self.rowObject.interval = null; self.rowObject.indent(0); window.scrollBy(0, parseInt(item.offsetHeight, 10)); } handle.get(0).focus(); // Regain focus after the DOM manipulation. } break; } if (self.rowObject && self.rowObject.changed == true) { $(item).addClass('drag'); if (self.oldRowElement) { $(self.oldRowElement).removeClass('drag-previous'); } self.oldRowElement = item; self.restripeTable(); self.onDrag(); } // Returning false if we have an arrow key to prevent scrolling. if (keyChange) { return false; } }); // Compatibility addition, return false on keypress to prevent unwanted scrolling. // IE and Safari will suppress scrolling on keydown, but all other browsers // need to return false on keypress. http://www.quirksmode.org/js/keys.html handle.keypress(function (event) { switch (event.keyCode) { case 37: // Left arrow. case 38: // Up arrow. case 39: // Right arrow. case 40: // Down arrow. return false; } }); }; /** * Mousemove event handler, bound to document. */ Drupal.tableDrag.prototype.dragRow = function (event, self) { if (self.dragObject) { self.currentMouseCoords = self.mouseCoords(event); var y = self.currentMouseCoords.y - self.dragObject.initMouseOffset.y; var x = self.currentMouseCoords.x - self.dragObject.initMouseOffset.x; // Check for row swapping and vertical scrolling. if (y != self.oldY) { self.rowObject.direction = y > self.oldY ? 'down' : 'up'; self.oldY = y; // Update the old value. // Check if the window should be scrolled (and how fast). var scrollAmount = self.checkScroll(self.currentMouseCoords.y); // Stop any current scrolling. clearInterval(self.scrollInterval); // Continue scrolling if the mouse has moved in the scroll direction. if (scrollAmount > 0 && self.rowObject.direction == 'down' || scrollAmount < 0 && self.rowObject.direction == 'up') { self.setScroll(scrollAmount); } // If we have a valid target, perform the swap and restripe the table. var currentRow = self.findDropTargetRow(x, y); if (currentRow) { if (self.rowObject.direction == 'down') { self.rowObject.swap('after', currentRow, self); } else { self.rowObject.swap('before', currentRow, self); } self.restripeTable(); } } // Similar to row swapping, handle indentations. if (self.indentEnabled) { var xDiff = self.currentMouseCoords.x - self.dragObject.indentMousePos.x; // Set the number of indentations the mouse has been moved left or right. var indentDiff = Math.round(xDiff / self.indentAmount * self.rtl); // Indent the row with our estimated diff, which may be further // restricted according to the rows around this row. var indentChange = self.rowObject.indent(indentDiff); // Update table and mouse indentations. self.dragObject.indentMousePos.x += self.indentAmount * indentChange * self.rtl; self.indentCount = Math.max(self.indentCount, self.rowObject.indents); } return false; } }; /** * Mouseup event handler, bound to document. * Blur event handler, bound to drag handle for keyboard support. */ Drupal.tableDrag.prototype.dropRow = function (event, self) { // Drop row functionality shared between mouseup and blur events. if (self.rowObject != null) { var droppedRow = self.rowObject.element; // The row is already in the right place so we just release it. if (self.rowObject.changed == true) { // Update the fields in the dropped row. self.updateFields(droppedRow); // If a setting exists for affecting the entire group, update all the // fields in the entire dragged group. for (var group in self.tableSettings) { var rowSettings = self.rowSettings(group, droppedRow); if (rowSettings.relationship == 'group') { for (var n in self.rowObject.children) { self.updateField(self.rowObject.children[n], group); } } } self.rowObject.markChanged(); if (self.changed == false) { $(Drupal.theme('tableDragChangedWarning')).insertBefore(self.table).hide().fadeIn('slow'); self.changed = true; } } if (self.indentEnabled) { self.rowObject.removeIndentClasses(); } if (self.oldRowElement) { $(self.oldRowElement).removeClass('drag-previous'); } $(droppedRow).removeClass('drag').addClass('drag-previous'); self.oldRowElement = droppedRow; self.onDrop(); self.rowObject = null; } // Functionality specific only to mouseup event. if (self.dragObject != null) { $('.tabledrag-handle', droppedRow).removeClass('tabledrag-handle-hover'); self.dragObject = null; $('body').removeClass('drag'); clearInterval(self.scrollInterval); // Hack for IE6 that flickers uncontrollably if select lists are moved. if (navigator.userAgent.indexOf('MSIE 6.') != -1) { $('select', this.table).css('display', 'block'); } } }; /** * Get the mouse coordinates from the event (allowing for browser differences). */ Drupal.tableDrag.prototype.mouseCoords = function (event) { if (event.pageX || event.pageY) { return { x: event.pageX, y: event.pageY }; } return { x: event.clientX + document.body.scrollLeft - document.body.clientLeft, y: event.clientY + document.body.scrollTop - document.body.clientTop }; }; /** * Given a target element and a mouse event, get the mouse offset from that * element. To do this we need the element's position and the mouse position. */ Drupal.tableDrag.prototype.getMouseOffset = function (target, event) { var docPos = $(target).offset(); var mousePos = this.mouseCoords(event); return { x: mousePos.x - docPos.left, y: mousePos.y - docPos.top }; }; /** * Find the row the mouse is currently over. This row is then taken and swapped * with the one being dragged. * * @param x * The x coordinate of the mouse on the page (not the screen). * @param y * The y coordinate of the mouse on the page (not the screen). */ Drupal.tableDrag.prototype.findDropTargetRow = function (x, y) { var rows = $(this.table.tBodies[0].rows).not(':hidden'); for (var n = 0; n < rows.length; n++) { var row = rows[n]; var indentDiff = 0; var rowY = $(row).offset().top; // Because Safari does not report offsetHeight on table rows, but does on // table cells, grab the firstChild of the row and use that instead. // http://jacob.peargrove.com/blog/2006/technical/table-row-offsettop-bug-in-safari. if (row.offsetHeight == 0) { var rowHeight = parseInt(row.firstChild.offsetHeight, 10) / 2; } // Other browsers. else { var rowHeight = parseInt(row.offsetHeight, 10) / 2; } // Because we always insert before, we need to offset the height a bit. if ((y > (rowY - rowHeight)) && (y < (rowY + rowHeight))) { if (this.indentEnabled) { // Check that this row is not a child of the row being dragged. for (var n in this.rowObject.group) { if (this.rowObject.group[n] == row) { return null; } } } else { // Do not allow a row to be swapped with itself. if (row == this.rowObject.element) { return null; } } // Check that swapping with this row is allowed. if (!this.rowObject.isValidSwap(row)) { return null; } // We may have found the row the mouse just passed over, but it doesn't // take into account hidden rows. Skip backwards until we find a draggable // row. while ($(row).is(':hidden') && $(row).prev('tr').is(':hidden')) { row = $(row).prev('tr').get(0); } return row; } } return null; }; /** * After the row is dropped, update the table fields according to the settings * set for this table. * * @param changedRow * DOM object for the row that was just dropped. */ Drupal.tableDrag.prototype.updateFields = function (changedRow) { for (var group in this.tableSettings) { // Each group may have a different setting for relationship, so we find // the source rows for each separately. this.updateField(changedRow, group); } }; /** * After the row is dropped, update a single table field according to specific * settings. * * @param changedRow * DOM object for the row that was just dropped. * @param group * The settings group on which field updates will occur. */ Drupal.tableDrag.prototype.updateField = function (changedRow, group) { var rowSettings = this.rowSettings(group, changedRow); // Set the row as its own target. if (rowSettings.relationship == 'self' || rowSettings.relationship == 'group') { var sourceRow = changedRow; } // Siblings are easy, check previous and next rows. else if (rowSettings.relationship == 'sibling') { var previousRow = $(changedRow).prev('tr').get(0); var nextRow = $(changedRow).next('tr').get(0); var sourceRow = changedRow; if ($(previousRow).is('.draggable') && $('.' + group, previousRow).length) { if (this.indentEnabled) { if ($('.indentations', previousRow).length == $('.indentations', changedRow)) { sourceRow = previousRow; } } else { sourceRow = previousRow; } } else if ($(nextRow).is('.draggable') && $('.' + group, nextRow).length) { if (this.indentEnabled) { if ($('.indentations', nextRow).length == $('.indentations', changedRow)) { sourceRow = nextRow; } } else { sourceRow = nextRow; } } } // Parents, look up the tree until we find a field not in this group. // Go up as many parents as indentations in the changed row. else if (rowSettings.relationship == 'parent') { var previousRow = $(changedRow).prev('tr'); while (previousRow.length && $('.indentation', previousRow).length >= this.rowObject.indents) { previousRow = previousRow.prev('tr'); } // If we found a row. if (previousRow.length) { sourceRow = previousRow[0]; } // Otherwise we went all the way to the left of the table without finding // a parent, meaning this item has been placed at the root level. else { // Use the first row in the table as source, because it's guaranteed to // be at the root level. Find the first item, then compare this row // against it as a sibling. sourceRow = $(this.table).find('tr.draggable:first').get(0); if (sourceRow == this.rowObject.element) { sourceRow = $(this.rowObject.group[this.rowObject.group.length - 1]).next('tr.draggable').get(0); } var useSibling = true; } } // Because we may have moved the row from one category to another, // take a look at our sibling and borrow its sources and targets. this.copyDragClasses(sourceRow, changedRow, group); rowSettings = this.rowSettings(group, changedRow); // In the case that we're looking for a parent, but the row is at the top // of the tree, copy our sibling's values. if (useSibling) { rowSettings.relationship = 'sibling'; rowSettings.source = rowSettings.target; } var targetClass = '.' + rowSettings.target; var targetElement = $(targetClass, changedRow).get(0); // Check if a target element exists in this row. if (targetElement) { var sourceClass = '.' + rowSettings.source; var sourceElement = $(sourceClass, sourceRow).get(0); switch (rowSettings.action) { case 'depth': // Get the depth of the target row. targetElement.value = $('.indentation', $(sourceElement).closest('tr')).length; break; case 'match': // Update the value. targetElement.value = sourceElement.value; break; case 'order': var siblings = this.rowObject.findSiblings(rowSettings); if ($(targetElement).is('select')) { // Get a list of acceptable values. var values = []; $('option', targetElement).each(function () { values.push(this.value); }); var maxVal = values[values.length - 1]; // Populate the values in the siblings. $(targetClass, siblings).each(function () { // If there are more items than possible values, assign the maximum value to the row. if (values.length > 0) { this.value = values.shift(); } else { this.value = maxVal; } }); } else { // Assume a numeric input field. var weight = parseInt($(targetClass, siblings[0]).val(), 10) || 0; $(targetClass, siblings).each(function () { this.value = weight; weight++; }); } break; } } }; /** * Copy all special tableDrag classes from one row's form elements to a * different one, removing any special classes that the destination row * may have had. */ Drupal.tableDrag.prototype.copyDragClasses = function (sourceRow, targetRow, group) { var sourceElement = $('.' + group, sourceRow); var targetElement = $('.' + group, targetRow); if (sourceElement.length && targetElement.length) { targetElement[0].className = sourceElement[0].className; } }; Drupal.tableDrag.prototype.checkScroll = function (cursorY) { var de = document.documentElement; var b = document.body; var windowHeight = this.windowHeight = window.innerHeight || (de.clientHeight && de.clientWidth != 0 ? de.clientHeight : b.offsetHeight); var scrollY = this.scrollY = (document.all ? (!de.scrollTop ? b.scrollTop : de.scrollTop) : (window.pageYOffset ? window.pageYOffset : window.scrollY)); var trigger = this.scrollSettings.trigger; var delta = 0; // Return a scroll speed relative to the edge of the screen. if (cursorY - scrollY > windowHeight - trigger) { delta = trigger / (windowHeight + scrollY - cursorY); delta = (delta > 0 && delta < trigger) ? delta : trigger; return delta * this.scrollSettings.amount; } else if (cursorY - scrollY < trigger) { delta = trigger / (cursorY - scrollY); delta = (delta > 0 && delta < trigger) ? delta : trigger; return -delta * this.scrollSettings.amount; } }; Drupal.tableDrag.prototype.setScroll = function (scrollAmount) { var self = this; this.scrollInterval = setInterval(function () { // Update the scroll values stored in the object. self.checkScroll(self.currentMouseCoords.y); var aboveTable = self.scrollY > self.table.topY; var belowTable = self.scrollY + self.windowHeight < self.table.bottomY; if (scrollAmount > 0 && belowTable || scrollAmount < 0 && aboveTable) { window.scrollBy(0, scrollAmount); } }, this.scrollSettings.interval); }; Drupal.tableDrag.prototype.restripeTable = function () { // :even and :odd are reversed because jQuery counts from 0 and // we count from 1, so we're out of sync. // Match immediate children of the parent element to allow nesting. $('> tbody > tr.draggable:visible, > tr.draggable:visible', this.table) .removeClass('odd even') .filter(':odd').addClass('even').end() .filter(':even').addClass('odd'); }; /** * Stub function. Allows a custom handler when a row begins dragging. */ Drupal.tableDrag.prototype.onDrag = function () { return null; }; /** * Stub function. Allows a custom handler when a row is dropped. */ Drupal.tableDrag.prototype.onDrop = function () { return null; }; /** * Constructor to make a new object to manipulate a table row. * * @param tableRow * The DOM element for the table row we will be manipulating. * @param method * The method in which this row is being moved. Either 'keyboard' or 'mouse'. * @param indentEnabled * Whether the containing table uses indentations. Used for optimizations. * @param maxDepth * The maximum amount of indentations this row may contain. * @param addClasses * Whether we want to add classes to this row to indicate child relationships. */ Drupal.tableDrag.prototype.row = function (tableRow, method, indentEnabled, maxDepth, addClasses) { this.element = tableRow; this.method = method; this.group = [tableRow]; this.groupDepth = $('.indentation', tableRow).length; this.changed = false; this.table = $(tableRow).closest('table').get(0); this.indentEnabled = indentEnabled; this.maxDepth = maxDepth; this.direction = ''; // Direction the row is being moved. if (this.indentEnabled) { this.indents = $('.indentation', tableRow).length; this.children = this.findChildren(addClasses); this.group = $.merge(this.group, this.children); // Find the depth of this entire group. for (var n = 0; n < this.group.length; n++) { this.groupDepth = Math.max($('.indentation', this.group[n]).length, this.groupDepth); } } }; /** * Find all children of rowObject by indentation. * * @param addClasses * Whether we want to add classes to this row to indicate child relationships. */ Drupal.tableDrag.prototype.row.prototype.findChildren = function (addClasses) { var parentIndentation = this.indents; var currentRow = $(this.element, this.table).next('tr.draggable'); var rows = []; var child = 0; while (currentRow.length) { var rowIndentation = $('.indentation', currentRow).length; // A greater indentation indicates this is a child. if (rowIndentation > parentIndentation) { child++; rows.push(currentRow[0]); if (addClasses) { $('.indentation', currentRow).each(function (indentNum) { if (child == 1 && (indentNum == parentIndentation)) { $(this).addClass('tree-child-first'); } if (indentNum == parentIndentation) { $(this).addClass('tree-child'); } else if (indentNum > parentIndentation) { $(this).addClass('tree-child-horizontal'); } }); } } else { break; } currentRow = currentRow.next('tr.draggable'); } if (addClasses && rows.length) { $('.indentation:nth-child(' + (parentIndentation + 1) + ')', rows[rows.length - 1]).addClass('tree-child-last'); } return rows; }; /** * Ensure that two rows are allowed to be swapped. * * @param row * DOM object for the row being considered for swapping. */ Drupal.tableDrag.prototype.row.prototype.isValidSwap = function (row) { if (this.indentEnabled) { var prevRow, nextRow; if (this.direction == 'down') { prevRow = row; nextRow = $(row).next('tr').get(0); } else { prevRow = $(row).prev('tr').get(0); nextRow = row; } this.interval = this.validIndentInterval(prevRow, nextRow); // We have an invalid swap if the valid indentations interval is empty. if (this.interval.min > this.interval.max) { return false; } } // Do not let an un-draggable first row have anything put before it. if (this.table.tBodies[0].rows[0] == row && $(row).is(':not(.draggable)')) { return false; } return true; }; /** * Perform the swap between two rows. * * @param position * Whether the swap will occur 'before' or 'after' the given row. * @param row * DOM element what will be swapped with the row group. */ Drupal.tableDrag.prototype.row.prototype.swap = function (position, row) { Drupal.detachBehaviors(this.group, Drupal.settings, 'move'); $(row)[position](this.group); Drupal.attachBehaviors(this.group, Drupal.settings); this.changed = true; this.onSwap(row); }; /** * Determine the valid indentations interval for the row at a given position * in the table. * * @param prevRow * DOM object for the row before the tested position * (or null for first position in the table). * @param nextRow * DOM object for the row after the tested position * (or null for last position in the table). */ Drupal.tableDrag.prototype.row.prototype.validIndentInterval = function (prevRow, nextRow) { var minIndent, maxIndent; // Minimum indentation: // Do not orphan the next row. minIndent = nextRow ? $('.indentation', nextRow).length : 0; // Maximum indentation: if (!prevRow || $(prevRow).is(':not(.draggable)') || $(this.element).is('.tabledrag-root')) { // Do not indent: // - the first row in the table, // - rows dragged below a non-draggable row, // - 'root' rows. maxIndent = 0; } else { // Do not go deeper than as a child of the previous row. maxIndent = $('.indentation', prevRow).length + ($(prevRow).is('.tabledrag-leaf') ? 0 : 1); // Limit by the maximum allowed depth for the table. if (this.maxDepth) { maxIndent = Math.min(maxIndent, this.maxDepth - (this.groupDepth - this.indents)); } } return { 'min': minIndent, 'max': maxIndent }; }; /** * Indent a row within the legal bounds of the table. * * @param indentDiff * The number of additional indentations proposed for the row (can be * positive or negative). This number will be adjusted to nearest valid * indentation level for the row. */ Drupal.tableDrag.prototype.row.prototype.indent = function (indentDiff) { // Determine the valid indentations interval if not available yet. if (!this.interval) { var prevRow = $(this.element).prev('tr').get(0); var nextRow = $(this.group).filter(':last').next('tr').get(0); this.interval = this.validIndentInterval(prevRow, nextRow); } // Adjust to the nearest valid indentation. var indent = this.indents + indentDiff; indent = Math.max(indent, this.interval.min); indent = Math.min(indent, this.interval.max); indentDiff = indent - this.indents; for (var n = 1; n <= Math.abs(indentDiff); n++) { // Add or remove indentations. if (indentDiff < 0) { $('.indentation:first', this.group).remove(); this.indents--; } else { $('td:first', this.group).prepend(Drupal.theme('tableDragIndentation')); this.indents++; } } if (indentDiff) { // Update indentation for this row. this.changed = true; this.groupDepth += indentDiff; this.onIndent(); } return indentDiff; }; /** * Find all siblings for a row, either according to its subgroup or indentation. * Note that the passed-in row is included in the list of siblings. * * @param settings * The field settings we're using to identify what constitutes a sibling. */ Drupal.tableDrag.prototype.row.prototype.findSiblings = function (rowSettings) { var siblings = []; var directions = ['prev', 'next']; var rowIndentation = this.indents; for (var d = 0; d < directions.length; d++) { var checkRow = $(this.element)[directions[d]](); while (checkRow.length) { // Check that the sibling contains a similar target field. if ($('.' + rowSettings.target, checkRow)) { // Either add immediately if this is a flat table, or check to ensure // that this row has the same level of indentation. if (this.indentEnabled) { var checkRowIndentation = $('.indentation', checkRow).length; } if (!(this.indentEnabled) || (checkRowIndentation == rowIndentation)) { siblings.push(checkRow[0]); } else if (checkRowIndentation < rowIndentation) { // No need to keep looking for siblings when we get to a parent. break; } } else { break; } checkRow = $(checkRow)[directions[d]](); } // Since siblings are added in reverse order for previous, reverse the // completed list of previous siblings. Add the current row and continue. if (directions[d] == 'prev') { siblings.reverse(); siblings.push(this.element); } } return siblings; }; /** * Remove indentation helper classes from the current row group. */ Drupal.tableDrag.prototype.row.prototype.removeIndentClasses = function () { for (var n in this.children) { $('.indentation', this.children[n]) .removeClass('tree-child') .removeClass('tree-child-first') .removeClass('tree-child-last') .removeClass('tree-child-horizontal'); } }; /** * Add an asterisk or other marker to the changed row. */ Drupal.tableDrag.prototype.row.prototype.markChanged = function () { var marker = Drupal.theme('tableDragChangedMarker'); var cell = $('td:first', this.element); if ($('span.tabledrag-changed', cell).length == 0) { cell.append(marker); } }; /** * Stub function. Allows a custom handler when a row is indented. */ Drupal.tableDrag.prototype.row.prototype.onIndent = function () { return null; }; /** * Stub function. Allows a custom handler when a row is swapped. */ Drupal.tableDrag.prototype.row.prototype.onSwap = function (swappedRow) { return null; }; Drupal.theme.prototype.tableDragChangedMarker = function () { return '<span class="warning tabledrag-changed">*</span>'; }; Drupal.theme.prototype.tableDragIndentation = function () { return '<div class="indentation">&nbsp;</div>'; }; Drupal.theme.prototype.tableDragChangedWarning = function () { return '<div class="tabledrag-changed-warning messages warning">' + Drupal.theme('tableDragChangedMarker') + ' ' + Drupal.t('Changes made in this table will not be saved until the form is submitted.') + '</div>'; }; })(jQuery);
src/RadialProgress.js
samidarko/react-radial-progress
import React from 'react'; function clamp (n, min, max) { return Math.max(min, Math.min(max, n)); } export class RadialProgress extends React.Component { constructor() { super(); this.initialize = this.initialize.bind(this); this.generatePath = this.generatePath.bind(this); this.setInterval = this.setInterval.bind(this); this.state = {value: 0}; } setInterval() { clearInterval(this.interval); this.interval = setInterval(() => { if (this.state.value < this.props.value) { this.setState({value: this.state.value + this.props.progressRate}); } else { clearInterval(this.interval); } }, 1000/this.props.fps); } initialize() { if (this.props.animated) { this.setInterval(); } else { this.setState({value: this.props.value}); } } componentDidMount() { this.initialize(); } componentWillUnmount() { if (this.props.animated) clearInterval(this.interval); } componentWillReceiveProps() { this.setState({value: 0}, this.initialize); } generatePath(degrees) { const radius = this.props.radius; const radians = (degrees * Math.PI / 180); var x = Math.sin(radians) * radius; var y = Math.cos(radians) * -radius; const halfEdgeSize = this.props.edgeSize/2; x += halfEdgeSize; y += halfEdgeSize; const largeArcSweepFlag = degrees > 180 ? 1 : 0; const startX = halfEdgeSize; const startY = halfEdgeSize - radius; return `M${startX},${startY} A${radius},${radius} 0 ${largeArcSweepFlag} 1 ${x},${y} `; } render() { const center = this.props.edgeSize / 2; const radius = this.props.radius; let degrees, text = ''; if (this.props.unit === 'percent') { let percent = clamp(this.state.value, 0, 100); degrees = percent / 100 * 360; degrees = clamp(degrees, 0, 359.9); text = this.props.formatText(percent) } else { degrees = this.state.value; degrees = clamp(degrees, 0, 359.9); text = this.props.formatText(degrees) } const pathDescription = this.generatePath(degrees); return ( <svg height={this.props.edgeSize} width={this.props.edgeSize}> <circle cx={center} cy={center} r={radius} stroke={this.props.circleStroke} strokeWidth={this.props.circleStrokeWidth} fill={this.props.circleFill}/> <path d={pathDescription} fill="transparent" stroke={this.props.progressStroke} strokeWidth={this.props.circleStrokeWidth}/> { this.props.displayText && <text x={center} y={center} textAnchor="middle">{text}</text> } </svg> ); } } RadialProgress.defaultProps = { edgeSize: 100, radius: 45, circleStrokeWidth: 4, circleStroke: '#D8D8D8', circleFill: 'transparent', progressStroke: 'black', unit: 'degrees', displayText: true, formatText: (value) => value, animated: true, fps: 60, progressRate: 1 }; RadialProgress.propTypes = { edgeSize: React.PropTypes.number.isRequired, radius: React.PropTypes.number.isRequired, circleStrokeWidth: React.PropTypes.number.isRequired, circleStroke: React.PropTypes.string.isRequired, circleFill: React.PropTypes.string.isRequired, progressStroke: React.PropTypes.string.isRequired, value: React.PropTypes.number.isRequired, unit: React.PropTypes.oneOf(['degrees', 'percent']).isRequired, displayText: React.PropTypes.bool.isRequired, formatText: React.PropTypes.func, animated: React.PropTypes.bool.isRequired, fps: React.PropTypes.number.isRequired, progressRate: React.PropTypes.number.isRequired }; export default RadialProgress;
ajax/libs/react-router/0.10.1/react-router.min.js
NameFILIP/cdnjs
!function(e){if("object"==typeof exports&&"undefined"!=typeof module)module.exports=e();else if("function"==typeof define&&define.amd)define([],e);else{var f;"undefined"!=typeof window?f=window:"undefined"!=typeof global?f=global:"undefined"!=typeof self&&(f=self),f.ReactRouter=e()}}(function(){var define;return function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a="function"==typeof require&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);throw new Error("Cannot find module '"+o+"'")}var f=n[o]={exports:{}};t[o][0].call(f.exports,function(e){var n=t[o][1][e];return s(n?n:e)},f,f.exports,e,t,n,r)}return n[o].exports}for(var i="function"==typeof require&&require,o=0;o<r.length;o++)s(r[o]);return s}({1:[function(_dereq_,module){var LocationActions={PUSH:"push",REPLACE:"replace",POP:"pop"};module.exports=LocationActions},{}],2:[function(_dereq_,module){var LocationActions=_dereq_("../actions/LocationActions"),ImitateBrowserBehavior={updateScrollPosition:function(position,actionType){switch(actionType){case LocationActions.PUSH:case LocationActions.REPLACE:window.scrollTo(0,0);break;case LocationActions.POP:position?window.scrollTo(position.x,position.y):window.scrollTo(0,0)}}};module.exports=ImitateBrowserBehavior},{"../actions/LocationActions":1}],3:[function(_dereq_,module){var ScrollToTopBehavior={updateScrollPosition:function(){window.scrollTo(0,0)}};module.exports=ScrollToTopBehavior},{}],4:[function(_dereq_,module){function DefaultRoute(props){return Route(merge(props,{path:null,isDefault:!0}))}var merge=_dereq_("react/lib/merge"),Route=_dereq_("./Route");module.exports=DefaultRoute},{"./Route":8,"react/lib/merge":75}],5:[function(_dereq_,module){function isLeftClickEvent(event){return 0===event.button}function isModifiedEvent(event){return!!(event.metaKey||event.altKey||event.ctrlKey||event.shiftKey)}var React="undefined"!=typeof window?window.React:"undefined"!=typeof global?global.React:null,classSet=_dereq_("react/lib/cx"),merge=_dereq_("react/lib/merge"),ActiveState=_dereq_("../mixins/ActiveState"),Navigation=_dereq_("../mixins/Navigation"),Link=React.createClass({displayName:"Link",mixins:[ActiveState,Navigation],propTypes:{activeClassName:React.PropTypes.string.isRequired,to:React.PropTypes.string.isRequired,params:React.PropTypes.object,query:React.PropTypes.object,onClick:React.PropTypes.func},getDefaultProps:function(){return{activeClassName:"active"}},handleClick:function(event){var clickResult,allowTransition=!0;this.props.onClick&&(clickResult=this.props.onClick(event)),!isModifiedEvent(event)&&isLeftClickEvent(event)&&((clickResult===!1||event.defaultPrevented===!0)&&(allowTransition=!1),event.preventDefault(),allowTransition&&this.transitionTo(this.props.to,this.props.params,this.props.query))},getHref:function(){return this.makeHref(this.props.to,this.props.params,this.props.query)},getClassName:function(){var classNames={};return this.props.className&&(classNames[this.props.className]=!0),this.isActive(this.props.to,this.props.params,this.props.query)&&(classNames[this.props.activeClassName]=!0),classSet(classNames)},render:function(){var props=merge(this.props,{href:this.getHref(),className:this.getClassName(),onClick:this.handleClick});return React.DOM.a(props,this.props.children)}});module.exports=Link},{"../mixins/ActiveState":15,"../mixins/Navigation":18,"react/lib/cx":65,"react/lib/merge":75}],6:[function(_dereq_,module){function NotFoundRoute(props){return Route(merge(props,{path:null,catchAll:!0}))}var merge=_dereq_("react/lib/merge"),Route=_dereq_("./Route");module.exports=NotFoundRoute},{"./Route":8,"react/lib/merge":75}],7:[function(_dereq_,module){function createRedirectHandler(to,_params,_query){return React.createClass({statics:{willTransitionTo:function(transition,params,query){transition.redirect(to,_params||params,_query||query)}},render:function(){return null}})}function Redirect(props){return Route({name:props.name,path:props.from||props.path||"*",handler:createRedirectHandler(props.to,props.params,props.query)})}var React="undefined"!=typeof window?window.React:"undefined"!=typeof global?global.React:null,Route=_dereq_("./Route");module.exports=Redirect},{"./Route":8}],8:[function(_dereq_,module){var React="undefined"!=typeof window?window.React:"undefined"!=typeof global?global.React:null,withoutProperties=_dereq_("../utils/withoutProperties"),RESERVED_PROPS={handler:!0,path:!0,defaultRoute:!0,notFoundRoute:!0,paramNames:!0,children:!0},Route=React.createClass({displayName:"Route",statics:{getUnreservedProps:function(props){return withoutProperties(props,RESERVED_PROPS)}},propTypes:{handler:React.PropTypes.any.isRequired,path:React.PropTypes.string,name:React.PropTypes.string,ignoreScrollBehavior:React.PropTypes.bool},render:function(){throw new Error("The <Route> component should not be rendered directly. You may be missing a <Routes> wrapper around your list of routes.")}});module.exports=Route},{"../utils/withoutProperties":30}],9:[function(_dereq_,module){function makeMatch(route,params){return{route:route,params:params}}function getRootMatch(matches){return matches[matches.length-1]}function findMatches(path,routes,defaultRoute,notFoundRoute){for(var route,params,matches=null,i=0,len=routes.length;len>i;++i){if(route=routes[i],matches=findMatches(path,route.props.children,route.props.defaultRoute,route.props.notFoundRoute),null!=matches){var rootParams=getRootMatch(matches).params;return params=route.props.paramNames.reduce(function(params,paramName){return params[paramName]=rootParams[paramName],params},{}),matches.unshift(makeMatch(route,params)),matches}if(params=Path.extractParams(route.props.path,path))return[makeMatch(route,params)]}return defaultRoute&&(params=Path.extractParams(defaultRoute.props.path,path))?[makeMatch(defaultRoute,params)]:notFoundRoute&&(params=Path.extractParams(notFoundRoute.props.path,path))?[makeMatch(notFoundRoute,params)]:matches}function hasMatch(matches,match){return matches.some(function(m){if(m.route!==match.route)return!1;for(var property in m.params)if(m.params[property]!==match.params[property])return!1;return!0})}function runTransitionFromHooks(matches,transition,callback){var hooks=reversedArray(matches).map(function(match){return function(){var handler=match.route.props.handler;if(!transition.isAborted&&handler.willTransitionFrom)return handler.willTransitionFrom(transition,match.component);var promise=transition.promise;return delete transition.promise,promise}});runHooks(hooks,callback)}function runTransitionToHooks(matches,transition,query,callback){var hooks=matches.map(function(match){return function(){var handler=match.route.props.handler;!transition.isAborted&&handler.willTransitionTo&&handler.willTransitionTo(transition,match.params,query);var promise=transition.promise;return delete transition.promise,promise}});runHooks(hooks,callback)}function runHooks(hooks,callback){try{var promise=hooks.reduce(function(promise,hook){return promise?promise.then(hook):hook()},null)}catch(error){return callback(error)}promise?promise.then(function(){setTimeout(callback)},function(error){setTimeout(function(){callback(error)})}):callback()}function updateMatchComponents(matches,refs){for(var match,i=0,len=matches.length;len>i&&(match=matches[i],match.component=refs.__activeRoute__,null!=match.component);++i)refs=match.component.refs}function shouldUpdateScroll(currentMatches,previousMatches){var commonMatches=currentMatches.filter(function(match){return-1!==previousMatches.indexOf(match)});return!commonMatches.some(function(match){return match.route.props.ignoreScrollBehavior})}function returnNull(){return null}function routeIsActive(activeRoutes,routeName){return activeRoutes.some(function(route){return route.props.name===routeName})}function paramsAreActive(activeParams,params){for(var property in params)if(String(activeParams[property])!==String(params[property]))return!1;return!0}function queryIsActive(activeQuery,query){for(var property in query)if(String(activeQuery[property])!==String(query[property]))return!1;return!0}function defaultTransitionErrorHandler(error){throw error}var React="undefined"!=typeof window?window.React:"undefined"!=typeof global?global.React:null,warning=_dereq_("react/lib/warning"),invariant=_dereq_("react/lib/invariant"),copyProperties=_dereq_("react/lib/copyProperties"),HashLocation=_dereq_("../locations/HashLocation"),ActiveContext=_dereq_("../mixins/ActiveContext"),LocationContext=_dereq_("../mixins/LocationContext"),RouteContext=_dereq_("../mixins/RouteContext"),ScrollContext=_dereq_("../mixins/ScrollContext"),reversedArray=_dereq_("../utils/reversedArray"),Transition=_dereq_("../utils/Transition"),Redirect=_dereq_("../utils/Redirect"),Path=_dereq_("../utils/Path"),Route=_dereq_("./Route"),Routes=React.createClass({displayName:"Routes",mixins:[RouteContext,ActiveContext,LocationContext,ScrollContext],propTypes:{initialPath:React.PropTypes.string,initialMatches:React.PropTypes.array,onChange:React.PropTypes.func,onError:React.PropTypes.func.isRequired},getDefaultProps:function(){return{initialPath:null,initialMatches:[],onError:defaultTransitionErrorHandler}},getInitialState:function(){return{path:this.props.initialPath,matches:this.props.initialMatches}},componentDidMount:function(){warning(null==this._owner,"<Routes> should be rendered directly using React.renderComponent, not inside some other component's render method"),this._handleStateChange()},componentDidUpdate:function(){this._handleStateChange()},match:function(path){var routes=this.getRoutes();return findMatches(Path.withoutQuery(path),routes,this.props.defaultRoute,this.props.notFoundRoute)},updateLocation:function(path,actionType){this.state.path!==path&&(this.state.path&&this.recordScroll(this.state.path),this.dispatch(path,function(error,abortReason,nextState){error?this.props.onError.call(this,error):abortReason instanceof Redirect?this.replaceWith(abortReason.to,abortReason.params,abortReason.query):abortReason?this.goBack():(this._nextStateChangeHandler=this._finishTransitionTo.bind(this,path,actionType,this.state.matches),this.setState(nextState))}))},_handleStateChange:function(){this._nextStateChangeHandler&&(this._nextStateChangeHandler(),delete this._nextStateChangeHandler)},_finishTransitionTo:function(path,actionType,previousMatches){var currentMatches=this.state.matches;updateMatchComponents(currentMatches,this.refs),shouldUpdateScroll(currentMatches,previousMatches)&&this.updateScroll(path,actionType),this.props.onChange&&this.props.onChange.call(this)},dispatch:function(path,callback){var transition=new Transition(this,path),currentMatches=this.state?this.state.matches:[],nextMatches=this.match(path)||[];warning(nextMatches.length,'No route matches path "%s". Make sure you have <Route path="%s"> somewhere in your <Routes>',path,path);var fromMatches,toMatches;currentMatches.length?(fromMatches=currentMatches.filter(function(match){return!hasMatch(nextMatches,match)}),toMatches=nextMatches.filter(function(match){return!hasMatch(currentMatches,match)})):(fromMatches=[],toMatches=nextMatches);var callbackScope=this,query=Path.extractQuery(path)||{};runTransitionFromHooks(fromMatches,transition,function(error){return error||transition.isAborted?callback.call(callbackScope,error,transition.abortReason):void runTransitionToHooks(toMatches,transition,query,function(error){if(error||transition.isAborted)return callback.call(callbackScope,error,transition.abortReason);var matches=currentMatches.slice(0,currentMatches.length-fromMatches.length).concat(toMatches),rootMatch=getRootMatch(matches),params=rootMatch&&rootMatch.params||{},routes=matches.map(function(match){return match.route});callback.call(callbackScope,null,null,{path:path,matches:matches,activeRoutes:routes,activeParams:params,activeQuery:query})})})},getHandlerProps:function(){var matches=this.state.matches,query=this.state.activeQuery,handler=returnNull,props={ref:null,params:null,query:null,activeRouteHandler:handler,key:null};return reversedArray(matches).forEach(function(match){var route=match.route;props=Route.getUnreservedProps(route.props),props.ref="__activeRoute__",props.params=match.params,props.query=query,props.activeRouteHandler=handler,route.props.addHandlerKey&&(props.key=Path.injectParams(route.props.path,match.params)),handler=function(props,addedProps){if(arguments.length>2&&"undefined"!=typeof arguments[2])throw new Error("Passing children to a route handler is not supported");return route.props.handler(copyProperties(props,addedProps))}.bind(this,props)}),props},getActiveComponent:function(){return this.refs.__activeRoute__},getCurrentPath:function(){return this.state.path},makePath:function(to,params,query){var path;if(Path.isAbsolute(to))path=Path.normalize(to);else{var namedRoutes=this.getNamedRoutes(),route=namedRoutes[to];invariant(route,'Unable to find a route named "%s". Make sure you have <Route name="%s"> somewhere in your <Routes>',to,to),path=route.props.path}return Path.withQuery(Path.injectParams(path,params),query)},makeHref:function(to,params,query){var path=this.makePath(to,params,query);return this.getLocation()===HashLocation?"#"+path:path},transitionTo:function(to,params,query){var location=this.getLocation();invariant(location,"You cannot use transitionTo without a location"),location.push(this.makePath(to,params,query))},replaceWith:function(to,params,query){var location=this.getLocation();invariant(location,"You cannot use replaceWith without a location"),location.replace(this.makePath(to,params,query))},goBack:function(){var location=this.getLocation();invariant(location,"You cannot use goBack without a location"),location.pop()},isActive:function(to,params,query){return Path.isAbsolute(to)?to===this.getCurrentPath():routeIsActive(this.getActiveRoutes(),to)&&paramsAreActive(this.getActiveParams(),params)&&(null==query||queryIsActive(this.getActiveQuery(),query))},render:function(){var match=this.state.matches[0];return null==match?null:match.route.props.handler(this.getHandlerProps())},childContextTypes:{currentPath:React.PropTypes.string,makePath:React.PropTypes.func.isRequired,makeHref:React.PropTypes.func.isRequired,transitionTo:React.PropTypes.func.isRequired,replaceWith:React.PropTypes.func.isRequired,goBack:React.PropTypes.func.isRequired,isActive:React.PropTypes.func.isRequired},getChildContext:function(){return{currentPath:this.getCurrentPath(),makePath:this.makePath,makeHref:this.makeHref,transitionTo:this.transitionTo,replaceWith:this.replaceWith,goBack:this.goBack,isActive:this.isActive}}});module.exports=Routes},{"../locations/HashLocation":11,"../mixins/ActiveContext":14,"../mixins/LocationContext":17,"../mixins/RouteContext":19,"../mixins/ScrollContext":20,"../utils/Path":22,"../utils/Redirect":24,"../utils/Transition":26,"../utils/reversedArray":28,"./Route":8,"react/lib/copyProperties":64,"react/lib/invariant":70,"react/lib/warning":77}],10:[function(_dereq_,module,exports){exports.DefaultRoute=_dereq_("./components/DefaultRoute"),exports.Link=_dereq_("./components/Link"),exports.NotFoundRoute=_dereq_("./components/NotFoundRoute"),exports.Redirect=_dereq_("./components/Redirect"),exports.Route=_dereq_("./components/Route"),exports.Routes=_dereq_("./components/Routes"),exports.ActiveState=_dereq_("./mixins/ActiveState"),exports.CurrentPath=_dereq_("./mixins/CurrentPath"),exports.Navigation=_dereq_("./mixins/Navigation"),exports.renderRoutesToString=_dereq_("./utils/ServerRendering").renderRoutesToString,exports.renderRoutesToStaticMarkup=_dereq_("./utils/ServerRendering").renderRoutesToStaticMarkup},{"./components/DefaultRoute":4,"./components/Link":5,"./components/NotFoundRoute":6,"./components/Redirect":7,"./components/Route":8,"./components/Routes":9,"./mixins/ActiveState":15,"./mixins/CurrentPath":16,"./mixins/Navigation":18,"./utils/ServerRendering":25}],11:[function(_dereq_,module){function getHashPath(){return window.location.hash.substr(1)}function ensureSlash(){var path=getHashPath();return"/"===path.charAt(0)?!0:(HashLocation.replace("/"+path),!1)}function onHashChange(){if(ensureSlash()){{getHashPath()}_onChange({type:_actionType||LocationActions.POP,path:getHashPath()}),_actionType=null}}var _actionType,_onChange,LocationActions=_dereq_("../actions/LocationActions"),getWindowPath=_dereq_("../utils/getWindowPath"),HashLocation={setup:function(onChange){_onChange=onChange,ensureSlash(),window.addEventListener?window.addEventListener("hashchange",onHashChange,!1):window.attachEvent("onhashchange",onHashChange)},teardown:function(){window.removeEventListener?window.removeEventListener("hashchange",onHashChange,!1):window.detachEvent("onhashchange",onHashChange)},push:function(path){_actionType=LocationActions.PUSH,window.location.hash=path},replace:function(path){_actionType=LocationActions.REPLACE,window.location.replace(getWindowPath()+"#"+path)},pop:function(){_actionType=LocationActions.POP,window.history.back()},getCurrentPath:getHashPath,toString:function(){return"<HashLocation>"}};module.exports=HashLocation},{"../actions/LocationActions":1,"../utils/getWindowPath":27}],12:[function(_dereq_,module){function onPopState(){_onChange({type:LocationActions.POP,path:getWindowPath()})}var _onChange,LocationActions=_dereq_("../actions/LocationActions"),getWindowPath=_dereq_("../utils/getWindowPath"),HistoryLocation={setup:function(onChange){_onChange=onChange,window.addEventListener?window.addEventListener("popstate",onPopState,!1):window.attachEvent("popstate",onPopState)},teardown:function(){window.removeEventListener?window.removeEventListener("popstate",onPopState,!1):window.detachEvent("popstate",onPopState)},push:function(path){window.history.pushState({path:path},"",path),_onChange({type:LocationActions.PUSH,path:getWindowPath()})},replace:function(path){window.history.replaceState({path:path},"",path),_onChange({type:LocationActions.REPLACE,path:getWindowPath()})},pop:function(){window.history.back()},getCurrentPath:getWindowPath,toString:function(){return"<HistoryLocation>"}};module.exports=HistoryLocation},{"../actions/LocationActions":1,"../utils/getWindowPath":27}],13:[function(_dereq_,module){var getWindowPath=_dereq_("../utils/getWindowPath"),RefreshLocation={push:function(path){window.location=path},replace:function(path){window.location.replace(path)},pop:function(){window.history.back()},getCurrentPath:getWindowPath,toString:function(){return"<RefreshLocation>"}};module.exports=RefreshLocation},{"../utils/getWindowPath":27}],14:[function(_dereq_,module){var React="undefined"!=typeof window?window.React:"undefined"!=typeof global?global.React:null,copyProperties=_dereq_("react/lib/copyProperties"),ActiveContext={propTypes:{initialActiveRoutes:React.PropTypes.array.isRequired,initialActiveParams:React.PropTypes.object.isRequired,initialActiveQuery:React.PropTypes.object.isRequired},getDefaultProps:function(){return{initialActiveRoutes:[],initialActiveParams:{},initialActiveQuery:{}}},getInitialState:function(){return{activeRoutes:this.props.initialActiveRoutes,activeParams:this.props.initialActiveParams,activeQuery:this.props.initialActiveQuery}},getActiveRoutes:function(){return this.state.activeRoutes.slice(0)},getActiveParams:function(){return copyProperties({},this.state.activeParams)},getActiveQuery:function(){return copyProperties({},this.state.activeQuery)},childContextTypes:{activeRoutes:React.PropTypes.array.isRequired,activeParams:React.PropTypes.object.isRequired,activeQuery:React.PropTypes.object.isRequired},getChildContext:function(){return{activeRoutes:this.getActiveRoutes(),activeParams:this.getActiveParams(),activeQuery:this.getActiveQuery()}}};module.exports=ActiveContext},{"react/lib/copyProperties":64}],15:[function(_dereq_,module){var React="undefined"!=typeof window?window.React:"undefined"!=typeof global?global.React:null,ActiveState={contextTypes:{activeRoutes:React.PropTypes.array.isRequired,activeParams:React.PropTypes.object.isRequired,activeQuery:React.PropTypes.object.isRequired,isActive:React.PropTypes.func.isRequired},getActiveRoutes:function(){return this.context.activeRoutes},getActiveParams:function(){return this.context.activeParams},getActiveQuery:function(){return this.context.activeQuery},isActive:function(to,params,query){return this.context.isActive(to,params,query)}};module.exports=ActiveState},{}],16:[function(_dereq_,module){var React="undefined"!=typeof window?window.React:"undefined"!=typeof global?global.React:null,CurrentPath={contextTypes:{currentPath:React.PropTypes.string.isRequired},getCurrentPath:function(){return this.context.currentPath}};module.exports=CurrentPath},{}],17:[function(_dereq_,module){var React="undefined"!=typeof window?window.React:"undefined"!=typeof global?global.React:null,invariant=_dereq_("react/lib/invariant"),canUseDOM=_dereq_("react/lib/ExecutionEnvironment").canUseDOM,HashLocation=_dereq_("../locations/HashLocation"),HistoryLocation=_dereq_("../locations/HistoryLocation"),RefreshLocation=_dereq_("../locations/RefreshLocation"),PathStore=_dereq_("../stores/PathStore"),supportsHistory=_dereq_("../utils/supportsHistory"),NAMED_LOCATIONS={none:null,hash:HashLocation,history:HistoryLocation,refresh:RefreshLocation},LocationContext={propTypes:{location:function(props,propName,componentName){var location=props[propName];return"string"!=typeof location||location in NAMED_LOCATIONS?void 0:new Error('Unknown location "'+location+'", see '+componentName)}},getDefaultProps:function(){return{location:canUseDOM?HashLocation:null}},componentWillMount:function(){var location=this.getLocation();invariant(null==location||canUseDOM,"Cannot use location without a DOM"),location&&(PathStore.setup(location),PathStore.addChangeListener(this.handlePathChange),this.updateLocation&&this.updateLocation(PathStore.getCurrentPath(),PathStore.getCurrentActionType()))},componentWillUnmount:function(){this.getLocation()&&PathStore.removeChangeListener(this.handlePathChange)},handlePathChange:function(){this.updateLocation&&this.updateLocation(PathStore.getCurrentPath(),PathStore.getCurrentActionType())},getLocation:function(){if(null==this._location){var location=this.props.location;"string"==typeof location&&(location=NAMED_LOCATIONS[location]),location!==HistoryLocation||supportsHistory()||(location=RefreshLocation),this._location=location}return this._location},childContextTypes:{location:React.PropTypes.object},getChildContext:function(){return{location:this.getLocation()}}};module.exports=LocationContext},{"../locations/HashLocation":11,"../locations/HistoryLocation":12,"../locations/RefreshLocation":13,"../stores/PathStore":21,"../utils/supportsHistory":29,"react/lib/ExecutionEnvironment":42,"react/lib/invariant":70}],18:[function(_dereq_,module){var React="undefined"!=typeof window?window.React:"undefined"!=typeof global?global.React:null,Navigation={contextTypes:{makePath:React.PropTypes.func.isRequired,makeHref:React.PropTypes.func.isRequired,transitionTo:React.PropTypes.func.isRequired,replaceWith:React.PropTypes.func.isRequired,goBack:React.PropTypes.func.isRequired},makePath:function(to,params,query){return this.context.makePath(to,params,query)},makeHref:function(to,params,query){return this.context.makeHref(to,params,query)},transitionTo:function(to,params,query){this.context.transitionTo(to,params,query)},replaceWith:function(to,params,query){this.context.replaceWith(to,params,query)},goBack:function(){this.context.goBack()}};module.exports=Navigation},{}],19:[function(_dereq_,module){function processRoute(route,container,namedRoutes){var props=route.props,parentPath=container&&container.props.path||"/";if(!props.path&&!props.name||props.isDefault||props.catchAll)props.path=parentPath,props.catchAll&&(props.path+="*");else{var path=props.path||props.name;Path.isAbsolute(path)||(path=Path.join(parentPath,path)),props.path=Path.normalize(path)}if(props.paramNames=Path.extractParamNames(props.path),container&&Array.isArray(container.props.paramNames)&&container.props.paramNames.forEach(function(paramName){invariant(-1!==props.paramNames.indexOf(paramName),'The nested route path "%s" is missing the "%s" parameter of its parent path "%s"',props.path,paramName,container.props.path)}),props.name){var existingRoute=namedRoutes[props.name];invariant(!existingRoute||route===existingRoute,'You cannot use the name "%s" for more than one route',props.name),namedRoutes[props.name]=route}return props.catchAll?(invariant(container,"<NotFoundRoute> must have a parent <Route>"),invariant(null==container.props.notFoundRoute,"You may not have more than one <NotFoundRoute> per <Route>"),container.props.notFoundRoute=route,null):props.isDefault?(invariant(container,"<DefaultRoute> must have a parent <Route>"),invariant(null==container.props.defaultRoute,"You may not have more than one <DefaultRoute> per <Route>"),container.props.defaultRoute=route,null):(props.children=processRoutes(props.children,route,namedRoutes),route)}function processRoutes(children,container,namedRoutes){var routes=[];return React.Children.forEach(children,function(child){(child=processRoute(child,container,namedRoutes))&&routes.push(child)}),routes}var React="undefined"!=typeof window?window.React:"undefined"!=typeof global?global.React:null,invariant=_dereq_("react/lib/invariant"),Path=_dereq_("../utils/Path"),RouteContext={_processRoutes:function(){this._namedRoutes={},this._routes=processRoutes(this.props.children,this,this._namedRoutes)},getRoutes:function(){return null==this._routes&&this._processRoutes(),this._routes},getNamedRoutes:function(){return null==this._namedRoutes&&this._processRoutes(),this._namedRoutes},getRouteByName:function(routeName){var namedRoutes=this.getNamedRoutes();return namedRoutes[routeName]||null},childContextTypes:{routes:React.PropTypes.array.isRequired,namedRoutes:React.PropTypes.object.isRequired},getChildContext:function(){return{routes:this.getRoutes(),namedRoutes:this.getNamedRoutes()}}};module.exports=RouteContext},{"../utils/Path":22,"react/lib/invariant":70}],20:[function(_dereq_,module){function getWindowScrollPosition(){return invariant(canUseDOM,"Cannot get current scroll position without a DOM"),{x:window.scrollX,y:window.scrollY}}var React="undefined"!=typeof window?window.React:"undefined"!=typeof global?global.React:null,invariant=_dereq_("react/lib/invariant"),canUseDOM=_dereq_("react/lib/ExecutionEnvironment").canUseDOM,ImitateBrowserBehavior=_dereq_("../behaviors/ImitateBrowserBehavior"),ScrollToTopBehavior=_dereq_("../behaviors/ScrollToTopBehavior"),NAMED_SCROLL_BEHAVIORS={none:null,browser:ImitateBrowserBehavior,imitateBrowser:ImitateBrowserBehavior,scrollToTop:ScrollToTopBehavior},ScrollContext={propTypes:{scrollBehavior:function(props,propName,componentName){var behavior=props[propName];return"string"!=typeof behavior||behavior in NAMED_SCROLL_BEHAVIORS?void 0:new Error('Unknown scroll behavior "'+behavior+'", see '+componentName)}},getDefaultProps:function(){return{scrollBehavior:canUseDOM?ImitateBrowserBehavior:null}},componentWillMount:function(){invariant(null==this.getScrollBehavior()||canUseDOM,"Cannot use scroll behavior without a DOM")},recordScroll:function(path){var positions=this.getScrollPositions();positions[path]=getWindowScrollPosition()},updateScroll:function(path,actionType){var behavior=this.getScrollBehavior(),position=this.getScrollPosition(path)||null;behavior&&behavior.updateScrollPosition(position,actionType)},getScrollBehavior:function(){if(null==this._scrollBehavior){var behavior=this.props.scrollBehavior;"string"==typeof behavior&&(behavior=NAMED_SCROLL_BEHAVIORS[behavior]),this._scrollBehavior=behavior}return this._scrollBehavior},getScrollPositions:function(){return null==this._scrollPositions&&(this._scrollPositions={}),this._scrollPositions},getScrollPosition:function(path){var positions=this.getScrollPositions();return positions[path]},childContextTypes:{scrollBehavior:React.PropTypes.object},getChildContext:function(){return{scrollBehavior:this.getScrollBehavior()}}};module.exports=ScrollContext},{"../behaviors/ImitateBrowserBehavior":2,"../behaviors/ScrollToTopBehavior":3,"react/lib/ExecutionEnvironment":42,"react/lib/invariant":70}],21:[function(_dereq_,module){function notifyChange(){_events.emit(CHANGE_EVENT)}function handleLocationChangeAction(action){_currentPath!==action.path&&(_currentPath=action.path,_currentActionType=action.type,notifyChange())}var _currentLocation,_currentActionType,invariant=_dereq_("react/lib/invariant"),EventEmitter=_dereq_("events").EventEmitter,CHANGE_EVENT=(_dereq_("../actions/LocationActions"),"change"),_events=new EventEmitter,_currentPath="/",PathStore={addChangeListener:function(listener){_events.addListener(CHANGE_EVENT,listener)},removeChangeListener:function(listener){_events.removeListener(CHANGE_EVENT,listener)},removeAllChangeListeners:function(){_events.removeAllListeners(CHANGE_EVENT)},setup:function(location){invariant(null==_currentLocation||_currentLocation===location,"You cannot use %s and %s on the same page",_currentLocation,location),_currentLocation!==location&&(location.setup&&location.setup(handleLocationChangeAction),_currentPath=location.getCurrentPath()),_currentLocation=location},teardown:function(){_currentLocation&&_currentLocation.teardown&&_currentLocation.teardown(),_currentLocation=_currentActionType=null,_currentPath="/",PathStore.removeAllChangeListeners()},getCurrentPath:function(){return _currentPath},getCurrentActionType:function(){return _currentActionType}};module.exports=PathStore},{"../actions/LocationActions":1,events:31,"react/lib/invariant":70}],22:[function(_dereq_,module){function encodeURL(url){return encodeURIComponent(url).replace(/%20/g,"+")}function decodeURL(url){return decodeURIComponent(url.replace(/\+/g," "))}function encodeURLPath(path){return String(path).split("/").map(encodeURL).join("/")}function compilePattern(pattern){if(!(pattern in _compiledPatterns)){var paramNames=[],source=pattern.replace(paramCompileMatcher,function(match,paramName){return paramName?(paramNames.push(paramName),"([^/?#]+)"):"*"===match?(paramNames.push("splat"),"(.*?)"):"\\"+match});_compiledPatterns[pattern]={matcher:new RegExp("^"+source+"$","i"),paramNames:paramNames}}return _compiledPatterns[pattern]}var invariant=_dereq_("react/lib/invariant"),merge=_dereq_("qs/lib/utils").merge,qs=_dereq_("qs"),paramCompileMatcher=/:([a-zA-Z_$][a-zA-Z0-9_$]*)|[*.()\[\]\\+|{}^$]/g,paramInjectMatcher=/:([a-zA-Z_$][a-zA-Z0-9_$?]*[?]?)|[*]/g,paramInjectTrailingSlashMatcher=/\/\/\?|\/\?/g,queryMatcher=/\?(.+)/,_compiledPatterns={},Path={extractParamNames:function(pattern){return compilePattern(pattern).paramNames},extractParams:function(pattern,path){var object=compilePattern(pattern),match=decodeURL(path).match(object.matcher);if(!match)return null;var params={};return object.paramNames.forEach(function(paramName,index){params[paramName]=match[index+1]}),params},injectParams:function(pattern,params){params=params||{};var splatIndex=0;return pattern.replace(paramInjectMatcher,function(match,paramName){if(paramName=paramName||"splat","?"!==paramName.slice(-1))invariant(null!=params[paramName],'Missing "'+paramName+'" parameter for path "'+pattern+'"');else if(paramName=paramName.slice(0,-1),null==params[paramName])return"";var segment;return"splat"===paramName&&Array.isArray(params[paramName])?(segment=params[paramName][splatIndex++],invariant(null!=segment,"Missing splat # "+splatIndex+' for path "'+pattern+'"')):segment=params[paramName],encodeURLPath(segment)}).replace(paramInjectTrailingSlashMatcher,"/")},extractQuery:function(path){var match=path.match(queryMatcher);return match&&qs.parse(match[1])},withoutQuery:function(path){return path.replace(queryMatcher,"")},withQuery:function(path,query){var existingQuery=Path.extractQuery(path);existingQuery&&(query=query?merge(existingQuery,query):existingQuery);var queryString=query&&qs.stringify(query);return queryString?Path.withoutQuery(path)+"?"+queryString:path },isAbsolute:function(path){return"/"===path.charAt(0)},normalize:function(path){return path.replace(/^\/*/,"/")},join:function(a,b){return a.replace(/\/*$/,"/")+b}};module.exports=Path},{qs:32,"qs/lib/utils":36,"react/lib/invariant":70}],23:[function(_dereq_,module){var Promise=_dereq_("when/lib/Promise");module.exports=Promise},{"when/lib/Promise":78}],24:[function(_dereq_,module){function Redirect(to,params,query){this.to=to,this.params=params,this.query=query}module.exports=Redirect},{}],25:[function(_dereq_,module){function cloneRoutesForServerRendering(routes){return cloneWithProps(routes,{location:"none",scrollBehavior:"none"})}function mergeStateIntoInitialProps(state,props){copyProperties(props,{initialPath:state.path,initialMatches:state.matches,initialActiveRoutes:state.activeRoutes,initialActiveParams:state.activeParams,initialActiveQuery:state.activeQuery})}function renderRoutesToString(routes,path,callback){invariant(ReactElement.isValidElement(routes),"You must pass a valid ReactComponent to renderRoutesToString");var component=instantiateReactComponent(cloneRoutesForServerRendering(routes));component.dispatch(path,function(error,abortReason,nextState){if(error||abortReason)return callback(error,abortReason);mergeStateIntoInitialProps(nextState,component.props);var transaction;try{var id=ReactInstanceHandles.createReactRootID();transaction=ReactServerRenderingTransaction.getPooled(!1),transaction.perform(function(){var markup=component.mountComponent(id,transaction,0);callback(null,null,ReactMarkupChecksum.addChecksumToMarkup(markup))},null)}finally{ReactServerRenderingTransaction.release(transaction)}})}function renderRoutesToStaticMarkup(routes,path,callback){invariant(ReactElement.isValidElement(routes),"You must pass a valid ReactComponent to renderRoutesToStaticMarkup");var component=instantiateReactComponent(cloneRoutesForServerRendering(routes));component.dispatch(path,function(error,abortReason,nextState){if(error||abortReason)return callback(error,abortReason);mergeStateIntoInitialProps(nextState,component.props);var transaction;try{var id=ReactInstanceHandles.createReactRootID();transaction=ReactServerRenderingTransaction.getPooled(!1),transaction.perform(function(){callback(null,null,component.mountComponent(id,transaction,0))},null)}finally{ReactServerRenderingTransaction.release(transaction)}})}var ReactElement=_dereq_("react/lib/ReactElement"),ReactInstanceHandles=_dereq_("react/lib/ReactInstanceHandles"),ReactMarkupChecksum=_dereq_("react/lib/ReactMarkupChecksum"),ReactServerRenderingTransaction=_dereq_("react/lib/ReactServerRenderingTransaction"),cloneWithProps=_dereq_("react/lib/cloneWithProps"),copyProperties=_dereq_("react/lib/copyProperties"),instantiateReactComponent=_dereq_("react/lib/instantiateReactComponent"),invariant=_dereq_("react/lib/invariant");module.exports={renderRoutesToString:renderRoutesToString,renderRoutesToStaticMarkup:renderRoutesToStaticMarkup}},{"react/lib/ReactElement":48,"react/lib/ReactInstanceHandles":51,"react/lib/ReactMarkupChecksum":53,"react/lib/ReactServerRenderingTransaction":58,"react/lib/cloneWithProps":63,"react/lib/copyProperties":64,"react/lib/instantiateReactComponent":69,"react/lib/invariant":70}],26:[function(_dereq_,module){function Transition(routesComponent,path){this.routesComponent=routesComponent,this.path=path,this.abortReason=null,this.isAborted=!1}var Promise=_dereq_("./Promise"),Redirect=_dereq_("./Redirect");Transition.prototype.abort=function(reason){this.abortReason=reason,this.isAborted=!0},Transition.prototype.redirect=function(to,params,query){this.abort(new Redirect(to,params,query))},Transition.prototype.wait=function(value){this.promise=Promise.resolve(value)},Transition.prototype.retry=function(){this.routesComponent.replaceWith(this.path)},module.exports=Transition},{"./Promise":23,"./Redirect":24}],27:[function(_dereq_,module){function getWindowPath(){return window.location.pathname+window.location.search}module.exports=getWindowPath},{}],28:[function(_dereq_,module){function reversedArray(array){return array.slice(0).reverse()}module.exports=reversedArray},{}],29:[function(_dereq_,module){function supportsHistory(){var ua=navigator.userAgent;return-1===ua.indexOf("Android 2.")&&-1===ua.indexOf("Android 4.0")||-1===ua.indexOf("Mobile Safari")||-1!==ua.indexOf("Chrome")?window.history&&"pushState"in window.history:!1}module.exports=supportsHistory},{}],30:[function(_dereq_,module){function withoutProperties(object,properties){var result={};for(var property in object)object.hasOwnProperty(property)&&!properties[property]&&(result[property]=object[property]);return result}module.exports=withoutProperties},{}],31:[function(_dereq_,module){function EventEmitter(){this._events=this._events||{},this._maxListeners=this._maxListeners||void 0}function isFunction(arg){return"function"==typeof arg}function isNumber(arg){return"number"==typeof arg}function isObject(arg){return"object"==typeof arg&&null!==arg}function isUndefined(arg){return void 0===arg}module.exports=EventEmitter,EventEmitter.EventEmitter=EventEmitter,EventEmitter.prototype._events=void 0,EventEmitter.prototype._maxListeners=void 0,EventEmitter.defaultMaxListeners=10,EventEmitter.prototype.setMaxListeners=function(n){if(!isNumber(n)||0>n||isNaN(n))throw TypeError("n must be a positive number");return this._maxListeners=n,this},EventEmitter.prototype.emit=function(type){var er,handler,len,args,i,listeners;if(this._events||(this._events={}),"error"===type&&(!this._events.error||isObject(this._events.error)&&!this._events.error.length))throw er=arguments[1],er instanceof Error?er:TypeError('Uncaught, unspecified "error" event.');if(handler=this._events[type],isUndefined(handler))return!1;if(isFunction(handler))switch(arguments.length){case 1:handler.call(this);break;case 2:handler.call(this,arguments[1]);break;case 3:handler.call(this,arguments[1],arguments[2]);break;default:for(len=arguments.length,args=new Array(len-1),i=1;len>i;i++)args[i-1]=arguments[i];handler.apply(this,args)}else if(isObject(handler)){for(len=arguments.length,args=new Array(len-1),i=1;len>i;i++)args[i-1]=arguments[i];for(listeners=handler.slice(),len=listeners.length,i=0;len>i;i++)listeners[i].apply(this,args)}return!0},EventEmitter.prototype.addListener=function(type,listener){var m;if(!isFunction(listener))throw TypeError("listener must be a function");if(this._events||(this._events={}),this._events.newListener&&this.emit("newListener",type,isFunction(listener.listener)?listener.listener:listener),this._events[type]?isObject(this._events[type])?this._events[type].push(listener):this._events[type]=[this._events[type],listener]:this._events[type]=listener,isObject(this._events[type])&&!this._events[type].warned){var m;m=isUndefined(this._maxListeners)?EventEmitter.defaultMaxListeners:this._maxListeners,m&&m>0&&this._events[type].length>m&&(this._events[type].warned=!0,console.error("(node) warning: possible EventEmitter memory leak detected. %d listeners added. Use emitter.setMaxListeners() to increase limit.",this._events[type].length),"function"==typeof console.trace&&console.trace())}return this},EventEmitter.prototype.on=EventEmitter.prototype.addListener,EventEmitter.prototype.once=function(type,listener){function g(){this.removeListener(type,g),fired||(fired=!0,listener.apply(this,arguments))}if(!isFunction(listener))throw TypeError("listener must be a function");var fired=!1;return g.listener=listener,this.on(type,g),this},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;if(list=this._events[type],length=list.length,position=-1,list===listener||isFunction(list.listener)&&list.listener===listener)delete this._events[type],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(0>position)return this;1===list.length?(list.length=0,delete this._events[type]):list.splice(position,1),this._events.removeListener&&this.emit("removeListener",type,listener)}return this},EventEmitter.prototype.removeAllListeners=function(type){var key,listeners;if(!this._events)return this;if(!this._events.removeListener)return 0===arguments.length?this._events={}:this._events[type]&&delete this._events[type],this;if(0===arguments.length){for(key in this._events)"removeListener"!==key&&this.removeAllListeners(key);return this.removeAllListeners("removeListener"),this._events={},this}if(listeners=this._events[type],isFunction(listeners))this.removeListener(type,listeners);else for(;listeners.length;)this.removeListener(type,listeners[listeners.length-1]);return delete this._events[type],this},EventEmitter.prototype.listeners=function(type){var ret;return ret=this._events&&this._events[type]?isFunction(this._events[type])?[this._events[type]]:this._events[type].slice():[]},EventEmitter.listenerCount=function(emitter,type){var ret;return ret=emitter._events&&emitter._events[type]?isFunction(emitter._events[type])?1:emitter._events[type].length:0}},{}],32:[function(_dereq_,module){module.exports=_dereq_("./lib")},{"./lib":33}],33:[function(_dereq_,module){var Stringify=_dereq_("./stringify"),Parse=_dereq_("./parse");module.exports={stringify:Stringify,parse:Parse}},{"./parse":34,"./stringify":35}],34:[function(_dereq_,module){var Utils=_dereq_("./utils"),internals={delimiter:"&",depth:5,arrayLimit:20,parameterLimit:1e3};internals.parseValues=function(str,options){for(var obj={},parts=str.split(options.delimiter,1/0===options.parameterLimit?void 0:options.parameterLimit),i=0,il=parts.length;il>i;++i){var part=parts[i],pos=-1===part.indexOf("]=")?part.indexOf("="):part.indexOf("]=")+1;if(-1===pos)obj[Utils.decode(part)]="";else{var key=Utils.decode(part.slice(0,pos)),val=Utils.decode(part.slice(pos+1));obj[key]=obj[key]?[].concat(obj[key]).concat(val):val}}return obj},internals.parseObject=function(chain,val,options){if(!chain.length)return val;var root=chain.shift(),obj={};if("[]"===root)obj=[],obj=obj.concat(internals.parseObject(chain,val,options));else{var cleanRoot="["===root[0]&&"]"===root[root.length-1]?root.slice(1,root.length-1):root,index=parseInt(cleanRoot,10);!isNaN(index)&&root!==cleanRoot&&index<=options.arrayLimit?(obj=[],obj[index]=internals.parseObject(chain,val,options)):obj[cleanRoot]=internals.parseObject(chain,val,options)}return obj},internals.parseKeys=function(key,val,options){if(key){var parent=/^([^\[\]]*)/,child=/(\[[^\[\]]*\])/g,segment=parent.exec(key);if(!Object.prototype.hasOwnProperty(segment[1])){var keys=[];segment[1]&&keys.push(segment[1]);for(var i=0;null!==(segment=child.exec(key))&&i<options.depth;)++i,Object.prototype.hasOwnProperty(segment[1].replace(/\[|\]/g,""))||keys.push(segment[1]);return segment&&keys.push("["+key.slice(segment.index)+"]"),internals.parseObject(keys,val,options)}}},module.exports=function(str,options){if(""===str||null===str||"undefined"==typeof str)return{};options=options||{},options.delimiter="string"==typeof options.delimiter||Utils.isRegExp(options.delimiter)?options.delimiter:internals.delimiter,options.depth="number"==typeof options.depth?options.depth:internals.depth,options.arrayLimit="number"==typeof options.arrayLimit?options.arrayLimit:internals.arrayLimit,options.parameterLimit="number"==typeof options.parameterLimit?options.parameterLimit:internals.parameterLimit;for(var tempObj="string"==typeof str?internals.parseValues(str,options):str,obj={},keys=Object.keys(tempObj),i=0,il=keys.length;il>i;++i){var key=keys[i],newObj=internals.parseKeys(key,tempObj[key],options);obj=Utils.merge(obj,newObj)}return Utils.compact(obj)}},{"./utils":36}],35:[function(_dereq_,module){var Utils=_dereq_("./utils"),internals={delimiter:"&"};internals.stringify=function(obj,prefix){if(Utils.isBuffer(obj)?obj=obj.toString():obj instanceof Date?obj=obj.toISOString():null===obj&&(obj=""),"string"==typeof obj||"number"==typeof obj||"boolean"==typeof obj)return[encodeURIComponent(prefix)+"="+encodeURIComponent(obj)];var values=[];for(var key in obj)obj.hasOwnProperty(key)&&(values=values.concat(internals.stringify(obj[key],prefix+"["+key+"]")));return values},module.exports=function(obj,options){options=options||{};var delimiter="undefined"==typeof options.delimiter?internals.delimiter:options.delimiter,keys=[];for(var key in obj)obj.hasOwnProperty(key)&&(keys=keys.concat(internals.stringify(obj[key],key)));return keys.join(delimiter)}},{"./utils":36}],36:[function(_dereq_,module,exports){exports.arrayToObject=function(source){for(var obj={},i=0,il=source.length;il>i;++i)"undefined"!=typeof source[i]&&(obj[i]=source[i]);return obj},exports.merge=function(target,source){if(!source)return target;if(Array.isArray(source)){for(var i=0,il=source.length;il>i;++i)"undefined"!=typeof source[i]&&(target[i]="object"==typeof target[i]?exports.merge(target[i],source[i]):source[i]);return target}if(Array.isArray(target)){if("object"!=typeof source)return target.push(source),target;target=exports.arrayToObject(target)}for(var keys=Object.keys(source),k=0,kl=keys.length;kl>k;++k){var key=keys[k],value=source[key];target[key]=value&&"object"==typeof value&&target[key]?exports.merge(target[key],value):value}return target},exports.decode=function(str){try{return decodeURIComponent(str.replace(/\+/g," "))}catch(e){return str}},exports.compact=function(obj,refs){if("object"!=typeof obj||null===obj)return obj;refs=refs||[];var lookup=refs.indexOf(obj);if(-1!==lookup)return refs[lookup];if(refs.push(obj),Array.isArray(obj)){for(var compacted=[],i=0,l=obj.length;l>i;++i)"undefined"!=typeof obj[i]&&compacted.push(obj[i]);return compacted}for(var keys=Object.keys(obj),i=0,il=keys.length;il>i;++i){var key=keys[i];obj[key]=exports.compact(obj[key],refs)}return obj},exports.isRegExp=function(obj){return"[object RegExp]"===Object.prototype.toString.call(obj)},exports.isBuffer=function(obj){return"undefined"!=typeof Buffer?Buffer.isBuffer(obj):!1}},{}],37:[function(_dereq_,module){"use strict";function CallbackQueue(){this._callbacks=null,this._contexts=null}var PooledClass=_dereq_("./PooledClass"),assign=_dereq_("./Object.assign"),invariant=_dereq_("./invariant");assign(CallbackQueue.prototype,{enqueue:function(callback,context){this._callbacks=this._callbacks||[],this._contexts=this._contexts||[],this._callbacks.push(callback),this._contexts.push(context)},notifyAll:function(){var callbacks=this._callbacks,contexts=this._contexts;if(callbacks){invariant(callbacks.length===contexts.length),this._callbacks=null,this._contexts=null;for(var i=0,l=callbacks.length;l>i;i++)callbacks[i].call(contexts[i]);callbacks.length=0,contexts.length=0}},reset:function(){this._callbacks=null,this._contexts=null},destructor:function(){this.reset()}}),PooledClass.addPoolingTo(CallbackQueue),module.exports=CallbackQueue},{"./Object.assign":43,"./PooledClass":44,"./invariant":70}],38:[function(_dereq_,module){"use strict";var keyMirror=_dereq_("./keyMirror"),PropagationPhases=keyMirror({bubbled:null,captured:null}),topLevelTypes=keyMirror({topBlur:null,topChange:null,topClick:null,topCompositionEnd:null,topCompositionStart:null,topCompositionUpdate:null,topContextMenu:null,topCopy:null,topCut:null,topDoubleClick:null,topDrag:null,topDragEnd:null,topDragEnter:null,topDragExit:null,topDragLeave:null,topDragOver:null,topDragStart:null,topDrop:null,topError:null,topFocus:null,topInput:null,topKeyDown:null,topKeyPress:null,topKeyUp:null,topLoad:null,topMouseDown:null,topMouseMove:null,topMouseOut:null,topMouseOver:null,topMouseUp:null,topPaste:null,topReset:null,topScroll:null,topSelectionChange:null,topSubmit:null,topTextInput:null,topTouchCancel:null,topTouchEnd:null,topTouchMove:null,topTouchStart:null,topWheel:null}),EventConstants={topLevelTypes:topLevelTypes,PropagationPhases:PropagationPhases};module.exports=EventConstants},{"./keyMirror":73}],39:[function(_dereq_,module){"use strict";var EventPluginRegistry=_dereq_("./EventPluginRegistry"),EventPluginUtils=_dereq_("./EventPluginUtils"),accumulateInto=_dereq_("./accumulateInto"),forEachAccumulated=_dereq_("./forEachAccumulated"),invariant=_dereq_("./invariant"),listenerBank={},eventQueue=null,executeDispatchesAndRelease=function(event){if(event){var executeDispatch=EventPluginUtils.executeDispatch,PluginModule=EventPluginRegistry.getPluginModuleForEvent(event);PluginModule&&PluginModule.executeDispatch&&(executeDispatch=PluginModule.executeDispatch),EventPluginUtils.executeDispatchesInOrder(event,executeDispatch),event.isPersistent()||event.constructor.release(event)}},InstanceHandle=null,EventPluginHub={injection:{injectMount:EventPluginUtils.injection.injectMount,injectInstanceHandle:function(InjectedInstanceHandle){InstanceHandle=InjectedInstanceHandle},getInstanceHandle:function(){return InstanceHandle},injectEventPluginOrder:EventPluginRegistry.injectEventPluginOrder,injectEventPluginsByName:EventPluginRegistry.injectEventPluginsByName},eventNameDispatchConfigs:EventPluginRegistry.eventNameDispatchConfigs,registrationNameModules:EventPluginRegistry.registrationNameModules,putListener:function(id,registrationName,listener){invariant(!listener||"function"==typeof listener);var bankForRegistrationName=listenerBank[registrationName]||(listenerBank[registrationName]={});bankForRegistrationName[id]=listener},getListener:function(id,registrationName){var bankForRegistrationName=listenerBank[registrationName];return bankForRegistrationName&&bankForRegistrationName[id]},deleteListener:function(id,registrationName){var bankForRegistrationName=listenerBank[registrationName];bankForRegistrationName&&delete bankForRegistrationName[id]},deleteAllListeners:function(id){for(var registrationName in listenerBank)delete listenerBank[registrationName][id]},extractEvents:function(topLevelType,topLevelTarget,topLevelTargetID,nativeEvent){for(var events,plugins=EventPluginRegistry.plugins,i=0,l=plugins.length;l>i;i++){var possiblePlugin=plugins[i];if(possiblePlugin){var extractedEvents=possiblePlugin.extractEvents(topLevelType,topLevelTarget,topLevelTargetID,nativeEvent);extractedEvents&&(events=accumulateInto(events,extractedEvents))}}return events},enqueueEvents:function(events){events&&(eventQueue=accumulateInto(eventQueue,events))},processEventQueue:function(){var processingEventQueue=eventQueue;eventQueue=null,forEachAccumulated(processingEventQueue,executeDispatchesAndRelease),invariant(!eventQueue)},__purge:function(){listenerBank={}},__getListenerBank:function(){return listenerBank}};module.exports=EventPluginHub},{"./EventPluginRegistry":40,"./EventPluginUtils":41,"./accumulateInto":61,"./forEachAccumulated":67,"./invariant":70}],40:[function(_dereq_,module){"use strict";function recomputePluginOrdering(){if(EventPluginOrder)for(var pluginName in namesToPlugins){var PluginModule=namesToPlugins[pluginName],pluginIndex=EventPluginOrder.indexOf(pluginName);if(invariant(pluginIndex>-1),!EventPluginRegistry.plugins[pluginIndex]){invariant(PluginModule.extractEvents),EventPluginRegistry.plugins[pluginIndex]=PluginModule;var publishedEvents=PluginModule.eventTypes;for(var eventName in publishedEvents)invariant(publishEventForPlugin(publishedEvents[eventName],PluginModule,eventName))}}}function publishEventForPlugin(dispatchConfig,PluginModule,eventName){invariant(!EventPluginRegistry.eventNameDispatchConfigs.hasOwnProperty(eventName)),EventPluginRegistry.eventNameDispatchConfigs[eventName]=dispatchConfig;var phasedRegistrationNames=dispatchConfig.phasedRegistrationNames;if(phasedRegistrationNames){for(var phaseName in phasedRegistrationNames)if(phasedRegistrationNames.hasOwnProperty(phaseName)){var phasedRegistrationName=phasedRegistrationNames[phaseName];publishRegistrationName(phasedRegistrationName,PluginModule,eventName)}return!0}return dispatchConfig.registrationName?(publishRegistrationName(dispatchConfig.registrationName,PluginModule,eventName),!0):!1}function publishRegistrationName(registrationName,PluginModule,eventName){invariant(!EventPluginRegistry.registrationNameModules[registrationName]),EventPluginRegistry.registrationNameModules[registrationName]=PluginModule,EventPluginRegistry.registrationNameDependencies[registrationName]=PluginModule.eventTypes[eventName].dependencies}var invariant=_dereq_("./invariant"),EventPluginOrder=null,namesToPlugins={},EventPluginRegistry={plugins:[],eventNameDispatchConfigs:{},registrationNameModules:{},registrationNameDependencies:{},injectEventPluginOrder:function(InjectedEventPluginOrder){invariant(!EventPluginOrder),EventPluginOrder=Array.prototype.slice.call(InjectedEventPluginOrder),recomputePluginOrdering()},injectEventPluginsByName:function(injectedNamesToPlugins){var isOrderingDirty=!1;for(var pluginName in injectedNamesToPlugins)if(injectedNamesToPlugins.hasOwnProperty(pluginName)){var PluginModule=injectedNamesToPlugins[pluginName];namesToPlugins.hasOwnProperty(pluginName)&&namesToPlugins[pluginName]===PluginModule||(invariant(!namesToPlugins[pluginName]),namesToPlugins[pluginName]=PluginModule,isOrderingDirty=!0)}isOrderingDirty&&recomputePluginOrdering()},getPluginModuleForEvent:function(event){var dispatchConfig=event.dispatchConfig;if(dispatchConfig.registrationName)return EventPluginRegistry.registrationNameModules[dispatchConfig.registrationName]||null;for(var phase in dispatchConfig.phasedRegistrationNames)if(dispatchConfig.phasedRegistrationNames.hasOwnProperty(phase)){var PluginModule=EventPluginRegistry.registrationNameModules[dispatchConfig.phasedRegistrationNames[phase]];if(PluginModule)return PluginModule}return null},_resetEventPlugins:function(){EventPluginOrder=null;for(var pluginName in namesToPlugins)namesToPlugins.hasOwnProperty(pluginName)&&delete namesToPlugins[pluginName];EventPluginRegistry.plugins.length=0;var eventNameDispatchConfigs=EventPluginRegistry.eventNameDispatchConfigs;for(var eventName in eventNameDispatchConfigs)eventNameDispatchConfigs.hasOwnProperty(eventName)&&delete eventNameDispatchConfigs[eventName];var registrationNameModules=EventPluginRegistry.registrationNameModules;for(var registrationName in registrationNameModules)registrationNameModules.hasOwnProperty(registrationName)&&delete registrationNameModules[registrationName]}};module.exports=EventPluginRegistry},{"./invariant":70}],41:[function(_dereq_,module){"use strict";function isEndish(topLevelType){return topLevelType===topLevelTypes.topMouseUp||topLevelType===topLevelTypes.topTouchEnd||topLevelType===topLevelTypes.topTouchCancel}function isMoveish(topLevelType){return topLevelType===topLevelTypes.topMouseMove||topLevelType===topLevelTypes.topTouchMove}function isStartish(topLevelType){return topLevelType===topLevelTypes.topMouseDown||topLevelType===topLevelTypes.topTouchStart}function forEachEventDispatch(event,cb){var dispatchListeners=event._dispatchListeners,dispatchIDs=event._dispatchIDs;if(Array.isArray(dispatchListeners))for(var i=0;i<dispatchListeners.length&&!event.isPropagationStopped();i++)cb(event,dispatchListeners[i],dispatchIDs[i]);else dispatchListeners&&cb(event,dispatchListeners,dispatchIDs)}function executeDispatch(event,listener,domID){event.currentTarget=injection.Mount.getNode(domID);var returnValue=listener(event,domID);return event.currentTarget=null,returnValue}function executeDispatchesInOrder(event,executeDispatch){forEachEventDispatch(event,executeDispatch),event._dispatchListeners=null,event._dispatchIDs=null}function executeDispatchesInOrderStopAtTrueImpl(event){var dispatchListeners=event._dispatchListeners,dispatchIDs=event._dispatchIDs;if(Array.isArray(dispatchListeners)){for(var i=0;i<dispatchListeners.length&&!event.isPropagationStopped();i++)if(dispatchListeners[i](event,dispatchIDs[i]))return dispatchIDs[i]}else if(dispatchListeners&&dispatchListeners(event,dispatchIDs))return dispatchIDs;return null}function executeDispatchesInOrderStopAtTrue(event){var ret=executeDispatchesInOrderStopAtTrueImpl(event);return event._dispatchIDs=null,event._dispatchListeners=null,ret}function executeDirectDispatch(event){var dispatchListener=event._dispatchListeners,dispatchID=event._dispatchIDs;invariant(!Array.isArray(dispatchListener));var res=dispatchListener?dispatchListener(event,dispatchID):null;return event._dispatchListeners=null,event._dispatchIDs=null,res}function hasDispatches(event){return!!event._dispatchListeners}var EventConstants=_dereq_("./EventConstants"),invariant=_dereq_("./invariant"),injection={Mount:null,injectMount:function(InjectedMount){injection.Mount=InjectedMount}},topLevelTypes=EventConstants.topLevelTypes,EventPluginUtils={isEndish:isEndish,isMoveish:isMoveish,isStartish:isStartish,executeDirectDispatch:executeDirectDispatch,executeDispatch:executeDispatch,executeDispatchesInOrder:executeDispatchesInOrder,executeDispatchesInOrderStopAtTrue:executeDispatchesInOrderStopAtTrue,hasDispatches:hasDispatches,injection:injection,useTouchEvents:!1};module.exports=EventPluginUtils},{"./EventConstants":38,"./invariant":70}],42:[function(_dereq_,module){"use strict";var canUseDOM=!("undefined"==typeof window||!window.document||!window.document.createElement),ExecutionEnvironment={canUseDOM:canUseDOM,canUseWorkers:"undefined"!=typeof Worker,canUseEventListeners:canUseDOM&&!(!window.addEventListener&&!window.attachEvent),canUseViewport:canUseDOM&&!!window.screen,isInWorker:!canUseDOM};module.exports=ExecutionEnvironment},{}],43:[function(_dereq_,module){function assign(target){if(null==target)throw new TypeError("Object.assign target cannot be null or undefined");for(var to=Object(target),hasOwnProperty=Object.prototype.hasOwnProperty,nextIndex=1;nextIndex<arguments.length;nextIndex++){var nextSource=arguments[nextIndex];if(null!=nextSource){var from=Object(nextSource);for(var key in from)hasOwnProperty.call(from,key)&&(to[key]=from[key])}}return to}module.exports=assign},{}],44:[function(_dereq_,module){"use strict";var invariant=_dereq_("./invariant"),oneArgumentPooler=function(copyFieldsFrom){var Klass=this;if(Klass.instancePool.length){var instance=Klass.instancePool.pop();return Klass.call(instance,copyFieldsFrom),instance}return new Klass(copyFieldsFrom)},twoArgumentPooler=function(a1,a2){var Klass=this;if(Klass.instancePool.length){var instance=Klass.instancePool.pop();return Klass.call(instance,a1,a2),instance}return new Klass(a1,a2)},threeArgumentPooler=function(a1,a2,a3){var Klass=this;if(Klass.instancePool.length){var instance=Klass.instancePool.pop();return Klass.call(instance,a1,a2,a3),instance}return new Klass(a1,a2,a3)},fiveArgumentPooler=function(a1,a2,a3,a4,a5){var Klass=this;if(Klass.instancePool.length){var instance=Klass.instancePool.pop();return Klass.call(instance,a1,a2,a3,a4,a5),instance}return new Klass(a1,a2,a3,a4,a5)},standardReleaser=function(instance){var Klass=this;invariant(instance instanceof Klass),instance.destructor&&instance.destructor(),Klass.instancePool.length<Klass.poolSize&&Klass.instancePool.push(instance)},DEFAULT_POOL_SIZE=10,DEFAULT_POOLER=oneArgumentPooler,addPoolingTo=function(CopyConstructor,pooler){var NewKlass=CopyConstructor;return NewKlass.instancePool=[],NewKlass.getPooled=pooler||DEFAULT_POOLER,NewKlass.poolSize||(NewKlass.poolSize=DEFAULT_POOL_SIZE),NewKlass.release=standardReleaser,NewKlass},PooledClass={addPoolingTo:addPoolingTo,oneArgumentPooler:oneArgumentPooler,twoArgumentPooler:twoArgumentPooler,threeArgumentPooler:threeArgumentPooler,fiveArgumentPooler:fiveArgumentPooler};module.exports=PooledClass},{"./invariant":70}],45:[function(_dereq_,module){"use strict";function getListeningForDocument(mountAt){return Object.prototype.hasOwnProperty.call(mountAt,topListenersIDKey)||(mountAt[topListenersIDKey]=reactTopListenersCounter++,alreadyListeningTo[mountAt[topListenersIDKey]]={}),alreadyListeningTo[mountAt[topListenersIDKey]]}var EventConstants=_dereq_("./EventConstants"),EventPluginHub=_dereq_("./EventPluginHub"),EventPluginRegistry=_dereq_("./EventPluginRegistry"),ReactEventEmitterMixin=_dereq_("./ReactEventEmitterMixin"),ViewportMetrics=_dereq_("./ViewportMetrics"),assign=_dereq_("./Object.assign"),isEventSupported=_dereq_("./isEventSupported"),alreadyListeningTo={},isMonitoringScrollValue=!1,reactTopListenersCounter=0,topEventMapping={topBlur:"blur",topChange:"change",topClick:"click",topCompositionEnd:"compositionend",topCompositionStart:"compositionstart",topCompositionUpdate:"compositionupdate",topContextMenu:"contextmenu",topCopy:"copy",topCut:"cut",topDoubleClick:"dblclick",topDrag:"drag",topDragEnd:"dragend",topDragEnter:"dragenter",topDragExit:"dragexit",topDragLeave:"dragleave",topDragOver:"dragover",topDragStart:"dragstart",topDrop:"drop",topFocus:"focus",topInput:"input",topKeyDown:"keydown",topKeyPress:"keypress",topKeyUp:"keyup",topMouseDown:"mousedown",topMouseMove:"mousemove",topMouseOut:"mouseout",topMouseOver:"mouseover",topMouseUp:"mouseup",topPaste:"paste",topScroll:"scroll",topSelectionChange:"selectionchange",topTextInput:"textInput",topTouchCancel:"touchcancel",topTouchEnd:"touchend",topTouchMove:"touchmove",topTouchStart:"touchstart",topWheel:"wheel"},topListenersIDKey="_reactListenersID"+String(Math.random()).slice(2),ReactBrowserEventEmitter=assign({},ReactEventEmitterMixin,{ReactEventListener:null,injection:{injectReactEventListener:function(ReactEventListener){ReactEventListener.setHandleTopLevel(ReactBrowserEventEmitter.handleTopLevel),ReactBrowserEventEmitter.ReactEventListener=ReactEventListener}},setEnabled:function(enabled){ReactBrowserEventEmitter.ReactEventListener&&ReactBrowserEventEmitter.ReactEventListener.setEnabled(enabled)},isEnabled:function(){return!(!ReactBrowserEventEmitter.ReactEventListener||!ReactBrowserEventEmitter.ReactEventListener.isEnabled())},listenTo:function(registrationName,contentDocumentHandle){for(var mountAt=contentDocumentHandle,isListening=getListeningForDocument(mountAt),dependencies=EventPluginRegistry.registrationNameDependencies[registrationName],topLevelTypes=EventConstants.topLevelTypes,i=0,l=dependencies.length;l>i;i++){var dependency=dependencies[i];isListening.hasOwnProperty(dependency)&&isListening[dependency]||(dependency===topLevelTypes.topWheel?isEventSupported("wheel")?ReactBrowserEventEmitter.ReactEventListener.trapBubbledEvent(topLevelTypes.topWheel,"wheel",mountAt):isEventSupported("mousewheel")?ReactBrowserEventEmitter.ReactEventListener.trapBubbledEvent(topLevelTypes.topWheel,"mousewheel",mountAt):ReactBrowserEventEmitter.ReactEventListener.trapBubbledEvent(topLevelTypes.topWheel,"DOMMouseScroll",mountAt):dependency===topLevelTypes.topScroll?isEventSupported("scroll",!0)?ReactBrowserEventEmitter.ReactEventListener.trapCapturedEvent(topLevelTypes.topScroll,"scroll",mountAt):ReactBrowserEventEmitter.ReactEventListener.trapBubbledEvent(topLevelTypes.topScroll,"scroll",ReactBrowserEventEmitter.ReactEventListener.WINDOW_HANDLE):dependency===topLevelTypes.topFocus||dependency===topLevelTypes.topBlur?(isEventSupported("focus",!0)?(ReactBrowserEventEmitter.ReactEventListener.trapCapturedEvent(topLevelTypes.topFocus,"focus",mountAt),ReactBrowserEventEmitter.ReactEventListener.trapCapturedEvent(topLevelTypes.topBlur,"blur",mountAt)):isEventSupported("focusin")&&(ReactBrowserEventEmitter.ReactEventListener.trapBubbledEvent(topLevelTypes.topFocus,"focusin",mountAt),ReactBrowserEventEmitter.ReactEventListener.trapBubbledEvent(topLevelTypes.topBlur,"focusout",mountAt)),isListening[topLevelTypes.topBlur]=!0,isListening[topLevelTypes.topFocus]=!0):topEventMapping.hasOwnProperty(dependency)&&ReactBrowserEventEmitter.ReactEventListener.trapBubbledEvent(dependency,topEventMapping[dependency],mountAt),isListening[dependency]=!0)}},trapBubbledEvent:function(topLevelType,handlerBaseName,handle){return ReactBrowserEventEmitter.ReactEventListener.trapBubbledEvent(topLevelType,handlerBaseName,handle)},trapCapturedEvent:function(topLevelType,handlerBaseName,handle){return ReactBrowserEventEmitter.ReactEventListener.trapCapturedEvent(topLevelType,handlerBaseName,handle) },ensureScrollValueMonitoring:function(){if(!isMonitoringScrollValue){var refresh=ViewportMetrics.refreshScrollValues;ReactBrowserEventEmitter.ReactEventListener.monitorScrollValue(refresh),isMonitoringScrollValue=!0}},eventNameDispatchConfigs:EventPluginHub.eventNameDispatchConfigs,registrationNameModules:EventPluginHub.registrationNameModules,putListener:EventPluginHub.putListener,getListener:EventPluginHub.getListener,deleteListener:EventPluginHub.deleteListener,deleteAllListeners:EventPluginHub.deleteAllListeners});module.exports=ReactBrowserEventEmitter},{"./EventConstants":38,"./EventPluginHub":39,"./EventPluginRegistry":40,"./Object.assign":43,"./ReactEventEmitterMixin":50,"./ViewportMetrics":60,"./isEventSupported":71}],46:[function(_dereq_,module){"use strict";var assign=_dereq_("./Object.assign"),ReactContext={current:{},withContext:function(newContext,scopedCallback){var result,previousContext=ReactContext.current;ReactContext.current=assign({},previousContext,newContext);try{result=scopedCallback()}finally{ReactContext.current=previousContext}return result}};module.exports=ReactContext},{"./Object.assign":43}],47:[function(_dereq_,module){"use strict";var ReactCurrentOwner={current:null};module.exports=ReactCurrentOwner},{}],48:[function(_dereq_,module){"use strict";var ReactContext=_dereq_("./ReactContext"),ReactCurrentOwner=_dereq_("./ReactCurrentOwner"),RESERVED_PROPS=(_dereq_("./warning"),{key:!0,ref:!0}),ReactElement=function(type,key,ref,owner,context,props){this.type=type,this.key=key,this.ref=ref,this._owner=owner,this._context=context,this.props=props};ReactElement.prototype={_isReactElement:!0},ReactElement.createElement=function(type,config,children){var propName,props={},key=null,ref=null;if(null!=config){ref=void 0===config.ref?null:config.ref,key=null==config.key?null:""+config.key;for(propName in config)config.hasOwnProperty(propName)&&!RESERVED_PROPS.hasOwnProperty(propName)&&(props[propName]=config[propName])}var childrenLength=arguments.length-2;if(1===childrenLength)props.children=children;else if(childrenLength>1){for(var childArray=Array(childrenLength),i=0;childrenLength>i;i++)childArray[i]=arguments[i+2];props.children=childArray}if(type.defaultProps){var defaultProps=type.defaultProps;for(propName in defaultProps)"undefined"==typeof props[propName]&&(props[propName]=defaultProps[propName])}return new ReactElement(type,key,ref,ReactCurrentOwner.current,ReactContext.current,props)},ReactElement.createFactory=function(type){var factory=ReactElement.createElement.bind(null,type);return factory.type=type,factory},ReactElement.cloneAndReplaceProps=function(oldElement,newProps){var newElement=new ReactElement(oldElement.type,oldElement.key,oldElement.ref,oldElement._owner,oldElement._context,newProps);return newElement},ReactElement.isValidElement=function(object){var isElement=!(!object||!object._isReactElement);return isElement},module.exports=ReactElement},{"./ReactContext":46,"./ReactCurrentOwner":47,"./warning":77}],49:[function(_dereq_,module){"use strict";function getEmptyComponent(){return invariant(component),component()}function registerNullComponentID(id){nullComponentIdsRegistry[id]=!0}function deregisterNullComponentID(id){delete nullComponentIdsRegistry[id]}function isNullComponentID(id){return nullComponentIdsRegistry[id]}var component,ReactElement=_dereq_("./ReactElement"),invariant=_dereq_("./invariant"),nullComponentIdsRegistry={},ReactEmptyComponentInjection={injectEmptyComponent:function(emptyComponent){component=ReactElement.createFactory(emptyComponent)}},ReactEmptyComponent={deregisterNullComponentID:deregisterNullComponentID,getEmptyComponent:getEmptyComponent,injection:ReactEmptyComponentInjection,isNullComponentID:isNullComponentID,registerNullComponentID:registerNullComponentID};module.exports=ReactEmptyComponent},{"./ReactElement":48,"./invariant":70}],50:[function(_dereq_,module){"use strict";function runEventQueueInBatch(events){EventPluginHub.enqueueEvents(events),EventPluginHub.processEventQueue()}var EventPluginHub=_dereq_("./EventPluginHub"),ReactEventEmitterMixin={handleTopLevel:function(topLevelType,topLevelTarget,topLevelTargetID,nativeEvent){var events=EventPluginHub.extractEvents(topLevelType,topLevelTarget,topLevelTargetID,nativeEvent);runEventQueueInBatch(events)}};module.exports=ReactEventEmitterMixin},{"./EventPluginHub":39}],51:[function(_dereq_,module){"use strict";function getReactRootIDString(index){return SEPARATOR+index.toString(36)}function isBoundary(id,index){return id.charAt(index)===SEPARATOR||index===id.length}function isValidID(id){return""===id||id.charAt(0)===SEPARATOR&&id.charAt(id.length-1)!==SEPARATOR}function isAncestorIDOf(ancestorID,descendantID){return 0===descendantID.indexOf(ancestorID)&&isBoundary(descendantID,ancestorID.length)}function getParentID(id){return id?id.substr(0,id.lastIndexOf(SEPARATOR)):""}function getNextDescendantID(ancestorID,destinationID){if(invariant(isValidID(ancestorID)&&isValidID(destinationID)),invariant(isAncestorIDOf(ancestorID,destinationID)),ancestorID===destinationID)return ancestorID;for(var start=ancestorID.length+SEPARATOR_LENGTH,i=start;i<destinationID.length&&!isBoundary(destinationID,i);i++);return destinationID.substr(0,i)}function getFirstCommonAncestorID(oneID,twoID){var minLength=Math.min(oneID.length,twoID.length);if(0===minLength)return"";for(var lastCommonMarkerIndex=0,i=0;minLength>=i;i++)if(isBoundary(oneID,i)&&isBoundary(twoID,i))lastCommonMarkerIndex=i;else if(oneID.charAt(i)!==twoID.charAt(i))break;var longestCommonID=oneID.substr(0,lastCommonMarkerIndex);return invariant(isValidID(longestCommonID)),longestCommonID}function traverseParentPath(start,stop,cb,arg,skipFirst,skipLast){start=start||"",stop=stop||"",invariant(start!==stop);var traverseUp=isAncestorIDOf(stop,start);invariant(traverseUp||isAncestorIDOf(start,stop));for(var depth=0,traverse=traverseUp?getParentID:getNextDescendantID,id=start;;id=traverse(id,stop)){var ret;if(skipFirst&&id===start||skipLast&&id===stop||(ret=cb(id,traverseUp,arg)),ret===!1||id===stop)break;invariant(depth++<MAX_TREE_DEPTH)}}var ReactRootIndex=_dereq_("./ReactRootIndex"),invariant=_dereq_("./invariant"),SEPARATOR=".",SEPARATOR_LENGTH=SEPARATOR.length,MAX_TREE_DEPTH=100,ReactInstanceHandles={createReactRootID:function(){return getReactRootIDString(ReactRootIndex.createReactRootIndex())},createReactID:function(rootID,name){return rootID+name},getReactRootIDFromNodeID:function(id){if(id&&id.charAt(0)===SEPARATOR&&id.length>1){var index=id.indexOf(SEPARATOR,1);return index>-1?id.substr(0,index):id}return null},traverseEnterLeave:function(leaveID,enterID,cb,upArg,downArg){var ancestorID=getFirstCommonAncestorID(leaveID,enterID);ancestorID!==leaveID&&traverseParentPath(leaveID,ancestorID,cb,upArg,!1,!0),ancestorID!==enterID&&traverseParentPath(ancestorID,enterID,cb,downArg,!0,!1)},traverseTwoPhase:function(targetID,cb,arg){targetID&&(traverseParentPath("",targetID,cb,arg,!0,!1),traverseParentPath(targetID,"",cb,arg,!1,!0))},traverseAncestors:function(targetID,cb,arg){traverseParentPath("",targetID,cb,arg,!0,!1)},_getFirstCommonAncestorID:getFirstCommonAncestorID,_getNextDescendantID:getNextDescendantID,isAncestorIDOf:isAncestorIDOf,SEPARATOR:SEPARATOR};module.exports=ReactInstanceHandles},{"./ReactRootIndex":57,"./invariant":70}],52:[function(_dereq_,module){"use strict";function proxyStaticMethods(target,source){if("function"==typeof source)for(var key in source)if(source.hasOwnProperty(key)){var value=source[key];if("function"==typeof value){var bound=value.bind(source);for(var k in value)value.hasOwnProperty(k)&&(bound[k]=value[k]);target[key]=bound}else target[key]=value}}var invariant=(_dereq_("./ReactCurrentOwner"),_dereq_("./invariant")),LEGACY_MARKER=(_dereq_("./monitorCodeUse"),_dereq_("./warning"),{}),NON_LEGACY_MARKER={},ReactLegacyElementFactory={};ReactLegacyElementFactory.wrapCreateFactory=function(createFactory){var legacyCreateFactory=function(type){return"function"!=typeof type?createFactory(type):type.isReactNonLegacyFactory?createFactory(type.type):type.isReactLegacyFactory?createFactory(type.type):type};return legacyCreateFactory},ReactLegacyElementFactory.wrapCreateElement=function(createElement){var legacyCreateElement=function(type){if("function"!=typeof type)return createElement.apply(this,arguments);var args;return type.isReactNonLegacyFactory?(args=Array.prototype.slice.call(arguments,0),args[0]=type.type,createElement.apply(this,args)):type.isReactLegacyFactory?(type._isMockFunction&&(type.type._mockedReactClassConstructor=type),args=Array.prototype.slice.call(arguments,0),args[0]=type.type,createElement.apply(this,args)):type.apply(null,Array.prototype.slice.call(arguments,1))};return legacyCreateElement},ReactLegacyElementFactory.wrapFactory=function(factory){invariant("function"==typeof factory);var legacyElementFactory=function(){return factory.apply(this,arguments)};return proxyStaticMethods(legacyElementFactory,factory.type),legacyElementFactory.isReactLegacyFactory=LEGACY_MARKER,legacyElementFactory.type=factory.type,legacyElementFactory},ReactLegacyElementFactory.markNonLegacyFactory=function(factory){return factory.isReactNonLegacyFactory=NON_LEGACY_MARKER,factory},ReactLegacyElementFactory.isValidFactory=function(factory){return"function"==typeof factory&&factory.isReactLegacyFactory===LEGACY_MARKER},ReactLegacyElementFactory.isValidClass=function(factory){return ReactLegacyElementFactory.isValidFactory(factory)},ReactLegacyElementFactory._isLegacyCallWarningEnabled=!0,module.exports=ReactLegacyElementFactory},{"./ReactCurrentOwner":47,"./invariant":70,"./monitorCodeUse":76,"./warning":77}],53:[function(_dereq_,module){"use strict";var adler32=_dereq_("./adler32"),ReactMarkupChecksum={CHECKSUM_ATTR_NAME:"data-react-checksum",addChecksumToMarkup:function(markup){var checksum=adler32(markup);return markup.replace(">"," "+ReactMarkupChecksum.CHECKSUM_ATTR_NAME+'="'+checksum+'">')},canReuseMarkup:function(markup,element){var existingChecksum=element.getAttribute(ReactMarkupChecksum.CHECKSUM_ATTR_NAME);existingChecksum=existingChecksum&&parseInt(existingChecksum,10);var markupChecksum=adler32(markup);return markupChecksum===existingChecksum}};module.exports=ReactMarkupChecksum},{"./adler32":62}],54:[function(_dereq_,module){"use strict";function createInstanceForTag(tag,props,parentType){var componentClass=tagToComponentClass[tag];return null==componentClass?(invariant(genericComponentClass),new genericComponentClass(tag,props)):parentType===tag?(invariant(genericComponentClass),new genericComponentClass(tag,props)):new componentClass.type(props)}var assign=_dereq_("./Object.assign"),invariant=_dereq_("./invariant"),genericComponentClass=null,tagToComponentClass={},ReactNativeComponentInjection={injectGenericComponentClass:function(componentClass){genericComponentClass=componentClass},injectComponentClasses:function(componentClasses){assign(tagToComponentClass,componentClasses)}},ReactNativeComponent={createInstanceForTag:createInstanceForTag,injection:ReactNativeComponentInjection};module.exports=ReactNativeComponent},{"./Object.assign":43,"./invariant":70}],55:[function(_dereq_,module){"use strict";function createTransferStrategy(mergeStrategy){return function(props,key,value){props[key]=props.hasOwnProperty(key)?mergeStrategy(props[key],value):value}}function transferInto(props,newProps){for(var thisKey in newProps)if(newProps.hasOwnProperty(thisKey)){var transferStrategy=TransferStrategies[thisKey];transferStrategy&&TransferStrategies.hasOwnProperty(thisKey)?transferStrategy(props,thisKey,newProps[thisKey]):props.hasOwnProperty(thisKey)||(props[thisKey]=newProps[thisKey])}return props}var assign=_dereq_("./Object.assign"),emptyFunction=_dereq_("./emptyFunction"),invariant=_dereq_("./invariant"),joinClasses=_dereq_("./joinClasses"),transferStrategyMerge=(_dereq_("./warning"),createTransferStrategy(function(a,b){return assign({},b,a)})),TransferStrategies={children:emptyFunction,className:createTransferStrategy(joinClasses),style:transferStrategyMerge},ReactPropTransferer={TransferStrategies:TransferStrategies,mergeProps:function(oldProps,newProps){return transferInto(assign({},oldProps),newProps)},Mixin:{transferPropsTo:function(element){return invariant(element._owner===this),transferInto(element.props,this.props),element}}};module.exports=ReactPropTransferer},{"./Object.assign":43,"./emptyFunction":66,"./invariant":70,"./joinClasses":72,"./warning":77}],56:[function(_dereq_,module){"use strict";function ReactPutListenerQueue(){this.listenersToPut=[]}var PooledClass=_dereq_("./PooledClass"),ReactBrowserEventEmitter=_dereq_("./ReactBrowserEventEmitter"),assign=_dereq_("./Object.assign");assign(ReactPutListenerQueue.prototype,{enqueuePutListener:function(rootNodeID,propKey,propValue){this.listenersToPut.push({rootNodeID:rootNodeID,propKey:propKey,propValue:propValue})},putListeners:function(){for(var i=0;i<this.listenersToPut.length;i++){var listenerToPut=this.listenersToPut[i];ReactBrowserEventEmitter.putListener(listenerToPut.rootNodeID,listenerToPut.propKey,listenerToPut.propValue)}},reset:function(){this.listenersToPut.length=0},destructor:function(){this.reset()}}),PooledClass.addPoolingTo(ReactPutListenerQueue),module.exports=ReactPutListenerQueue},{"./Object.assign":43,"./PooledClass":44,"./ReactBrowserEventEmitter":45}],57:[function(_dereq_,module){"use strict";var ReactRootIndexInjection={injectCreateReactRootIndex:function(_createReactRootIndex){ReactRootIndex.createReactRootIndex=_createReactRootIndex}},ReactRootIndex={createReactRootIndex:null,injection:ReactRootIndexInjection};module.exports=ReactRootIndex},{}],58:[function(_dereq_,module){"use strict";function ReactServerRenderingTransaction(renderToStaticMarkup){this.reinitializeTransaction(),this.renderToStaticMarkup=renderToStaticMarkup,this.reactMountReady=CallbackQueue.getPooled(null),this.putListenerQueue=ReactPutListenerQueue.getPooled()}var PooledClass=_dereq_("./PooledClass"),CallbackQueue=_dereq_("./CallbackQueue"),ReactPutListenerQueue=_dereq_("./ReactPutListenerQueue"),Transaction=_dereq_("./Transaction"),assign=_dereq_("./Object.assign"),emptyFunction=_dereq_("./emptyFunction"),ON_DOM_READY_QUEUEING={initialize:function(){this.reactMountReady.reset()},close:emptyFunction},PUT_LISTENER_QUEUEING={initialize:function(){this.putListenerQueue.reset()},close:emptyFunction},TRANSACTION_WRAPPERS=[PUT_LISTENER_QUEUEING,ON_DOM_READY_QUEUEING],Mixin={getTransactionWrappers:function(){return TRANSACTION_WRAPPERS},getReactMountReady:function(){return this.reactMountReady},getPutListenerQueue:function(){return this.putListenerQueue},destructor:function(){CallbackQueue.release(this.reactMountReady),this.reactMountReady=null,ReactPutListenerQueue.release(this.putListenerQueue),this.putListenerQueue=null}};assign(ReactServerRenderingTransaction.prototype,Transaction.Mixin,Mixin),PooledClass.addPoolingTo(ReactServerRenderingTransaction),module.exports=ReactServerRenderingTransaction},{"./CallbackQueue":37,"./Object.assign":43,"./PooledClass":44,"./ReactPutListenerQueue":56,"./Transaction":59,"./emptyFunction":66}],59:[function(_dereq_,module){"use strict";var invariant=_dereq_("./invariant"),Mixin={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(method,scope,a,b,c,d,e,f){invariant(!this.isInTransaction());var errorThrown,ret;try{this._isInTransaction=!0,errorThrown=!0,this.initializeAll(0),ret=method.call(scope,a,b,c,d,e,f),errorThrown=!1}finally{try{if(errorThrown)try{this.closeAll(0)}catch(err){}else this.closeAll(0)}finally{this._isInTransaction=!1}}return ret},initializeAll:function(startIndex){for(var transactionWrappers=this.transactionWrappers,i=startIndex;i<transactionWrappers.length;i++){var wrapper=transactionWrappers[i];try{this.wrapperInitData[i]=Transaction.OBSERVED_ERROR,this.wrapperInitData[i]=wrapper.initialize?wrapper.initialize.call(this):null}finally{if(this.wrapperInitData[i]===Transaction.OBSERVED_ERROR)try{this.initializeAll(i+1)}catch(err){}}}},closeAll:function(startIndex){invariant(this.isInTransaction());for(var transactionWrappers=this.transactionWrappers,i=startIndex;i<transactionWrappers.length;i++){var errorThrown,wrapper=transactionWrappers[i],initData=this.wrapperInitData[i];try{errorThrown=!0,initData!==Transaction.OBSERVED_ERROR&&wrapper.close&&wrapper.close.call(this,initData),errorThrown=!1}finally{if(errorThrown)try{this.closeAll(i+1)}catch(e){}}}this.wrapperInitData.length=0}},Transaction={Mixin:Mixin,OBSERVED_ERROR:{}};module.exports=Transaction},{"./invariant":70}],60:[function(_dereq_,module){"use strict";var getUnboundedScrollPosition=_dereq_("./getUnboundedScrollPosition"),ViewportMetrics={currentScrollLeft:0,currentScrollTop:0,refreshScrollValues:function(){var scrollPosition=getUnboundedScrollPosition(window);ViewportMetrics.currentScrollLeft=scrollPosition.x,ViewportMetrics.currentScrollTop=scrollPosition.y}};module.exports=ViewportMetrics},{"./getUnboundedScrollPosition":68}],61:[function(_dereq_,module){"use strict";function accumulateInto(current,next){if(invariant(null!=next),null==current)return next;var currentIsArray=Array.isArray(current),nextIsArray=Array.isArray(next);return currentIsArray&&nextIsArray?(current.push.apply(current,next),current):currentIsArray?(current.push(next),current):nextIsArray?[current].concat(next):[current,next]}var invariant=_dereq_("./invariant");module.exports=accumulateInto},{"./invariant":70}],62:[function(_dereq_,module){"use strict";function adler32(data){for(var a=1,b=0,i=0;i<data.length;i++)a=(a+data.charCodeAt(i))%MOD,b=(b+a)%MOD;return a|b<<16}var MOD=65521;module.exports=adler32},{}],63:[function(_dereq_,module){"use strict";function cloneWithProps(child,props){var newProps=ReactPropTransferer.mergeProps(props,child.props);return!newProps.hasOwnProperty(CHILDREN_PROP)&&child.props.hasOwnProperty(CHILDREN_PROP)&&(newProps.children=child.props.children),ReactElement.createElement(child.type,newProps)}var ReactElement=_dereq_("./ReactElement"),ReactPropTransferer=_dereq_("./ReactPropTransferer"),keyOf=_dereq_("./keyOf"),CHILDREN_PROP=(_dereq_("./warning"),keyOf({children:null}));module.exports=cloneWithProps},{"./ReactElement":48,"./ReactPropTransferer":55,"./keyOf":74,"./warning":77}],64:[function(_dereq_,module){function copyProperties(obj,a,b,c,d,e,f){obj=obj||{};for(var v,args=[a,b,c,d,e],ii=0;args[ii];){v=args[ii++];for(var k in v)obj[k]=v[k];v.hasOwnProperty&&v.hasOwnProperty("toString")&&"undefined"!=typeof v.toString&&obj.toString!==v.toString&&(obj.toString=v.toString)}return obj}module.exports=copyProperties,console.warn("react/lib/copyProperties has been deprecated and will be removed in the next version of React. All uses can be replaced with Object.assign(obj, a, b, ...) or _.extend(obj, a, b, ...).")},{}],65:[function(_dereq_,module){function cx(classNames){return"object"==typeof classNames?Object.keys(classNames).filter(function(className){return classNames[className]}).join(" "):Array.prototype.join.call(arguments," ")}module.exports=cx},{}],66:[function(_dereq_,module){function makeEmptyFunction(arg){return function(){return arg}}function emptyFunction(){}emptyFunction.thatReturns=makeEmptyFunction,emptyFunction.thatReturnsFalse=makeEmptyFunction(!1),emptyFunction.thatReturnsTrue=makeEmptyFunction(!0),emptyFunction.thatReturnsNull=makeEmptyFunction(null),emptyFunction.thatReturnsThis=function(){return this},emptyFunction.thatReturnsArgument=function(arg){return arg},module.exports=emptyFunction},{}],67:[function(_dereq_,module){"use strict";var forEachAccumulated=function(arr,cb,scope){Array.isArray(arr)?arr.forEach(cb,scope):arr&&cb.call(scope,arr)};module.exports=forEachAccumulated},{}],68:[function(_dereq_,module){"use strict";function getUnboundedScrollPosition(scrollable){return scrollable===window?{x:window.pageXOffset||document.documentElement.scrollLeft,y:window.pageYOffset||document.documentElement.scrollTop}:{x:scrollable.scrollLeft,y:scrollable.scrollTop}}module.exports=getUnboundedScrollPosition},{}],69:[function(_dereq_,module){"use strict";function instantiateReactComponent(element,parentCompositeType){var instance;return instance="string"==typeof element.type?ReactNativeComponent.createInstanceForTag(element.type,element.props,parentCompositeType):new element.type(element.props),instance.construct(element),instance}{var ReactNativeComponent=(_dereq_("./warning"),_dereq_("./ReactElement"),_dereq_("./ReactLegacyElement"),_dereq_("./ReactNativeComponent"));_dereq_("./ReactEmptyComponent")}module.exports=instantiateReactComponent},{"./ReactElement":48,"./ReactEmptyComponent":49,"./ReactLegacyElement":52,"./ReactNativeComponent":54,"./warning":77}],70:[function(_dereq_,module){"use strict";var invariant=function(condition,format,a,b,c,d,e,f){if(!condition){var error;if(void 0===format)error=new Error("Minified exception occurred; use the non-minified dev environment for the full error message and additional helpful warnings.");else{var args=[a,b,c,d,e,f],argIndex=0;error=new Error("Invariant Violation: "+format.replace(/%s/g,function(){return args[argIndex++]}))}throw error.framesToPop=1,error}};module.exports=invariant},{}],71:[function(_dereq_,module){"use strict";function isEventSupported(eventNameSuffix,capture){if(!ExecutionEnvironment.canUseDOM||capture&&!("addEventListener"in document))return!1;var eventName="on"+eventNameSuffix,isSupported=eventName in document;if(!isSupported){var element=document.createElement("div");element.setAttribute(eventName,"return;"),isSupported="function"==typeof element[eventName]}return!isSupported&&useHasFeature&&"wheel"===eventNameSuffix&&(isSupported=document.implementation.hasFeature("Events.wheel","3.0")),isSupported}var useHasFeature,ExecutionEnvironment=_dereq_("./ExecutionEnvironment");ExecutionEnvironment.canUseDOM&&(useHasFeature=document.implementation&&document.implementation.hasFeature&&document.implementation.hasFeature("","")!==!0),module.exports=isEventSupported},{"./ExecutionEnvironment":42}],72:[function(_dereq_,module){"use strict";function joinClasses(className){className||(className="");var nextClass,argLength=arguments.length;if(argLength>1)for(var ii=1;argLength>ii;ii++)nextClass=arguments[ii],nextClass&&(className=(className?className+" ":"")+nextClass);return className}module.exports=joinClasses},{}],73:[function(_dereq_,module){"use strict";var invariant=_dereq_("./invariant"),keyMirror=function(obj){var key,ret={};invariant(obj instanceof Object&&!Array.isArray(obj));for(key in obj)obj.hasOwnProperty(key)&&(ret[key]=key);return ret};module.exports=keyMirror},{"./invariant":70}],74:[function(_dereq_,module){var keyOf=function(oneKeyObj){var key;for(key in oneKeyObj)if(oneKeyObj.hasOwnProperty(key))return key;return null};module.exports=keyOf},{}],75:[function(_dereq_,module){"use strict";var assign=_dereq_("./Object.assign"),merge=function(one,two){return assign({},one,two)};module.exports=merge,console.warn("react/lib/merge has been deprecated and will be removed in the next version of React. All uses can be replaced with Object.assign({}, a, b) or _.extend({}, a, b).")},{"./Object.assign":43}],76:[function(_dereq_,module){"use strict";function monitorCodeUse(eventName){invariant(eventName&&!/[^a-z0-9_]/.test(eventName))}var invariant=_dereq_("./invariant");module.exports=monitorCodeUse},{"./invariant":70}],77:[function(_dereq_,module){"use strict";var emptyFunction=_dereq_("./emptyFunction"),warning=emptyFunction;module.exports=warning},{"./emptyFunction":66}],78:[function(_dereq_,module){!function(define){"use strict";define(function(_dereq_){var makePromise=_dereq_("./makePromise"),Scheduler=_dereq_("./Scheduler"),async=_dereq_("./async");return makePromise({scheduler:new Scheduler(async)})})}("function"==typeof define&&define.amd?define:function(factory){module.exports=factory(_dereq_)})},{"./Scheduler":80,"./async":81,"./makePromise":82}],79:[function(_dereq_,module){!function(define){"use strict";define(function(){function Queue(capacityPow2){this.head=this.tail=this.length=0,this.buffer=new Array(1<<capacityPow2)}return Queue.prototype.push=function(x){return this.length===this.buffer.length&&this._ensureCapacity(2*this.length),this.buffer[this.tail]=x,this.tail=this.tail+1&this.buffer.length-1,++this.length,this.length},Queue.prototype.shift=function(){var x=this.buffer[this.head];return this.buffer[this.head]=void 0,this.head=this.head+1&this.buffer.length-1,--this.length,x},Queue.prototype._ensureCapacity=function(capacity){var len,head=this.head,buffer=this.buffer,newBuffer=new Array(capacity),i=0;if(0===head)for(len=this.length;len>i;++i)newBuffer[i]=buffer[i];else{for(capacity=buffer.length,len=this.tail;capacity>head;++i,++head)newBuffer[i]=buffer[head];for(head=0;len>head;++i,++head)newBuffer[i]=buffer[head]}this.buffer=newBuffer,this.head=0,this.tail=this.length},Queue})}("function"==typeof define&&define.amd?define:function(factory){module.exports=factory()})},{}],80:[function(_dereq_,module){!function(define){"use strict";define(function(_dereq_){function Scheduler(async){this._async=async,this._queue=new Queue(15),this._afterQueue=new Queue(5),this._running=!1;var self=this;this.drain=function(){self._drain()}}function runQueue(queue){for(;queue.length>0;)queue.shift().run()}var Queue=_dereq_("./Queue");return Scheduler.prototype.enqueue=function(task){this._add(this._queue,task)},Scheduler.prototype.afterQueue=function(task){this._add(this._afterQueue,task)},Scheduler.prototype._drain=function(){runQueue(this._queue),this._running=!1,runQueue(this._afterQueue)},Scheduler.prototype._add=function(queue,task){queue.push(task),this._running||(this._running=!0,this._async(this.drain))},Scheduler})}("function"==typeof define&&define.amd?define:function(factory){module.exports=factory(_dereq_)})},{"./Queue":79}],81:[function(_dereq_,module){!function(define){"use strict";define(function(_dereq_){var nextTick,MutationObs;return nextTick="undefined"!=typeof process&&null!==process&&"function"==typeof process.nextTick?function(f){process.nextTick(f)}:(MutationObs="function"==typeof MutationObserver&&MutationObserver||"function"==typeof WebKitMutationObserver&&WebKitMutationObserver)?function(document,MutationObserver){function run(){var f=scheduled;scheduled=void 0,f()}var scheduled,el=document.createElement("div"),o=new MutationObserver(run);return o.observe(el,{attributes:!0}),function(f){scheduled=f,el.setAttribute("class","x")}}(document,MutationObs):function(cjsRequire){var vertx;try{vertx=cjsRequire("vertx")}catch(ignore){}if(vertx){if("function"==typeof vertx.runOnLoop)return vertx.runOnLoop;if("function"==typeof vertx.runOnContext)return vertx.runOnContext}var capturedSetTimeout=setTimeout;return function(t){capturedSetTimeout(t,0)}}(_dereq_)})}("function"==typeof define&&define.amd?define:function(factory){module.exports=factory(_dereq_)})},{}],82:[function(_dereq_,module){!function(define){"use strict";define(function(){return function(environment){function Promise(resolver,handler){this._handler=resolver===Handler?handler:init(resolver)}function init(resolver){function promiseResolve(x){handler.resolve(x)}function promiseReject(reason){handler.reject(reason)}function promiseNotify(x){handler.notify(x)}var handler=new Pending;try{resolver(promiseResolve,promiseReject,promiseNotify)}catch(e){promiseReject(e)}return handler}function resolve(x){return isPromise(x)?x:new Promise(Handler,new Async(getHandler(x)))}function reject(x){return new Promise(Handler,new Async(new Rejected(x)))}function never(){return foreverPendingPromise}function defer(){return new Promise(Handler,new Pending)}function all(promises){function settleAt(i,x,resolver){this[i]=x,0===--pending&&resolver.become(new Fulfilled(this))}var i,h,x,s,resolver=new Pending,pending=promises.length>>>0,results=new Array(pending);for(i=0;i<promises.length;++i)if(x=promises[i],void 0!==x||i in promises)if(maybeThenable(x))if(h=getHandlerMaybeThenable(x),s=h.state(),0===s)h.fold(settleAt,i,results,resolver);else{if(!(s>0)){unreportRemaining(promises,i+1,h),resolver.become(h);break}results[i]=h.value,--pending}else results[i]=x,--pending;else--pending;return 0===pending&&resolver.become(new Fulfilled(results)),new Promise(Handler,resolver)}function unreportRemaining(promises,start,rejectedHandler){var i,h,x;for(i=start;i<promises.length;++i)x=promises[i],maybeThenable(x)&&(h=getHandlerMaybeThenable(x),h!==rejectedHandler&&h.visit(h,void 0,h._unreport))}function race(promises){if(Object(promises)===promises&&0===promises.length)return never();var i,x,h=new Pending;for(i=0;i<promises.length;++i)x=promises[i],void 0!==x&&i in promises&&getHandler(x).visit(h,h.resolve,h.reject);return new Promise(Handler,h)}function getHandler(x){return isPromise(x)?x._handler.join():maybeThenable(x)?getHandlerUntrusted(x):new Fulfilled(x)}function getHandlerMaybeThenable(x){return isPromise(x)?x._handler.join():getHandlerUntrusted(x)}function getHandlerUntrusted(x){try{var untrustedThen=x.then;return"function"==typeof untrustedThen?new Thenable(untrustedThen,x):new Fulfilled(x)}catch(e){return new Rejected(e)}}function Handler(){}function FailIfRejected(){}function Pending(receiver,inheritedContext){Promise.createContext(this,inheritedContext),this.consumers=void 0,this.receiver=receiver,this.handler=void 0,this.resolved=!1}function Async(handler){this.handler=handler}function Thenable(then,thenable){Pending.call(this),tasks.enqueue(new AssimilateTask(then,thenable,this))}function Fulfilled(x){Promise.createContext(this),this.value=x}function Rejected(x){Promise.createContext(this),this.id=++errorId,this.value=x,this.handled=!1,this.reported=!1,this._report()}function ReportTask(rejection,context){this.rejection=rejection,this.context=context}function UnreportTask(rejection){this.rejection=rejection}function cycle(){return new Rejected(new TypeError("Promise cycle"))}function ContinuationTask(continuation,handler){this.continuation=continuation,this.handler=handler}function ProgressTask(value,handler){this.handler=handler,this.value=value}function AssimilateTask(then,thenable,resolver){this._then=then,this.thenable=thenable,this.resolver=resolver}function tryAssimilate(then,thenable,resolve,reject,notify){try{then.call(thenable,resolve,reject,notify)}catch(e){reject(e)}}function isPromise(x){return x instanceof Promise}function maybeThenable(x){return("object"==typeof x||"function"==typeof x)&&null!==x}function runContinuation1(f,h,receiver,next){return"function"!=typeof f?next.become(h):(Promise.enterContext(h),tryCatchReject(f,h.value,receiver,next),void Promise.exitContext())}function runContinuation3(f,x,h,receiver,next){return"function"!=typeof f?next.become(h):(Promise.enterContext(h),tryCatchReject3(f,x,h.value,receiver,next),void Promise.exitContext())}function runNotify(f,x,h,receiver,next){return"function"!=typeof f?next.notify(x):(Promise.enterContext(h),tryCatchReturn(f,x,receiver,next),void Promise.exitContext())}function tryCatchReject(f,x,thisArg,next){try{next.become(getHandler(f.call(thisArg,x)))}catch(e){next.become(new Rejected(e))}}function tryCatchReject3(f,x,y,thisArg,next){try{f.call(thisArg,x,y,next)}catch(e){next.become(new Rejected(e))}}function tryCatchReturn(f,x,thisArg,next){try{next.notify(f.call(thisArg,x))}catch(e){next.notify(e)}}function inherit(Parent,Child){Child.prototype=objectCreate(Parent.prototype),Child.prototype.constructor=Child}function noop(){}var tasks=environment.scheduler,objectCreate=Object.create||function(proto){function Child(){}return Child.prototype=proto,new Child};Promise.resolve=resolve,Promise.reject=reject,Promise.never=never,Promise._defer=defer,Promise._handler=getHandler,Promise.prototype.then=function(onFulfilled,onRejected){var parent=this._handler,state=parent.join().state(); if("function"!=typeof onFulfilled&&state>0||"function"!=typeof onRejected&&0>state)return new this.constructor(Handler,parent);var p=this._beget(),child=p._handler;return parent.chain(child,parent.receiver,onFulfilled,onRejected,arguments.length>2?arguments[2]:void 0),p},Promise.prototype["catch"]=function(onRejected){return this.then(void 0,onRejected)},Promise.prototype._beget=function(){var parent=this._handler,child=new Pending(parent.receiver,parent.join().context);return new this.constructor(Handler,child)},Promise.all=all,Promise.race=race,Handler.prototype.when=Handler.prototype.become=Handler.prototype.notify=Handler.prototype.fail=Handler.prototype._unreport=Handler.prototype._report=noop,Handler.prototype._state=0,Handler.prototype.state=function(){return this._state},Handler.prototype.join=function(){for(var h=this;void 0!==h.handler;)h=h.handler;return h},Handler.prototype.chain=function(to,receiver,fulfilled,rejected,progress){this.when({resolver:to,receiver:receiver,fulfilled:fulfilled,rejected:rejected,progress:progress})},Handler.prototype.visit=function(receiver,fulfilled,rejected,progress){this.chain(failIfRejected,receiver,fulfilled,rejected,progress)},Handler.prototype.fold=function(f,z,c,to){this.visit(to,function(x){f.call(c,z,x,this)},to.reject,to.notify)},inherit(Handler,FailIfRejected),FailIfRejected.prototype.become=function(h){h.fail()};var failIfRejected=new FailIfRejected;inherit(Handler,Pending),Pending.prototype._state=0,Pending.prototype.resolve=function(x){this.become(getHandler(x))},Pending.prototype.reject=function(x){this.resolved||this.become(new Rejected(x))},Pending.prototype.join=function(){if(!this.resolved)return this;for(var h=this;void 0!==h.handler;)if(h=h.handler,h===this)return this.handler=cycle();return h},Pending.prototype.run=function(){var q=this.consumers,handler=this.join();this.consumers=void 0;for(var i=0;i<q.length;++i)handler.when(q[i])},Pending.prototype.become=function(handler){this.resolved||(this.resolved=!0,this.handler=handler,void 0!==this.consumers&&tasks.enqueue(this),void 0!==this.context&&handler._report(this.context))},Pending.prototype.when=function(continuation){this.resolved?tasks.enqueue(new ContinuationTask(continuation,this.handler)):void 0===this.consumers?this.consumers=[continuation]:this.consumers.push(continuation)},Pending.prototype.notify=function(x){this.resolved||tasks.enqueue(new ProgressTask(x,this))},Pending.prototype.fail=function(context){var c="undefined"==typeof context?this.context:context;this.resolved&&this.handler.join().fail(c)},Pending.prototype._report=function(context){this.resolved&&this.handler.join()._report(context)},Pending.prototype._unreport=function(){this.resolved&&this.handler.join()._unreport()},inherit(Handler,Async),Async.prototype.when=function(continuation){tasks.enqueue(new ContinuationTask(continuation,this))},Async.prototype._report=function(context){this.join()._report(context)},Async.prototype._unreport=function(){this.join()._unreport()},inherit(Pending,Thenable),inherit(Handler,Fulfilled),Fulfilled.prototype._state=1,Fulfilled.prototype.fold=function(f,z,c,to){runContinuation3(f,z,this,c,to)},Fulfilled.prototype.when=function(cont){runContinuation1(cont.fulfilled,this,cont.receiver,cont.resolver)};var errorId=0;inherit(Handler,Rejected),Rejected.prototype._state=-1,Rejected.prototype.fold=function(f,z,c,to){to.become(this)},Rejected.prototype.when=function(cont){"function"==typeof cont.rejected&&this._unreport(),runContinuation1(cont.rejected,this,cont.receiver,cont.resolver)},Rejected.prototype._report=function(context){tasks.afterQueue(new ReportTask(this,context))},Rejected.prototype._unreport=function(){this.handled=!0,tasks.afterQueue(new UnreportTask(this))},Rejected.prototype.fail=function(context){Promise.onFatalRejection(this,void 0===context?this.context:context)},ReportTask.prototype.run=function(){this.rejection.handled||(this.rejection.reported=!0,Promise.onPotentiallyUnhandledRejection(this.rejection,this.context))},UnreportTask.prototype.run=function(){this.rejection.reported&&Promise.onPotentiallyUnhandledRejectionHandled(this.rejection)},Promise.createContext=Promise.enterContext=Promise.exitContext=Promise.onPotentiallyUnhandledRejection=Promise.onPotentiallyUnhandledRejectionHandled=Promise.onFatalRejection=noop;var foreverPendingHandler=new Handler,foreverPendingPromise=new Promise(Handler,foreverPendingHandler);return ContinuationTask.prototype.run=function(){this.handler.join().when(this.continuation)},ProgressTask.prototype.run=function(){var q=this.handler.consumers;if(void 0!==q)for(var c,i=0;i<q.length;++i)c=q[i],runNotify(c.progress,this.value,this.handler,c.receiver,c.resolver)},AssimilateTask.prototype.run=function(){function _resolve(x){h.resolve(x)}function _reject(x){h.reject(x)}function _notify(x){h.notify(x)}var h=this.resolver;tryAssimilate(this._then,this.thenable,_resolve,_reject,_notify)},Promise}})}("function"==typeof define&&define.amd?define:function(factory){module.exports=factory()})},{}]},{},[10])(10)});
people-app/pages/person.js
giltayar/micro-next-workshop
import React from 'react' import Head from 'next/head' import Router from 'next/router' import fetch from 'isomorphic-fetch' export default class PersonPage extends React.Component { static async getInitialProps({res, query}) { const peopleDbUrl = res ? process.env.PEOPLE_DB : window.peopleDbUrl if (!query.id) { return {peopleDbUrl, first: '', last: '', age: ''} } else { return Object.assign({}, {peopleDbUrl}, await (await fetch(`${peopleDbUrl}/people/${query.id}`)).json()) } } constructor(props) { super(props) this.state = props } render() { const {first, last, age} = this.state return ( <div className="container"> <script dangerouslySetInnerHTML={{ __html: `window.peopleDbUrl = ${JSON.stringify(this.props.peopleDbUrl)}` }}> </script> <Head> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossOrigin="anonymous" /> </Head> <style jsx>{` .panel { max-width: 400px; margin: 10px; } `}</style> <div className="panel panel-default"> <div className="panel-heading"><h1 className="panel-title">{first || last ? (first || '') + ' ' + (last || '') : 'New Person'}</h1></div> <form className="panel-body"> <div className="form-group"> <label htmlFor="firstName">First Name</label> <input type="text" className="form-control" id="firstName" placeholder="First Name" value={first} onChange={(ev) => this.setState({first: ev.target.value})} /> </div> <div className="form-group"> <label htmlFor="firstName">Last Name</label> <input type="text" className="form-control" id="lastName" placeholder="Last Name" value={last} onChange={(ev) => this.setState({last: ev.target.value})} /> </div> <div className="form-group"> <label htmlFor="firstName">Age</label> <input type="number" className="form-control" id="age" placeholder="Age" value={age} onChange={(ev) => this.setState({age: parseInt(ev.target.value)})} /> </div> <button type="submit" className="btn btn-default" onClick={(ev) => this.handleSave(ev)}> {this.state.id ? 'Save' : 'Add'} </button> </form> </div> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" /> </div> ) } async handleSave(ev) { ev.preventDefault() await fetch(`${this.state.peopleDbUrl}/people`, { method: this.state.id ? 'PUT' : 'POST', headers: {'content-type': 'application/json'}, body: JSON.stringify({id: this.state.id, first: this.state.first, last: this.state.last, age: this.state.age}) }) Router.push('/') } }
ajax/libs/redux-form/7.0.0/redux-form.min.js
jonobr1/cdnjs
!function(e,t){"object"==typeof exports&&"object"==typeof module?module.exports=t(require("react"),require("react-redux"),require("redux")):"function"==typeof define&&define.amd?define(["react","react-redux","redux"],t):"object"==typeof exports?exports.ReduxForm=t(require("react"),require("react-redux"),require("redux")):e.ReduxForm=t(e.React,e.ReactRedux,e.Redux)}(this,function(e,t,r){return function(e){function t(n){if(r[n])return r[n].exports;var o=r[n]={i:n,l:!1,exports:{}};return e[n].call(o.exports,o,o.exports,t),o.l=!0,o.exports}var r={};return t.m=e,t.c=r,t.d=function(e,r,n){t.o(e,r)||Object.defineProperty(e,r,{configurable:!1,enumerable:!0,get:n})},t.n=function(e){var r=e&&e.__esModule?function(){return e.default}:function(){return e};return t.d(r,"a",r),r},t.o=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},t.p="",t(t.s=41)}([function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{default:e}}Object.defineProperty(t,"__esModule",{value:!0});var o=r(56),u=n(o),i=r(57),a=n(i),f=r(64),s=n(f),c=r(65),l=n(c),d=r(82),p=n(d),y=r(83),v=n(y);t.default={allowsArrayErrors:!0,empty:{},emptyList:[],getIn:a.default,setIn:s.default,deepEqual:l.default,deleteIn:p.default,forEach:function(e,t){return e.forEach(t)},fromJS:function(e){return e},keys:v.default,size:function(e){return e?e.length:0},some:function(e,t){return e.some(t)},splice:u.default,toJS:function(e){return e}}},function(e,t,r){e.exports=r(43)()},function(t,r){t.exports=e},function(e,r){e.exports=t},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.default=function(e,t){var r=e._reduxForm.sectionPrefix;return r?r+"."+t:t}},function(e,t,r){"use strict";e.exports=function(e,t,r,n,o,u,i,a){if(!e){var f;if(void 0===t)f=Error("Minified exception occurred; use the non-minified dev environment for the full error message and additional helpful warnings.");else{var s=[r,n,o,u,i,a],c=0;f=Error(t.replace(/%s/g,function(){return s[c++]})),f.name="Invariant Violation"}throw f.framesToPop=1,f}}},function(e,t,r){function n(e){return i(e)?o(e,s):a(e)?[e]:u(f(c(e)))}var o=r(58),u=r(23),i=r(7),a=r(59),f=r(60),s=r(62),c=r(63);e.exports=n},function(e,t){e.exports=Array.isArray},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(11);e.exports=n},function(e,t,r){function n(e,t,r){"__proto__"==t&&o?o(e,t,{configurable:!0,enumerable:!0,value:r,writable:!0}):e[t]=r}var o=r(90);e.exports=n},function(e,t){function r(e){var t=typeof e;return null!=e&&("object"==t||"function"==t)}e.exports=r},function(e,t){function r(e,t){return e===t||e!==e&&t!==t}e.exports=r},function(e,t){function r(e,t){return function(r){return e(t(r))}}e.exports=r},function(e,t){function r(e){return null!=e&&"object"==typeof e}e.exports=r},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var n=r(121),o=function(e){return e&&e.__esModule?e:{default:e}}(n);t.default=function(e){var t=e.getIn,r=e.keys,n=(0,o.default)(e);return function(e,o){var u=arguments.length>2&&void 0!==arguments[2]&&arguments[2];return function(i){var a=o||function(e){return t(e,"form")},f=a(i);if(t(f,e+".syncError"))return!1;if(!u){if(t(f,e+".error"))return!1}var s=t(f,e+".syncErrors"),c=t(f,e+".asyncErrors"),l=u?void 0:t(f,e+".submitErrors");if(!s&&!c&&!l)return!0;var d=t(f,e+".registeredFields");return!d||!r(d).filter(function(e){return t(d,"['"+e+"'].count")>0}).some(function(e){return n(t(d,"['"+e+"']"),s,c,l)})}}}},function(e,t){function r(e){return!!e&&("object"==typeof e||"function"==typeof e)&&"function"==typeof e.then}e.exports=r},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var n=t.prefix="@@redux-form/";t.ARRAY_INSERT=n+"ARRAY_INSERT",t.ARRAY_MOVE=n+"ARRAY_MOVE",t.ARRAY_POP=n+"ARRAY_POP",t.ARRAY_PUSH=n+"ARRAY_PUSH",t.ARRAY_REMOVE=n+"ARRAY_REMOVE",t.ARRAY_REMOVE_ALL=n+"ARRAY_REMOVE_ALL",t.ARRAY_SHIFT=n+"ARRAY_SHIFT",t.ARRAY_SPLICE=n+"ARRAY_SPLICE",t.ARRAY_UNSHIFT=n+"ARRAY_UNSHIFT",t.ARRAY_SWAP=n+"ARRAY_SWAP",t.AUTOFILL=n+"AUTOFILL",t.BLUR=n+"BLUR",t.CHANGE=n+"CHANGE",t.CLEAR_SUBMIT=n+"CLEAR_SUBMIT",t.CLEAR_SUBMIT_ERRORS=n+"CLEAR_SUBMIT_ERRORS",t.CLEAR_ASYNC_ERROR=n+"CLEAR_ASYNC_ERROR",t.DESTROY=n+"DESTROY",t.FOCUS=n+"FOCUS",t.INITIALIZE=n+"INITIALIZE",t.REGISTER_FIELD=n+"REGISTER_FIELD",t.RESET=n+"RESET",t.SET_SUBMIT_FAILED=n+"SET_SUBMIT_FAILED",t.SET_SUBMIT_SUCCEEDED=n+"SET_SUBMIT_SUCCEEDED",t.START_ASYNC_VALIDATION=n+"START_ASYNC_VALIDATION",t.START_SUBMIT=n+"START_SUBMIT",t.STOP_ASYNC_VALIDATION=n+"STOP_ASYNC_VALIDATION",t.STOP_SUBMIT=n+"STOP_SUBMIT",t.SUBMIT=n+"SUBMIT",t.TOUCH=n+"TOUCH",t.UNREGISTER_FIELD=n+"UNREGISTER_FIELD",t.UNTOUCH=n+"UNTOUCH",t.UPDATE_SYNC_ERRORS=n+"UPDATE_SYNC_ERRORS",t.UPDATE_SYNC_WARNINGS=n+"UPDATE_SYNC_WARNINGS"},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.default=function(e){var t=e.initialized,r=e.trigger,n=e.pristine;if(!e.syncValidationPasses)return!1;switch(r){case"blur":return!0;case"submit":return!n||!t;default:return!1}}},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.default=function(e){var t=e.values,r=e.nextProps,n=e.initialRender,o=e.lastFieldValidatorKeys,u=e.fieldValidatorKeys,i=e.structure;return!!n||(!i.deepEqual(t,r&&r.values)||!i.deepEqual(o,u))}},function(e,t,r){"use strict";function n(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function o(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 u(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)}Object.defineProperty(t,"__esModule",{value:!0});var i=r(48),a=function(e){return e&&e.__esModule?e:{default:e}}(i);t.default=function(e){function t(e){n(this,t);var r=o(this,(t.__proto__||Object.getPrototypeOf(t)).call(this,"Submit Validation Failed"));return r.errors=e,r}return u(t,e),t}(a.default)},function(e,t,r){"use strict";function n(e,t){var r={};for(var n in e)0>t.indexOf(n)&&Object.prototype.hasOwnProperty.call(e,n)&&(r[n]=e[n]);return r}Object.defineProperty(t,"__esModule",{value:!0});var o=Object.assign||function(e){for(var t=1;arguments.length>t;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},u=function(e,t,r){var n=t.value;return"checkbox"===e?o({},t,{checked:!!n}):"radio"===e?o({},t,{checked:n===r,value:r}):"select-multiple"===e?o({},t,{value:n||[]}):"file"===e?o({},t,{value:n||void 0}):t};t.default=function(e,t,r){var i=e.getIn,a=e.toJS,f=r.asyncError,s=r.asyncValidating,c=r.onBlur,l=r.onChange,d=r.onDrop,p=r.onDragStart,y=r.dirty,v=r.dispatch,m=r.onFocus,b=r.form,h=r.format,_=r.initial,g=r.pristine,O=r.props,S=r.state,R=r.submitError,E=r.submitFailed,j=r.submitting,P=r.syncError,A=r.syncWarning,w=r.value,x=r._value,F=n(r,["asyncError","asyncValidating","onBlur","onChange","onDrop","onDragStart","dirty","dispatch","onFocus","form","format","initial","parse","pristine","props","state","submitError","submitFailed","submitting","syncError","syncWarning","validate","value","_value","warn"]),T=P||f||R,I=A,M=function(e,r){if(null===r)return e;var n=null==e?"":e;return r?r(e,t):n}(w,h);return{input:u(F.type,{name:t,onBlur:c,onChange:l,onDragStart:p,onDrop:d,onFocus:m,value:M},x),meta:o({},a(S),{active:!(!S||!i(S,"active")),asyncValidating:s,autofilled:!(!S||!i(S,"autofilled")),dirty:y,dispatch:v,error:T,form:b,initial:_,warning:I,invalid:!!T,pristine:g,submitting:!!j,submitFailed:!!E,touched:!(!S||!i(S,"touched")),valid:!T,visited:!(!S||!i(S,"visited"))}),custom:o({},F,O)}}},function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{default:e}}Object.defineProperty(t,"__esModule",{value:!0});var o=r(53),u=n(o),i=r(54),a=n(i);t.default=function(e,t){var r=t.name,n=t.parse,o=t.normalize,i=(0,u.default)(e,a.default);return n&&(i=n(i,r)),o&&(i=o(r,i)),i}},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.default=function(e){return!!(e&&e.stopPropagation&&e.preventDefault)}},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){function n(e,t,r){r="function"==typeof r?r:void 0;var n=r?r(e,t):void 0;return void 0===n?o(e,t,void 0,r):!!n}var o=r(66);e.exports=n},function(e,t,r){function n(e){var t=-1,r=null==e?0:e.length;for(this.clear();++t<r;){var n=e[t];this.set(n[0],n[1])}}var o=r(68),u=r(69),i=r(70),a=r(71),f=r(72);n.prototype.clear=o,n.prototype.delete=u,n.prototype.get=i,n.prototype.has=a,n.prototype.set=f,e.exports=n},function(e,t){function r(){return!1}e.exports=r},function(e,t){function r(){return!1}e.exports=r},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var n=r(24),o=function(e){return e&&e.__esModule?e:{default:e}}(n),u=function(e,t,r,n,o,u){if(u)return e===t};t.default=function(e,t,r){return!(0,o.default)(e.props,t,u)||!(0,o.default)(e.state,r,u)}},function(e,t,r){function n(e,t){var r={};return t=i(t,3),u(e,function(e,n,u){o(r,n,t(e,n,u))}),r}var o=r(9),u=r(92),i=r(95);e.exports=n},function(e,t,r){e.exports=r(93)()},function(e,t){e.exports=r},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.default=function(e){var t=e.deepEqual,r=e.empty,n=e.getIn;return function(e,o){return function(u){var i=o||function(e){return n(e,"form")},a=i(u),f=n(a,e+".initial")||r,s=n(a,e+".values")||f;return t(f,s)}}}},function(e,t,r){function n(e,t,r){(void 0===r||u(e[t],r))&&(void 0!==r||t in e)||o(e,t,r)}var o=r(9),u=r(11);e.exports=n},function(e,t,r){var n=r(137),o="object"==typeof self&&self&&self.Object===Object&&self;e.exports=n||o||Function("return this")()},function(e,t,r){e.exports=r(12)(Object.getPrototypeOf,Object)},function(e,t,r){function n(e){if(!u(e))return!1;var t=o(e);return t==a||t==f||t==i||t==s}var o=r(37),u=r(10),i="[object AsyncFunction]",a="[object Function]",f="[object GeneratorFunction]",s="[object Proxy]";e.exports=n},function(e,t){function r(e){return o.call(e)}var n=Object.prototype,o=n.toString;e.exports=r},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,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var n=Object.assign||function(e){for(var t=1;arguments.length>t;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},o=r(16);t.default={arrayInsert:function(e,t,r,n){return{type:o.ARRAY_INSERT,meta:{form:e,field:t,index:r},payload:n}},arrayMove:function(e,t,r,n){return{type:o.ARRAY_MOVE,meta:{form:e,field:t,from:r,to:n}}},arrayPop:function(e,t){return{type:o.ARRAY_POP,meta:{form:e,field:t}}},arrayPush:function(e,t,r){return{type:o.ARRAY_PUSH,meta:{form:e,field:t},payload:r}},arrayRemove:function(e,t,r){return{type:o.ARRAY_REMOVE,meta:{form:e,field:t,index:r}}},arrayRemoveAll:function(e,t){return{type:o.ARRAY_REMOVE_ALL,meta:{form:e,field:t}}},arrayShift:function(e,t){return{type:o.ARRAY_SHIFT,meta:{form:e,field:t}}},arraySplice:function(e,t,r,n,u){var i={type:o.ARRAY_SPLICE,meta:{form:e,field:t,index:r,removeNum:n}};return void 0!==u&&(i.payload=u),i},arraySwap:function(e,t,r,n){if(r===n)throw Error("Swap indices cannot be equal");if(0>r||0>n)throw Error("Swap indices cannot be negative");return{type:o.ARRAY_SWAP,meta:{form:e,field:t,indexA:r,indexB:n}}},arrayUnshift:function(e,t,r){return{type:o.ARRAY_UNSHIFT,meta:{form:e,field:t},payload:r}},autofill:function(e,t,r){return{type:o.AUTOFILL,meta:{form:e,field:t},payload:r}},blur:function(e,t,r,n){return{type:o.BLUR,meta:{form:e,field:t,touch:n},payload:r}},change:function(e,t,r,n,u){return{type:o.CHANGE,meta:{form:e,field:t,touch:n,persistentSubmitErrors:u},payload:r}},clearSubmit:function(e){return{type:o.CLEAR_SUBMIT,meta:{form:e}}},clearSubmitErrors:function(e){return{type:o.CLEAR_SUBMIT_ERRORS,meta:{form:e}}},clearAsyncError:function(e,t){return{type:o.CLEAR_ASYNC_ERROR,meta:{form:e,field:t}}},destroy:function(){for(var e=arguments.length,t=Array(e),r=0;e>r;r++)t[r]=arguments[r];return{type:o.DESTROY,meta:{form:t}}},focus:function(e,t){return{type:o.FOCUS,meta:{form:e,field:t}}},initialize:function(e,t,r){var u=arguments.length>3&&void 0!==arguments[3]?arguments[3]:{};return r instanceof Object&&(u=r,r=!1),{type:o.INITIALIZE,meta:n({form:e,keepDirty:r},u),payload:t}},registerField:function(e,t,r){return{type:o.REGISTER_FIELD,meta:{form:e},payload:{name:t,type:r}}},reset:function(e){return{type:o.RESET,meta:{form:e}}},startAsyncValidation:function(e,t){return{type:o.START_ASYNC_VALIDATION,meta:{form:e,field:t}}},startSubmit:function(e){return{type:o.START_SUBMIT,meta:{form:e}}},stopAsyncValidation:function(e,t){return{type:o.STOP_ASYNC_VALIDATION,meta:{form:e},payload:t,error:!(!t||!Object.keys(t).length)}},stopSubmit:function(e,t){return{type:o.STOP_SUBMIT,meta:{form:e},payload:t,error:!(!t||!Object.keys(t).length)}},submit:function(e){return{type:o.SUBMIT,meta:{form:e}}},setSubmitFailed:function(e){for(var t=arguments.length,r=Array(t>1?t-1:0),n=1;t>n;n++)r[n-1]=arguments[n];return{type:o.SET_SUBMIT_FAILED,meta:{form:e,fields:r},error:!0}},setSubmitSucceeded:function(e){for(var t=arguments.length,r=Array(t>1?t-1:0),n=1;t>n;n++)r[n-1]=arguments[n];return{type:o.SET_SUBMIT_SUCCEEDED,meta:{form:e,fields:r},error:!1}},touch:function(e){for(var t=arguments.length,r=Array(t>1?t-1:0),n=1;t>n;n++)r[n-1]=arguments[n];return{type:o.TOUCH,meta:{form:e,fields:r}}},unregisterField:function(e,t){return{type:o.UNREGISTER_FIELD,meta:{form:e},payload:{name:t,destroyOnUnmount:2>=arguments.length||void 0===arguments[2]||arguments[2]}}},untouch:function(e){for(var t=arguments.length,r=Array(t>1?t-1:0),n=1;t>n;n++)r[n-1]=arguments[n];return{type:o.UNTOUCH,meta:{form:e,fields:r}}},updateSyncErrors:function(e){return{type:o.UPDATE_SYNC_ERRORS,meta:{form:e},payload:{syncErrors:arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},error:arguments[2]}}},updateSyncWarnings:function(e){return{type:o.UPDATE_SYNC_WARNINGS,meta:{form:e},payload:{syncWarnings:arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},warning:arguments[2]}}}}},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var n=r(22),o=function(e){return e&&e.__esModule?e:{default:e}}(n);t.default=function(e){var t=(0,o.default)(e);return t&&e.preventDefault(),t}},function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{default:e}}Object.defineProperty(t,"__esModule",{value:!0}),t.untouch=t.unregisterField=t.touch=t.submit=t.stopSubmit=t.stopAsyncValidation=t.startSubmit=t.startAsyncValidation=t.setSubmitSucceeded=t.setSubmitFailed=t.reset=t.registerField=t.initialize=t.focus=t.destroy=t.clearSubmitErrors=t.change=t.blur=t.autofill=t.arrayUnshift=t.arraySwap=t.arraySplice=t.arrayShift=t.arrayRemoveAll=t.arrayRemove=t.arrayPush=t.arrayPop=t.arrayMove=t.arrayInsert=t.actionTypes=t.values=t.reducer=t.reduxForm=t.hasSubmitFailed=t.hasSubmitSucceeded=t.isSubmitting=t.isValid=t.isPristine=t.isInvalid=t.isDirty=t.getFormSubmitErrors=t.getFormSyncWarnings=t.getFormAsyncErrors=t.getFormMeta=t.getFormSyncErrors=t.getFormInitialValues=t.getFormValues=t.getFormNames=t.formValues=t.formValueSelector=t.FieldArray=t.Fields=t.Field=t.formPropTypes=t.fieldPropTypes=t.fieldMetaPropTypes=t.fieldInputPropTypes=t.propTypes=t.SubmissionError=t.FormSection=t.Form=t.defaultShouldValidate=t.defaultShouldAsyncValidate=void 0;var o=r(17);Object.defineProperty(t,"defaultShouldAsyncValidate",{enumerable:!0,get:function(){return n(o).default}});var u=r(18);Object.defineProperty(t,"defaultShouldValidate",{enumerable:!0,get:function(){return n(u).default}});var i=r(42);Object.defineProperty(t,"Form",{enumerable:!0,get:function(){return n(i).default}});var a=r(47);Object.defineProperty(t,"FormSection",{enumerable:!0,get:function(){return n(a).default}});var f=r(19);Object.defineProperty(t,"SubmissionError",{enumerable:!0,get:function(){return n(f).default}});var s=r(49);Object.defineProperty(t,"propTypes",{enumerable:!0,get:function(){return n(s).default}}),Object.defineProperty(t,"fieldInputPropTypes",{enumerable:!0,get:function(){return s.fieldInputPropTypes}}),Object.defineProperty(t,"fieldMetaPropTypes",{enumerable:!0,get:function(){return s.fieldMetaPropTypes}}),Object.defineProperty(t,"fieldPropTypes",{enumerable:!0,get:function(){return s.fieldPropTypes}}),Object.defineProperty(t,"formPropTypes",{enumerable:!0,get:function(){return s.formPropTypes}});var c=r(50);Object.defineProperty(t,"Field",{enumerable:!0,get:function(){return n(c).default}});var l=r(84);Object.defineProperty(t,"Fields",{enumerable:!0,get:function(){return n(l).default}});var d=r(87);Object.defineProperty(t,"FieldArray",{enumerable:!0,get:function(){return n(d).default}});var p=r(97);Object.defineProperty(t,"formValueSelector",{enumerable:!0,get:function(){return n(p).default}});var y=r(99);Object.defineProperty(t,"formValues",{enumerable:!0,get:function(){return n(y).default}});var v=r(101);Object.defineProperty(t,"getFormNames",{enumerable:!0,get:function(){return n(v).default}});var m=r(103);Object.defineProperty(t,"getFormValues",{enumerable:!0,get:function(){return n(m).default}});var b=r(105);Object.defineProperty(t,"getFormInitialValues",{enumerable:!0,get:function(){return n(b).default}});var h=r(107);Object.defineProperty(t,"getFormSyncErrors",{enumerable:!0,get:function(){return n(h).default}});var _=r(109);Object.defineProperty(t,"getFormMeta",{enumerable:!0,get:function(){return n(_).default}});var g=r(111);Object.defineProperty(t,"getFormAsyncErrors",{enumerable:!0,get:function(){return n(g).default}});var O=r(113);Object.defineProperty(t,"getFormSyncWarnings",{enumerable:!0,get:function(){return n(O).default}});var S=r(115);Object.defineProperty(t,"getFormSubmitErrors",{enumerable:!0,get:function(){return n(S).default}});var R=r(117);Object.defineProperty(t,"isDirty",{enumerable:!0,get:function(){return n(R).default}});var E=r(119);Object.defineProperty(t,"isInvalid",{enumerable:!0,get:function(){return n(E).default}});var j=r(122);Object.defineProperty(t,"isPristine",{enumerable:!0,get:function(){return n(j).default}});var P=r(123);Object.defineProperty(t,"isValid",{enumerable:!0,get:function(){return n(P).default}});var A=r(124);Object.defineProperty(t,"isSubmitting",{enumerable:!0,get:function(){return n(A).default}});var w=r(126);Object.defineProperty(t,"hasSubmitSucceeded",{enumerable:!0,get:function(){return n(w).default}});var x=r(128);Object.defineProperty(t,"hasSubmitFailed",{enumerable:!0,get:function(){return n(x).default}});var F=r(130);Object.defineProperty(t,"reduxForm",{enumerable:!0,get:function(){return n(F).default}});var T=r(166);Object.defineProperty(t,"reducer",{enumerable:!0,get:function(){return n(T).default}});var I=r(169);Object.defineProperty(t,"values",{enumerable:!0,get:function(){return n(I).default}});var M=r(39),C=n(M),k=r(16),V=function(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}(k);t.actionTypes=V,t.arrayInsert=C.default.arrayInsert,t.arrayMove=C.default.arrayMove,t.arrayPop=C.default.arrayPop,t.arrayPush=C.default.arrayPush,t.arrayRemove=C.default.arrayRemove,t.arrayRemoveAll=C.default.arrayRemoveAll,t.arrayShift=C.default.arrayShift,t.arraySplice=C.default.arraySplice,t.arraySwap=C.default.arraySwap,t.arrayUnshift=C.default.arrayUnshift,t.autofill=C.default.autofill,t.blur=C.default.blur,t.change=C.default.change,t.clearSubmitErrors=C.default.clearSubmitErrors,t.destroy=C.default.destroy,t.focus=C.default.focus,t.initialize=C.default.initialize,t.registerField=C.default.registerField,t.reset=C.default.reset,t.setSubmitFailed=C.default.setSubmitFailed,t.setSubmitSucceeded=C.default.setSubmitSucceeded,t.startAsyncValidation=C.default.startAsyncValidation,t.startSubmit=C.default.startSubmit,t.stopAsyncValidation=C.default.stopAsyncValidation,t.stopSubmit=C.default.stopSubmit,t.submit=C.default.submit,t.touch=C.default.touch,t.unregisterField=C.default.unregisterField,t.untouch=C.default.untouch},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 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)}Object.defineProperty(t,"__esModule",{value:!0});var a=function(){function e(e,t){for(var r=0;t.length>r;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}}(),f=r(2),s=n(f),c=r(1),l=n(c),d=function(e){function t(e,r){o(this,t);var n=u(this,(t.__proto__||Object.getPrototypeOf(t)).call(this,e,r));if(!r._reduxForm)throw Error("Form must be inside a component decorated with reduxForm()");return n}return i(t,e),a(t,[{key:"componentWillMount",value:function(){this.context._reduxForm.registerInnerOnSubmit(this.props.onSubmit)}},{key:"render",value:function(){return s.default.createElement("form",this.props)}}]),t}(f.Component);d.propTypes={onSubmit:l.default.func.isRequired},d.contextTypes={_reduxForm:l.default.object},t.default=d},function(e,t,r){"use strict";var n=r(44),o=r(45),u=r(46);e.exports=function(){function e(e,t,r,n,i,a){a!==u&&o(!1,"Calling PropTypes validators directly is not supported by the `prop-types` package. Use PropTypes.checkPropTypes() to call them. Read more at http://fb.me/use-check-prop-types")}function t(){return e}e.isRequired=e;var r={array:e,bool:e,func:e,number:e,object:e,string:e,symbol:e,any:e,arrayOf:t,element:e,instanceOf:t,node:e,objectOf:t,oneOf:t,oneOfType:t,shape:t};return r.checkPropTypes=n,r.PropTypes=r,r}},function(e,t,r){"use strict";function n(e){return function(){return e}}var o=function(){};o.thatReturns=n,o.thatReturnsFalse=n(!1),o.thatReturnsTrue=n(!0),o.thatReturnsNull=n(null),o.thatReturnsThis=function(){return this},o.thatReturnsArgument=function(e){return e},e.exports=o},function(e,t,r){"use strict";function n(e,t,r,n,u,i,a,f){if(o(t),!e){var s;if(void 0===t)s=Error("Minified exception occurred; use the non-minified dev environment for the full error message and additional helpful warnings.");else{var c=[r,n,u,i,a,f],l=0;s=Error(t.replace(/%s/g,function(){return c[l++]})),s.name="Invariant Violation"}throw s.framesToPop=1,s}}var o=function(e){};e.exports=n},function(e,t,r){"use strict";e.exports="SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED"},function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{default:e}}function o(e,t){var r={};for(var n in e)0>t.indexOf(n)&&Object.prototype.hasOwnProperty.call(e,n)&&(r[n]=e[n]);return r}function u(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function i(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)}Object.defineProperty(t,"__esModule",{value:!0});var f=Object.assign||function(e){for(var t=1;arguments.length>t;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;t.length>r;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(2),l=n(c),d=r(1),p=n(d),y=r(4),v=n(y),m=function(e){function t(e,r){u(this,t);var n=i(this,(t.__proto__||Object.getPrototypeOf(t)).call(this,e,r));if(!r._reduxForm)throw Error("FormSection must be inside a component decorated with reduxForm()");return n}return a(t,e),s(t,[{key:"getChildContext",value:function(){var e=this.context;return{_reduxForm:f({},e._reduxForm,{sectionPrefix:(0,v.default)(e,this.props.name)})}}},{key:"render",value:function(){var e=this.props,t=e.children,r=e.component,n=o(e,["children","name","component"]);return l.default.isValidElement(t)?t:(0,c.createElement)(r,f({},n,{children:t}))}}]),t}(c.Component);m.propTypes={name:p.default.string.isRequired,component:p.default.oneOfType([p.default.func,p.default.string])},m.defaultProps={component:"div"},m.childContextTypes={_reduxForm:p.default.object.isRequired},m.contextTypes={_reduxForm:p.default.object},t.default=m},function(e,t,r){"use strict";function n(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function o(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 u(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)}Object.defineProperty(t,"__esModule",{value:!0}),t.default=function(e){function t(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"";n(this,t);var r=o(this,(t.__proto__||Object.getPrototypeOf(t)).call(this,e));return Object.defineProperty(r,"message",{configurable:!0,enumerable:!1,value:e,writable:!0}),Object.defineProperty(r,"name",{configurable:!0,enumerable:!1,value:r.constructor.name,writable:!0}),Error.hasOwnProperty("captureStackTrace")?(Error.captureStackTrace(r,r.constructor),o(r)):(Object.defineProperty(r,"stack",{configurable:!0,enumerable:!1,value:Error(e).stack,writable:!0}),r)}return u(t,e),t}(function(e){function t(){e.apply(this,arguments)}return t.prototype=Object.create(e.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),Object.setPrototypeOf?Object.setPrototypeOf(t,e):t.__proto__=e,t}(Error)),e.exports=t.default},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.fieldPropTypes=t.fieldMetaPropTypes=t.fieldInputPropTypes=t.formPropTypes=void 0;var n=r(1),o=function(e){return e&&e.__esModule?e:{default:e}}(n),u=o.default.any,i=o.default.bool,a=o.default.func,f=o.default.shape,s=o.default.string,c=o.default.oneOfType,l=o.default.object,d=t.formPropTypes={anyTouched:i.isRequired,asyncValidating:c([i,s]).isRequired,dirty:i.isRequired,error:u,form:s.isRequired,invalid:i.isRequired,initialized:i.isRequired,initialValues:l,pristine:i.isRequired,pure:i.isRequired,submitting:i.isRequired,submitFailed:i.isRequired,submitSucceeded:i.isRequired,valid:i.isRequired,warning:u,array:f({insert:a.isRequired,move:a.isRequired,pop:a.isRequired,push:a.isRequired,remove:a.isRequired,removeAll:a.isRequired,shift:a.isRequired,splice:a.isRequired,swap:a.isRequired,unshift:a.isRequired}),asyncValidate:a.isRequired,autofill:a.isRequired,blur:a.isRequired,change:a.isRequired,clearAsyncError:a.isRequired,destroy:a.isRequired,dispatch:a.isRequired,handleSubmit:a.isRequired,initialize:a.isRequired,reset:a.isRequired,touch:a.isRequired,submit:a.isRequired,untouch:a.isRequired,triggerSubmit:i,clearSubmit:a.isRequired},p=t.fieldInputPropTypes={checked:i,name:s.isRequired,onBlur:a.isRequired,onChange:a.isRequired,onDragStart:a.isRequired,onDrop:a.isRequired,onFocus:a.isRequired,value:u},y=t.fieldMetaPropTypes={active:i.isRequired,asyncValidating:i.isRequired,autofilled:i.isRequired,dirty:i.isRequired,dispatch:a.isRequired,error:s,form:s.isRequired,invalid:i.isRequired,pristine:i.isRequired,submitting:i.isRequired,submitFailed:i.isRequired,touched:i.isRequired,valid:i.isRequired,visited:i.isRequired,warning:s};t.fieldPropTypes={input:f(p).isRequired,meta:f(y).isRequired,custom:l.isRequired};t.default=d},function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{default:e}}Object.defineProperty(t,"__esModule",{value:!0}),t.default=(0,n(r(51)).default)(n(r(0)).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 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)}Object.defineProperty(t,"__esModule",{value:!0});var a=Object.assign||function(e){for(var t=1;arguments.length>t;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},f=function(){function e(e,t){for(var r=0;t.length>r;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=r(2),c=r(1),l=n(c),d=r(5),p=n(d),y=r(52),v=n(y),m=r(28),b=n(m),h=r(4),_=n(h);t.default=function(e){var t=(0,v.default)(e),r=e.setIn,n=function(e){function n(e,t){o(this,n);var i=u(this,(n.__proto__||Object.getPrototypeOf(n)).call(this,e,t));if(i.saveRef=function(e){return i.ref=e},i.normalize=function(e,t){var n=i.props.normalize;if(!n)return t;var o=i.context._reduxForm.getValues();return n(t,i.value,r(o,e,t),o)},!t._reduxForm)throw Error("Field must be inside a component decorated with reduxForm()");return i}return i(n,e),f(n,[{key:"shouldComponentUpdate",value:function(e){return(0,b.default)(this,e)}},{key:"componentWillMount",value:function(){var e=this;this.context._reduxForm.register(this.name,"Field",function(){return e.props.validate},function(){return e.props.warn})}},{key:"componentWillReceiveProps",value:function(e){this.props.name===e.name&&this.props.validate===e.validate&&this.props.warn===e.warn||(this.context._reduxForm.unregister(this.name),this.context._reduxForm.register((0,_.default)(this.context,e.name),"Field",function(){return e.validate},function(){return e.warn}))}},{key:"componentWillUnmount",value:function(){this.context._reduxForm.unregister(this.name)}},{key:"getRenderedComponent",value:function(){return(0,p.default)(this.props.withRef,"If you want to access getRenderedComponent(), you must specify a withRef prop to Field"),this.ref.getWrappedInstance().getRenderedComponent()}},{key:"render",value:function(){return(0,s.createElement)(t,a({},this.props,{name:this.name,normalize:this.normalize,_reduxForm:this.context._reduxForm,ref:this.saveRef}))}},{key:"name",get:function(){return(0,_.default)(this.context,this.props.name)}},{key:"dirty",get:function(){return!this.pristine}},{key:"pristine",get:function(){return this.ref.getWrappedInstance().isPristine()}},{key:"value",get:function(){return this.ref&&this.ref.getWrappedInstance().getValue()}}]),n}(s.Component);return n.propTypes={name:l.default.string.isRequired,component:l.default.oneOfType([l.default.func,l.default.string]).isRequired,format:l.default.func,normalize:l.default.func,onBlur:l.default.func,onChange:l.default.func,onFocus:l.default.func,onDragStart:l.default.func,onDrop:l.default.func,parse:l.default.func,props:l.default.object,validate:l.default.oneOfType([l.default.func,l.default.arrayOf(l.default.func)]),warn:l.default.oneOfType([l.default.func,l.default.arrayOf(l.default.func)]),withRef:l.default.bool},n.contextTypes={_reduxForm:l.default.object},n}},function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{default:e}}function o(e,t){var r={};for(var n in e)0>t.indexOf(n)&&Object.prototype.hasOwnProperty.call(e,n)&&(r[n]=e[n]);return r}function u(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function i(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)}Object.defineProperty(t,"__esModule",{value:!0});var f=Object.assign||function(e){for(var t=1;arguments.length>t;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;t.length>r;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&&e!==Symbol.prototype?"symbol":typeof e},l=r(2),d=r(1),p=n(d),y=r(3),v=r(20),m=n(v),b=r(21),h=n(b),_=r(55),g=r(0),O=n(g),S=["_reduxForm"],R=function(e){return e&&"object"===(void 0===e?"undefined":c(e))},E=function(e){return e&&"function"==typeof e},j=function(e){R(e)&&E(e.preventDefault)&&e.preventDefault()},P=function(e,t){if(R(e)&&R(e.dataTransfer)&&E(e.dataTransfer.getData))return e.dataTransfer.getData(t)},A=function(e,t,r){R(e)&&R(e.dataTransfer)&&E(e.dataTransfer.setData)&&e.dataTransfer.setData(t,r)};t.default=function(e){var t=e.deepEqual,r=e.getIn,n=function(e,t){var r=O.default.getIn(e,t);return r&&r._error?r._error:r},c=function(e,t){var n=r(e,t);return n&&n._warning?n._warning:n},d=function(r){function n(){var e,t,r,o;u(this,n);for(var a=arguments.length,s=Array(a),c=0;a>c;c++)s[c]=arguments[c];return t=r=i(this,(e=n.__proto__||Object.getPrototypeOf(n)).call.apply(e,[this].concat(s))),r.saveRef=function(e){return r.ref=e},r.isPristine=function(){return r.props.pristine},r.getValue=function(){return r.props.value},r.handleChange=function(e){var t=r.props,n=t.name,o=t.dispatch,u=t.parse,i=t.normalize,a=t.onChange,s=t._reduxForm,c=t.value,l=(0,h.default)(e,{name:n,parse:u,normalize:i}),d=!1;a&&a(f({},e,{preventDefault:function(){return d=!0,j(e)}}),l,c),d||o(s.change(n,l))},r.handleFocus=function(e){var t=r.props,n=t.name,o=t.dispatch,u=t.onFocus,i=t._reduxForm,a=!1;u&&u(f({},e,{preventDefault:function(){return a=!0,j(e)}})),a||o(i.focus(n))},r.handleBlur=function(e){var t=r.props,n=t.name,o=t.dispatch,u=t.parse,i=t.normalize,a=t.onBlur,s=t._reduxForm,c=t._value,l=t.value,d=(0,h.default)(e,{name:n,parse:u,normalize:i});d===c&&void 0!==c&&(d=l);var p=!1;a&&a(f({},e,{preventDefault:function(){return p=!0,j(e)}}),d,l),p||(o(s.blur(n,d)),s.asyncValidate&&s.asyncValidate(n,d))},r.handleDragStart=function(e){var t=r.props,n=t.onDragStart,o=t.value;A(e,_.dataKey,null==o?"":o),n&&n(e)},r.handleDrop=function(e){var t=r.props,n=t.name,o=t.dispatch,u=t.onDrop,i=t._reduxForm,a=t.value,s=P(e,_.dataKey),c=!1;u&&u(f({},e,{preventDefault:function(){return c=!0,j(e)}}),s,a),c||(o(i.change(n,s)),j(e))},o=t,i(r,o)}return a(n,r),s(n,[{key:"shouldComponentUpdate",value:function(e){var r=this,n=Object.keys(e);return n.length!==Object.keys(this.props).length||n.some(function(n){return!~S.indexOf(n)&&!t(r.props[n],e[n])})}},{key:"getRenderedComponent",value:function(){return this.ref}},{key:"render",value:function(){var t=this.props,r=t.component,n=t.withRef,u=t.name,i=t._reduxForm,a=o(t,["component","withRef","name","_reduxForm","normalize","onBlur","onChange","onFocus","onDragStart","onDrop"]),s=(0,m.default)(e,u,f({},a,{form:i.form,onBlur:this.handleBlur,onChange:this.handleChange,onDrop:this.handleDrop,onDragStart:this.handleDragStart,onFocus:this.handleFocus})),c=s.custom,d=o(s,["custom"]);if(n&&(c.ref=this.saveRef),"string"==typeof r){var p=d.input;return(0,l.createElement)(r,f({},p,c))}return(0,l.createElement)(r,f({},d,c))}}]),n}(l.Component);return d.propTypes={component:p.default.oneOfType([p.default.func,p.default.string]).isRequired,props:p.default.object},(0,y.connect)(function(e,o){var u=o.name,i=o._reduxForm,a=i.initialValues,f=i.getFormState,s=f(e),l=r(s,"initial."+u),d=void 0!==l?l:a&&r(a,u),p=r(s,"values."+u),y=r(s,"submitting"),v=n(r(s,"syncErrors"),u),m=c(r(s,"syncWarnings"),u),b=t(p,d);return{asyncError:r(s,"asyncErrors."+u),asyncValidating:r(s,"asyncValidating")===u,dirty:!b,pristine:b,state:r(s,"fields."+u),submitError:r(s,"submitErrors."+u),submitFailed:r(s,"submitFailed"),submitting:y,syncError:v,syncWarning:m,initial:d,value:p,_value:o.value}},void 0,void 0,{withRef:!0})(d)}},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var n=r(22),o=function(e){return e&&e.__esModule?e:{default:e}}(n),u=function(e){var t=[];if(e)for(var r=0;e.length>r;r++){var n=e[r];n.selected&&t.push(n.value)}return t};t.default=function(e,t){if((0,o.default)(e)){if(!t&&e.nativeEvent&&void 0!==e.nativeEvent.text)return e.nativeEvent.text;if(t&&void 0!==e.nativeEvent)return e.nativeEvent.text;var r=e.target,n=r.type,i=r.value,a=r.checked,f=r.files,s=e.dataTransfer;return"checkbox"===n?a||"":"file"===n?f||s&&s.files:"select-multiple"===n?u(e.target.options):i}return e}},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.default="undefined"!=typeof window&&window.navigator&&window.navigator.product&&"ReactNative"===window.navigator.product},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0});t.dataKey="text"},function(e,t,r){"use strict";function n(e){if(Array.isArray(e)){for(var t=0,r=Array(e.length);e.length>t;t++)r[t]=e[t];return r}return Array.from(e)}Object.defineProperty(t,"__esModule",{value:!0}),t.default=function(e,t,r,o){if(e=e||[],e.length>t){if(void 0===o&&!r){var u=[].concat(n(e));return u.splice(t,0,!0),u[t]=void 0,u}if(null!=o){var i=[].concat(n(e));return i.splice(t,r,o),i}var a=[].concat(n(e));return a.splice(t,r),a}if(r)return e;var f=[].concat(n(e));return f[t]=o,f}},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var n=r(6),o=function(e){return e&&e.__esModule?e:{default:e}}(n);t.default=function(e,t){if(!e)return e;var r=(0,o.default)(t),n=r.length;if(n){for(var u=e,i=0;n>i&&u;++i)u=u[r[i]];return u}}},function(e,t){function r(e,t){for(var r=-1,n=null==e?0:e.length,o=Array(n);++r<n;)o[r]=t(e[r],r,e);return o}e.exports=r},function(e,t){function r(){return!1}e.exports=r},function(e,t,r){var n=/^\./,o=/[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g,u=/\\(\\)?/g;e.exports=r(61)(function(e){var t=[];return n.test(e)&&t.push(""),e.replace(o,function(e,r,n,o){t.push(n?o.replace(u,"$1"):r||e)}),t})},function(e,t){function r(e){return e}e.exports=r},function(e,t){function r(e){return e}e.exports=r},function(e,t){function r(e){return e}e.exports=r},function(e,t,r){"use strict";function n(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 o=r(6),u=function(e){return e&&e.__esModule?e:{default:e}}(o),i=Object.assign||function(e){for(var t=1;arguments.length>t;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},a=function e(t,r,o,u){if(u>=o.length)return r;var a=o[u],f=t&&(Array.isArray(t)?t[+a]:t[a]),s=e(f,r,o,u+1);if(!t){if(isNaN(a))return n({},a,s);var c=[];return c[parseInt(a,10)]=s,c}if(Array.isArray(t)){var l=[].concat(t);return l[parseInt(a,10)]=s,l}return i({},t,n({},a,s))};t.default=function(e,t,r){return a(e,r,(0,u.default)(t),0)}},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var n=r(24),o=function(e){return e&&e.__esModule?e:{default:e}}(n),u=function(e,t){return e===t||(null!=e&&""!==e&&!1!==e||null!=t&&""!==t&&!1!==t?(!e||!t||e._error===t._error)&&((!e||!t||e._warning===t._warning)&&void 0):!(void 0===e&&!1===t||!1===e&&void 0===t))};t.default=function(e,t){return(0,o.default)(e,t,u)}},function(e,t,r){function n(e,t,r,i,a){return e===t||(null==e||null==t||!u(e)&&!u(t)?e!==e&&t!==t:o(e,t,r,i,n,a))}var o=r(67),u=r(13);e.exports=n},function(e,t,r){function n(e,t,r,n,m,h){var _=s(e),g=s(t),O=_?y:f(e),S=g?y:f(t);O=O==p?v:O,S=S==p?v:S;var R=O==v,E=S==v,j=O==S;if(j&&c(e)){if(!c(t))return!1;_=!0,R=!1}if(j&&!R)return h||(h=new o),_||l(e)?u(e,t,r,n,m,h):i(e,t,O,r,n,m,h);if(!(r&d)){var P=R&&b.call(e,"__wrapped__"),A=E&&b.call(t,"__wrapped__");if(P||A){var w=P?e.value():e,x=A?t.value():t;return h||(h=new o),m(w,x,r,n,h)}}return!!j&&(h||(h=new o),a(e,t,r,n,m,h))}var o=r(25),u=r(73),i=r(78),a=r(79),f=r(81),s=r(7),c=r(26),l=r(27),d=1,p="[object Arguments]",y="[object Array]",v="[object Object]",m=Object.prototype,b=m.hasOwnProperty;e.exports=n},function(e,t){function r(){this.__data__=[],this.size=0}e.exports=r},function(e,t,r){function n(e){var t=this.__data__,r=o(t,e);return r>=0&&(r==t.length-1?t.pop():i.call(t,r,1),--this.size,!0)}var o=r(8),u=Array.prototype,i=u.splice;e.exports=n},function(e,t,r){function n(e){var t=this.__data__,r=o(t,e);return 0>r?void 0:t[r][1]}var o=r(8);e.exports=n},function(e,t,r){function n(e){return o(this.__data__,e)>-1}var o=r(8);e.exports=n},function(e,t,r){function n(e,t){var r=this.__data__,n=o(r,e);return 0>n?(++this.size,r.push([e,t])):r[n][1]=t,this}var o=r(8);e.exports=n},function(e,t,r){function n(e,t,r,n,s,c){var l=r&a,d=e.length,p=t.length;if(!(d==p||l&&p>d))return!1;var y=c.get(e);if(y&&c.get(t))return y==t;var v=-1,m=!0,b=r&f?new o:void 0;for(c.set(e,t),c.set(t,e);++v<d;){var h=e[v],_=t[v];if(n)var g=l?n(_,h,v,t,e,c):n(h,_,v,e,t,c);if(void 0!==g){if(g)continue;m=!1;break}if(b){if(!u(t,function(e,t){if(!i(b,t)&&(h===e||s(h,e,r,n,c)))return b.push(t)})){m=!1;break}}else if(h!==_&&!s(h,_,r,n,c)){m=!1;break}}return c.delete(e),c.delete(t),m}var o=r(74),u=r(75),i=r(76),a=1,f=2;e.exports=n},function(e,t,r){function n(){if(!arguments.length)return[];var e=arguments[0];return o(e)?e:[e]}var o=r(7);e.exports=n},function(e,t){function r(e,t){for(var r=-1,n=null==e?0:e.length;++r<n;)if(t(e[r],r,e))return!0;return!1}e.exports=r},function(e,t,r){function n(e,t){return!!(null==e?0:e.length)&&o(e,t,0)>-1}var o=r(77);e.exports=n},function(e,t){function r(e,t,r){for(var n=r-1,o=e.length;++n<o;)if(e[n]===t)return n;return-1}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,n,i,f){var s=r&u,c=o(e),l=c.length;if(l!=o(t).length&&!s)return!1;for(var d=l;d--;){var p=c[d];if(!(s?p in t:a.call(t,p)))return!1}var y=f.get(e);if(y&&f.get(t))return y==t;var v=!0;f.set(e,t),f.set(t,e);for(var m=s;++d<l;){p=c[d];var b=e[p],h=t[p];if(n)var _=s?n(h,b,p,t,e,f):n(b,h,p,e,t,f);if(!(void 0===_?b===h||i(b,h,r,n,f):_)){v=!1;break}m||(m="constructor"==p)}if(v&&!m){var g=e.constructor,O=t.constructor;g!=O&&"constructor"in e&&"constructor"in t&&!("function"==typeof g&&g instanceof g&&"function"==typeof O&&O instanceof O)&&(v=!1)}return f.delete(e),f.delete(t),v}var o=r(80),u=1,i=Object.prototype,a=i.hasOwnProperty;e.exports=n},function(e,t,r){e.exports=r(12)(Object.keys,Object)},function(e,t){function r(e){return o.call(e)}var n=Object.prototype,o=n.toString;e.exports=r},function(e,t,r){"use strict";function n(e,t,r){return t in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}function o(e){if(Array.isArray(e)){for(var t=0,r=Array(e.length);e.length>t;t++)r[t]=e[t];return r}return Array.from(e)}function u(e,t){if(void 0===e||null===e||void 0===t||null===t)return e;for(var r=arguments.length,i=Array(r>2?r-2:0),a=2;r>a;a++)i[a-2]=arguments[a];if(i.length){if(Array.isArray(e)){if(isNaN(t))throw Error('Must access array elements with a number, not "'+t+'".');var s=+t;if(e.length>s){var c=u.apply(void 0,[e&&e[s]].concat(o(i)));if(c!==e[s]){var l=[].concat(o(e));return l[s]=c,l}}return e}if(t in e){var d=u.apply(void 0,[e&&e[t]].concat(o(i)));return e[t]===d?e:f({},e,n({},t,d))}return e}if(Array.isArray(e)){if(isNaN(t))throw Error('Cannot delete non-numerical index from an array. Given: "'+t);var p=+t;if(e.length>p){var y=[].concat(o(e));return y.splice(p,1),y}return e}if(t in e){var v=f({},e);return delete v[t],v}return e}Object.defineProperty(t,"__esModule",{value:!0});var i=r(6),a=function(e){return e&&e.__esModule?e:{default:e}}(i),f=Object.assign||function(e){for(var t=1;arguments.length>t;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e};t.default=function(e,t){return u.apply(void 0,[e].concat(o((0,a.default)(t))))}},function(e,t,r){"use strict";function n(e){return e?Array.isArray(e)?e.map(function(e){return e.name}):Object.keys(e):[]}Object.defineProperty(t,"__esModule",{value:!0}),t.default=n},function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{default:e}}Object.defineProperty(t,"__esModule",{value:!0}),t.default=(0,n(r(85)).default)(n(r(0)).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 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)}Object.defineProperty(t,"__esModule",{value:!0});var a=Object.assign||function(e){for(var t=1;arguments.length>t;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},f=function(){function e(e,t){for(var r=0;t.length>r;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=r(2),c=r(1),l=n(c),d=r(5),p=n(d),y=r(86),v=n(y),m=r(28),b=n(m),h=r(0),_=n(h),g=r(4),O=n(g),S=function(e){return e?Array.isArray(e)||e._isFieldArray?void 0:Error('Invalid prop "names" supplied to <Fields/>. Must be either an array of strings or the fields array generated by FieldArray.'):Error('No "names" prop was specified <Fields/>')};t.default=function(e){var t=(0,v.default)(e),r=function(e){function r(e,t){o(this,r);var n=u(this,(r.__proto__||Object.getPrototypeOf(r)).call(this,e,t));if(!t._reduxForm)throw Error("Fields must be inside a component decorated with reduxForm()");return n}return i(r,e),f(r,[{key:"shouldComponentUpdate",value:function(e){return(0,b.default)(this,e)}},{key:"componentWillMount",value:function(){var e=S(this.props.names);if(e)throw e;var t=this.context,r=t._reduxForm.register;this.names.forEach(function(e){return r(e,"Field")})}},{key:"componentWillReceiveProps",value:function(e){if(!_.default.deepEqual(this.props.names,e.names)){var t=this.context,r=t._reduxForm,n=r.register,o=r.unregister;this.props.names.forEach(function(e){return o((0,O.default)(t,e))}),e.names.forEach(function(e){return n((0,O.default)(t,e),"Field")})}}},{key:"componentWillUnmount",value:function(){var e=this.context,t=e._reduxForm.unregister;this.props.names.forEach(function(r){return t((0,O.default)(e,r))})}},{key:"getRenderedComponent",value:function(){return(0,p.default)(this.props.withRef,"If you want to access getRenderedComponent(), you must specify a withRef prop to Fields"),this.refs.connected.getWrappedInstance().getRenderedComponent()}},{key:"render",value:function(){var e=this.context;return(0,s.createElement)(t,a({},this.props,{names:this.props.names.map(function(t){return(0,O.default)(e,t)}),_reduxForm:this.context._reduxForm,ref:"connected"}))}},{key:"names",get:function(){var e=this.context;return this.props.names.map(function(t){return(0,O.default)(e,t)})}},{key:"dirty",get:function(){return this.refs.connected.getWrappedInstance().isDirty()}},{key:"pristine",get:function(){return!this.dirty}},{key:"values",get:function(){return this.refs.connected&&this.refs.connected.getWrappedInstance().getValues()}}]),r}(s.Component);return r.propTypes={names:function(e,t){return S(e[t])},component:l.default.oneOfType([l.default.func,l.default.string]).isRequired,format:l.default.func,parse:l.default.func,props:l.default.object,withRef:l.default.bool},r.contextTypes={_reduxForm:l.default.object},r}},function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{default:e}}function o(e,t){var r={};for(var n in e)0>t.indexOf(n)&&Object.prototype.hasOwnProperty.call(e,n)&&(r[n]=e[n]);return r}function u(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function i(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)}Object.defineProperty(t,"__esModule",{value:!0});var f=Object.assign||function(e){for(var t=1;arguments.length>t;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;t.length>r;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(2),l=r(1),d=n(l),p=r(3),y=r(20),v=n(y),m=r(0),b=n(m),h=r(21),_=n(h),g=["_reduxForm"];t.default=function(e){var t=e.deepEqual,r=e.getIn,n=e.size,l=function(e,t){return b.default.getIn(e,t+"._error")||b.default.getIn(e,t)},y=function(e,t){var n=r(e,t);return n&&n._warning?n._warning:n},m=function(r){function l(e){u(this,l);var t=i(this,(l.__proto__||Object.getPrototypeOf(l)).call(this,e));return t.onChangeFns={},t.onFocusFns={},t.onBlurFns={},t.prepareEventHandlers=function(e){return e.names.forEach(function(e){t.onChangeFns[e]=function(r){return t.handleChange(e,r)},t.onFocusFns[e]=function(){return t.handleFocus(e)},t.onBlurFns[e]=function(r){return t.handleBlur(e,r)}})},t.handleChange=function(e,r){var n=t.props;(0,n.dispatch)(n._reduxForm.change(e,(0,_.default)(r,{name:e,parse:n.parse})))},t.handleFocus=function(e){var r=t.props;(0,r.dispatch)(r._reduxForm.focus(e))},t.handleBlur=function(e,r){var n=t.props,o=n.dispatch,u=n.parse,i=n._reduxForm,a=(0,_.default)(r,{name:e,parse:u});o(i.blur(e,a)),i.asyncValidate&&i.asyncValidate(e,a)},t.prepareEventHandlers(e),t}return a(l,r),s(l,[{key:"componentWillReceiveProps",value:function(e){var t=this;this.props.names===e.names||n(this.props.names)===n(e.names)&&!e.names.some(function(e){return!t.props._fields[e]})||this.prepareEventHandlers(e)}},{key:"shouldComponentUpdate",value:function(e){var r=this,n=Object.keys(e);return n.length!==Object.keys(this.props).length||n.some(function(n){return!~g.indexOf(n)&&!t(r.props[n],e[n])})}},{key:"isDirty",value:function(){var e=this.props._fields;return Object.keys(e).some(function(t){return e[t].dirty})}},{key:"getValues",value:function(){var e=this.props._fields;return Object.keys(e).reduce(function(t,r){return b.default.setIn(t,r,e[r].value)},{})}},{key:"getRenderedComponent",value:function(){return this.refs.renderedComponent}},{key:"render",value:function(){var t=this,r=this.props,n=r.component,u=r.withRef,i=r._fields,a=r._reduxForm,s=o(r,["component","withRef","_fields","_reduxForm"]),l=a.sectionPrefix,d=a.form,p=Object.keys(i).reduce(function(r,n){var u=i[n],a=(0,v.default)(e,n,f({},u,s,{form:d,onBlur:t.onBlurFns[n],onChange:t.onChangeFns[n],onFocus:t.onFocusFns[n]})),c=a.custom,p=o(a,["custom"]);r.custom=c;var y=l?n.replace(l+".",""):n;return b.default.setIn(r,y,p)},{}),y=p.custom,m=o(p,["custom"]);return u&&(m.ref="renderedComponent"),(0,c.createElement)(n,f({},m,y))}}]),l}(c.Component);return m.propTypes={component:d.default.oneOfType([d.default.func,d.default.string]).isRequired,_fields:d.default.object.isRequired,props:d.default.object},(0,p.connect)(function(e,t){var n=t.names,o=t._reduxForm,u=o.initialValues,i=o.getFormState,a=i(e);return{_fields:n.reduce(function(e,n){var o=r(a,"initial."+n),i=void 0!==o?o:u&&r(u,n),f=r(a,"values."+n),s=l(r(a,"syncErrors"),n),c=y(r(a,"syncWarnings"),n),d=r(a,"submitting"),p=f===i;return e[n]={asyncError:r(a,"asyncErrors."+n),asyncValidating:r(a,"asyncValidating")===n,dirty:!p,initial:i,pristine:p,state:r(a,"fields."+n),submitError:r(a,"submitErrors."+n),submitFailed:r(a,"submitFailed"),submitting:d,syncError:s,syncWarning:c,value:f,_value:t.value},e},{})}},void 0,void 0,{withRef:!0})(m)}},function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{default:e}}Object.defineProperty(t,"__esModule",{value:!0}),t.default=(0,n(r(88)).default)(n(r(0)).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 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 a(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 f=Object.assign||function(e){for(var t=1;arguments.length>t;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;t.length>r;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(2),l=r(1),d=n(l),p=r(5),y=n(p),v=r(89),m=n(v),b=r(4),h=n(b),_=function(e){return Array.isArray(e)?e:[e]},g=function(e,t){return e&&function(){for(var r=_(e),n=0;r.length>n;n++){var o=r[n].apply(r,arguments);if(o)return a({},t,o)}}};t.default=function(e){var t=(0,m.default)(e),r=function(e){function r(e,t){o(this,r);var n=u(this,(r.__proto__||Object.getPrototypeOf(r)).call(this,e,t));if(n.saveRef=function(e){return n.ref=e},!t._reduxForm)throw Error("FieldArray must be inside a component decorated with reduxForm()");return n}return i(r,e),s(r,[{key:"componentWillMount",value:function(){var e=this;this.context._reduxForm.register(this.name,"FieldArray",function(){return g(e.props.validate,"_error")},function(){return g(e.props.warn,"_warning")})}},{key:"componentWillReceiveProps",value:function(e){this.props.name!==e.name&&(this.context._reduxForm.unregister(this.name),this.context._reduxForm.register((0,h.default)(this.context,e.name),"FieldArray"))}},{key:"componentWillUnmount",value:function(){this.context._reduxForm.unregister(this.name)}},{key:"getRenderedComponent",value:function(){return(0,y.default)(this.props.withRef,"If you want to access getRenderedComponent(), you must specify a withRef prop to FieldArray"),this.ref.getWrappedInstance().getRenderedComponent()}},{key:"render",value:function(){return(0,c.createElement)(t,f({},this.props,{name:this.name,_reduxForm:this.context._reduxForm,ref:this.saveRef}))}},{key:"name",get:function(){return(0,h.default)(this.context,this.props.name)}},{key:"dirty",get:function(){return this.ref.getWrappedInstance().dirty}},{key:"pristine",get:function(){return this.ref.getWrappedInstance().pristine}},{key:"value",get:function(){return this.ref.getWrappedInstance().value}}]),r}(c.Component);return r.propTypes={name:d.default.string.isRequired,component:d.default.func.isRequired,props:d.default.object,validate:d.default.oneOfType([d.default.func,d.default.arrayOf(d.default.func)]),warn:d.default.oneOfType([d.default.func,d.default.arrayOf(d.default.func)]),withRef:d.default.bool},r.contextTypes={_reduxForm:d.default.object},r}},function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{default:e}}function o(e,t){var r={};for(var n in e)0>t.indexOf(n)&&Object.prototype.hasOwnProperty.call(e,n)&&(r[n]=e[n]);return r}function u(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function i(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)}Object.defineProperty(t,"__esModule",{value:!0});var f=r(29),s=n(f),c=function(){function e(e,t){for(var r=0;t.length>r;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}}(),l=r(2),d=r(1),p=n(d),y=r(3),v=r(31),m=r(96),b=n(m),h=r(0),_=n(h),g=["_reduxForm","value"];t.default=function(e){var t=e.deepEqual,r=e.getIn,n=e.size,f=function(e,t){return _.default.getIn(e,t+"._error")},d=function(e,t){return r(e,t+"._warning")},m=function(n){function f(){var e,t,n,o;u(this,f);for(var a=arguments.length,s=Array(a),c=0;a>c;c++)s[c]=arguments[c];return t=n=i(this,(e=f.__proto__||Object.getPrototypeOf(f)).call.apply(e,[this].concat(s))),n.getValue=function(e){return n.props.value&&r(n.props.value,e+"")},o=t,i(n,o)}return a(f,n),c(f,[{key:"shouldComponentUpdate",value:function(e){var r=this,n=this.props.value,o=e.value;if(n&&o&&(n.length!==o.length||e.rerenderOnEveryChange&&n.some(function(e,r){return!t(e,o[r])})))return!0;var u=Object.keys(e);return u.length!==Object.keys(this.props).length||u.some(function(n){return!~g.indexOf(n)&&!t(r.props[n],e[n])})}},{key:"getRenderedComponent",value:function(){return this.refs.renderedComponent}},{key:"render",value:function(){var t=this.props,r=t.component,n=t.withRef,u=t.name,i=t._reduxForm,a=o(t,["component","withRef","name","_reduxForm","validate","warn","rerenderOnEveryChange"]),f=(0,b.default)(e,u,i.form,i.sectionPrefix,this.getValue,a);return n&&(f.ref="renderedComponent"),(0,l.createElement)(r,f)}},{key:"dirty",get:function(){return this.props.dirty}},{key:"pristine",get:function(){return this.props.pristine}},{key:"value",get:function(){return this.props.value}}]),f}(l.Component);return m.propTypes={component:p.default.oneOfType([p.default.func,p.default.string]).isRequired,props:p.default.object,rerenderOnEveryChange:p.default.bool},m.defaultProps={rerenderOnEveryChange:!1},m.contextTypes={_reduxForm:p.default.object},(0,y.connect)(function(e,o){var u=o.name,i=o._reduxForm,a=i.initialValues,s=i.getFormState,c=s(e),l=r(c,"initial."+u)||a&&r(a,u),p=r(c,"values."+u),y=r(c,"submitting"),v=f(r(c,"syncErrors"),u),m=d(r(c,"syncWarnings"),u),b=t(p,l);return{asyncError:r(c,"asyncErrors."+u+"._error"),dirty:!b,pristine:b,state:r(c,"fields."+u),submitError:r(c,"submitErrors."+u+"._error"),submitFailed:r(c,"submitFailed"),submitting:y,syncError:v,syncWarning:m,value:p,length:n(p)}},function(e,t){var r=t.name,n=t._reduxForm;return(0,s.default)({arrayInsert:n.arrayInsert,arrayMove:n.arrayMove,arrayPop:n.arrayPop,arrayPush:n.arrayPush,arrayRemove:n.arrayRemove,arrayRemoveAll:n.arrayRemoveAll,arrayShift:n.arrayShift,arraySplice:n.arraySplice,arraySwap:n.arraySwap,arrayUnshift:n.arrayUnshift},function(t){return(0,v.bindActionCreators)(t.bind(null,r),e)})},void 0,{withRef:!0})(m)}},function(e,t,r){var n=r(91);e.exports=function(){try{var e=n(Object,"defineProperty");return e({},"",{}),e}catch(e){}}()},function(e,t){function r(e,t){return null==e?void 0:e[t]}e.exports=r},function(e,t,r){function n(e,t){return e&&o(e,t,u)}var o=r(30),u=r(94);e.exports=n},function(e,t){function r(e){return function(t,r,n){for(var o=-1,u=Object(t),i=n(t),a=i.length;a--;){var f=i[e?a:++o];if(!1===r(u[f],f,u))break}return t}}e.exports=r},function(e,t,r){e.exports=r(12)(Object.keys,Object)},function(e,t){function r(e){return e}e.exports=r},function(e,t,r){"use strict";function n(e,t){var r={};for(var n in e)0>t.indexOf(n)&&Object.prototype.hasOwnProperty.call(e,n)&&(r[n]=e[n]);return r}Object.defineProperty(t,"__esModule",{value:!0});var o=Object.assign||function(e){for(var t=1;arguments.length>t;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e};t.default=function(e,t,r,u,i,a){var f=e.getIn,s=a.arrayInsert,c=a.arrayMove,l=a.arrayPop,d=a.arrayPush,p=a.arrayRemove,y=a.arrayRemoveAll,v=a.arrayShift,m=a.arraySwap,b=a.arrayUnshift,h=a.asyncError,_=a.dirty,g=a.length,O=a.pristine,S=a.submitError,R=a.submitFailed,E=a.submitting,j=a.syncError,P=a.syncWarning,A=a.value,w=a.props,x=n(a,["arrayInsert","arrayMove","arrayPop","arrayPush","arrayRemove","arrayRemoveAll","arrayShift","arraySplice","arraySwap","arrayUnshift","asyncError","dirty","length","pristine","submitError","state","submitFailed","submitting","syncError","syncWarning","value","props"]),F=j||h||S,T=P,I=u?t.replace(u+".",""):t,M=o({fields:{_isFieldArray:!0,forEach:function(e){return(A||[]).forEach(function(t,r){return e(I+"["+r+"]",r,M.fields)})},get:i,getAll:function(){return A},insert:s,length:g,map:function(e){return(A||[]).map(function(t,r){return e(I+"["+r+"]",r,M.fields)})},move:c,name:t,pop:function(){return l(),f(A,g-1+"")},push:d,reduce:function(e,t){return(A||[]).reduce(function(t,r,n){return e(t,I+"["+n+"]",n,M.fields)},t)},remove:p,removeAll:y,shift:function(){return v(),f(A,"0")},swap:m,unshift:b},meta:{dirty:_,error:F,form:r,warning:T,invalid:!!F,pristine:O,submitting:E,submitFailed:R,valid:!F}},w,x);return M}},function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{default:e}}Object.defineProperty(t,"__esModule",{value:!0}),t.default=(0,n(r(98)).default)(n(r(0)).default)},function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{default:e}}Object.defineProperty(t,"__esModule",{value:!0});var o=r(5),u=n(o),i=r(0),a=n(i);t.default=function(e){var t=e.getIn;return function(e,r){(0,u.default)(e,"Form value must be specified");var n=r||function(e){return t(e,"form")};return function(r){for(var o=arguments.length,i=Array(o>1?o-1:0),f=1;o>f;f++)i[f-1]=arguments[f];return(0,u.default)(i.length,"No fields specified"),1===i.length?t(n(r),e+".values."+i[0]):i.reduce(function(o,u){var i=t(n(r),e+".values."+u);return void 0===i?o:a.default.setIn(o,u,i)},{})}}}},function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{default:e}}Object.defineProperty(t,"__esModule",{value:!0}),t.default=(0,n(r(100)).default)(n(r(0)).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 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 a(e){if(Array.isArray(e)){for(var t=0,r=Array(e.length);e.length>t;t++)r[t]=e[t];return r}return Array.from(e)}Object.defineProperty(t,"__esModule",{value:!0});var f=function(){function e(e,t){for(var r=0;t.length>r;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=r(2),c=n(s),l=r(1),d=n(l),p=r(3),y=r(4),v=n(y);t.default=function(e){var t=e.getIn;return function(e){for(var r=arguments.length,n=Array(r>1?r-1:0),s=1;r>s;s++)n[s-1]=arguments[s];var l=void 0;if("string"==typeof e)l=[e].concat(a(n)).map(function(e){return{prop:e,path:e}});else{var y=e;l=Object.keys(y).map(function(e){return{prop:e,path:y[e]}})}if(!l.length)throw Error("formValues(): You must specify values to get as formValues(name1, name2, ...) or formValues({propName1: propPath1, ...})");return function(e){var r=function(r){function n(r,i){o(this,n);var a=u(this,(n.__proto__||Object.getPrototypeOf(n)).call(this,r,i));if(!i._reduxForm)throw Error("formValues() must be used inside a React tree decorated with reduxForm()");var f=i._reduxForm.getValues;return a.Component=(0,p.connect)(function(e){var r={},n=f();return l.forEach(function(e){return r[e.prop]=t(n,(0,v.default)(i,e.path))}),r},function(){return{}})(e),a}return i(n,r),f(n,[{key:"render",value:function(){return c.default.createElement(this.Component,this.props)}}]),n}(c.default.Component);return r.contextTypes={_reduxForm:d.default.object},r}}}},function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{default:e}}Object.defineProperty(t,"__esModule",{value:!0}),t.default=(0,n(r(102)).default)(n(r(0)).default)},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.default=function(e){var t=e.getIn,r=e.keys;return function(e){return function(n){return r((e||function(e){return t(e,"form")})(n))}}}},function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{default:e}}Object.defineProperty(t,"__esModule",{value:!0}),t.default=(0,n(r(104)).default)(n(r(0)).default)},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.default=function(e){var t=e.getIn;return function(e,r){return function(n){return t((r||function(e){return t(e,"form")})(n),e+".values")}}}},function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{default:e}}Object.defineProperty(t,"__esModule",{value:!0}),t.default=(0,n(r(106)).default)(n(r(0)).default)},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.default=function(e){var t=e.getIn;return function(e,r){return function(n){return t((r||function(e){return t(e,"form")})(n),e+".initial")}}}},function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{default:e}}Object.defineProperty(t,"__esModule",{value:!0}),t.default=(0,n(r(108)).default)(n(r(0)).default)},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.default=function(e){var t=e.getIn;return function(e,r){return function(n){return t((r||function(e){return t(e,"form")})(n),e+".syncErrors")}}}},function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{default:e}}Object.defineProperty(t,"__esModule",{value:!0}),t.default=(0,n(r(110)).default)(n(r(0)).default)},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.default=function(e){var t=e.getIn;return function(e,r){return function(n){return t((r||function(e){return t(e,"form")})(n),e+".fields")}}}},function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{default:e}}Object.defineProperty(t,"__esModule",{value:!0}),t.default=(0,n(r(112)).default)(n(r(0)).default)},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.default=function(e){var t=e.getIn;return function(e,r){return function(n){return t((r||function(e){return t(e,"form")})(n),e+".asyncErrors")}}}},function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{default:e}}Object.defineProperty(t,"__esModule",{value:!0}),t.default=(0,n(r(114)).default)(n(r(0)).default)},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.default=function(e){var t=e.getIn;return function(e,r){return function(n){return t((r||function(e){return t(e,"form")})(n),e+".syncWarnings")}}}},function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{default:e}}Object.defineProperty(t,"__esModule",{value:!0}),t.default=(0,n(r(116)).default)(n(r(0)).default)},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.default=function(e){var t=e.getIn;return function(e,r){return function(n){return t((r||function(e){return t(e,"form")})(n),e+".submitErrors")}}}},function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{default:e}}Object.defineProperty(t,"__esModule",{value:!0}),t.default=(0,n(r(118)).default)(n(r(0)).default)},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var n=r(32),o=function(e){return e&&e.__esModule?e:{default:e}}(n);t.default=function(e){return function(t,r){var n=(0,o.default)(e)(t,r);return function(e){return!n(e)}}}},function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{default:e}}Object.defineProperty(t,"__esModule",{value:!0}),t.default=(0,n(r(120)).default)(n(r(0)).default)},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var n=r(14),o=function(e){return e&&e.__esModule?e:{default:e}}(n);t.default=function(e){return function(t,r){var n=(0,o.default)(e)(t,r);return function(e){return!n(e)}}}},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var n=function(e,t){switch(t){case"Field":return[e,e+"._error"];case"FieldArray":return[e+"._error"];default:throw Error("Unknown field type")}};t.default=function(e){var t=e.getIn;return function(e,r,o,u){if(!r&&!o&&!u)return!1;var i=t(e,"name"),a=t(e,"type");return n(i,a).some(function(e){return t(r,e)||t(o,e)||t(u,e)})}}},function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{default:e}}Object.defineProperty(t,"__esModule",{value:!0}),t.default=(0,n(r(32)).default)(n(r(0)).default)},function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{default:e}}Object.defineProperty(t,"__esModule",{value:!0}),t.default=(0,n(r(14)).default)(n(r(0)).default)},function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{default:e}}Object.defineProperty(t,"__esModule",{value:!0}),t.default=(0,n(r(125)).default)(n(r(0)).default)},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.default=function(e){var t=e.getIn;return function(e,r){return function(n){return!!t((r||function(e){return t(e,"form")})(n),e+".submitting")}}}},function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{default:e}}Object.defineProperty(t,"__esModule",{value:!0}),t.default=(0,n(r(127)).default)(n(r(0)).default)},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.default=function(e){var t=e.getIn;return function(e,r){return function(n){return!!t((r||function(e){return t(e,"form")})(n),e+".submitSucceeded")}}}},function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{default:e}}Object.defineProperty(t,"__esModule",{value:!0}),t.default=(0,n(r(129)).default)(n(r(0)).default)},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.default=function(e){var t=e.getIn;return function(e,r){return function(n){return!!t((r||function(e){return t(e,"form")})(n),e+".submitFailed")}}}},function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{default:e}}Object.defineProperty(t,"__esModule",{value:!0}),t.default=(0,n(r(131)).default)(n(r(0)).default)},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 i(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 f(e,t){var r={};for(var n in e)0>t.indexOf(n)&&Object.prototype.hasOwnProperty.call(e,n)&&(r[n]=e[n]);return r}Object.defineProperty(t,"__esModule",{value:!0});var s=r(132),c=n(s),l=r(29),d=n(l),p=function(){function e(e,t){for(var r=0;t.length>r;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}}(),y=Object.assign||function(e){for(var t=1;arguments.length>t;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},v="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},m=r(160),b=n(m),h=r(15),_=n(h),g=r(1),O=n(g),S=r(2),R=r(3),E=r(31),j=r(39),P=n(j),A=r(161),w=n(A),x=r(17),F=n(x),T=r(18),I=n(T),M=r(40),C=n(M),k=r(162),V=n(k),U=r(163),N=n(U),q=r(164),D=n(q),W=r(14),L=n(W),Y=r(0),B=n(Y),z=r(165),H=n(z),G=function(e){return!(!e||!e.prototype||"object"!==v(e.prototype.isReactComponent))},K=P.default.arrayInsert,J=P.default.arrayMove,Z=P.default.arrayPop,$=P.default.arrayPush,Q=P.default.arrayRemove,X=P.default.arrayRemoveAll,ee=P.default.arrayShift,te=P.default.arraySplice,re=P.default.arraySwap,ne=P.default.arrayUnshift,oe=P.default.blur,ue=P.default.change,ie=P.default.focus,ae=f(P.default,["arrayInsert","arrayMove","arrayPop","arrayPush","arrayRemove","arrayRemoveAll","arrayShift","arraySplice","arraySwap","arrayUnshift","blur","change","focus"]),fe={arrayInsert:K,arrayMove:J,arrayPop:Z,arrayPush:$,arrayRemove:Q,arrayRemoveAll:X,arrayShift:ee,arraySplice:te,arraySwap:re,arrayUnshift:ne},se=[].concat(function(e){if(Array.isArray(e)){for(var t=0,r=Array(e.length);e.length>t;t++)r[t]=e[t];return r}return Array.from(e)}(Object.keys(P.default)),["array","asyncErrors","initialValues","syncErrors","syncWarnings","values","registeredFields"]),ce=function(e){if(!e||"function"!=typeof e)throw Error("You must either pass handleSubmit() an onSubmit function or pass onSubmit as a prop");return e};t.default=function(e){var t=e.deepEqual,r=e.empty,n=e.getIn,s=e.setIn,l=e.keys,v=e.fromJS,m=(0,L.default)(e);return function(h){var g=y({touchOnBlur:!0,touchOnChange:!1,persistentSubmitErrors:!1,destroyOnUnmount:!0,shouldAsyncValidate:F.default,shouldValidate:I.default,enableReinitialize:!1,keepDirtyOnReinitialize:!1,getFormState:function(e){return n(e,"form")},pure:!0,forceUnregisterOnUnmount:!1},h);return function(h){var j=function(r){function d(){var t,r,o,a;u(this,d);for(var f=arguments.length,c=Array(f),p=0;f>p;p++)c[p]=arguments[p];return r=o=i(this,(t=d.__proto__||Object.getPrototypeOf(d)).call.apply(t,[this].concat(c))),o.destroyed=!1,o.fieldValidators={},o.lastFieldValidatorKeys=[],o.fieldWarners={},o.lastFieldWarnerKeys=[],o.innerOnSubmit=void 0,o.submitPromise=void 0,o.getValues=function(){return o.props.values},o.isValid=function(){return o.props.valid},o.isPristine=function(){return o.props.pristine},o.register=function(e,t,r,n){o.props.registerField(e,t),r&&(o.fieldValidators[e]=r),n&&(o.fieldWarners[e]=n)},o.unregister=function(e){o.destroyed||(o.props.destroyOnUnmount||o.props.forceUnregisterOnUnmount?(o.props.unregisterField(e),delete o.fieldValidators[e],delete o.fieldWarners[e]):o.props.unregisterField(e,!1))},o.getFieldList=function(e){var t=o.props.registeredFields,r=[];if(!t)return r;var u=l(t);return e&&e.excludeFieldArray&&(u=u.filter(function(e){return"FieldArray"!==n(t,"['"+e+"'].type")})),v(u.reduce(function(e,t){return e.push(t),e},r))},o.getValidators=function(){var e={};return Object.keys(o.fieldValidators).forEach(function(t){var r=o.fieldValidators[t]();r&&(e[t]=r)}),e},o.generateValidator=function(){var t=o.getValidators();return Object.keys(t).length?(0,N.default)(t,e):void 0},o.getWarners=function(){var e={};return Object.keys(o.fieldWarners).forEach(function(t){var r=o.fieldWarners[t]();r&&(e[t]=r)}),e},o.generateWarner=function(){var t=o.getWarners();return Object.keys(t).length?(0,N.default)(t,e):void 0},o.asyncValidate=function(e,t){var r=o.props,u=r.asyncBlurFields,i=r.asyncErrors,a=r.asyncValidate,f=r.dispatch,c=r.initialized,l=r.pristine,d=r.shouldAsyncValidate,p=r.startAsyncValidation,y=r.stopAsyncValidation,v=r.syncErrors,m=r.values,b=!e;if(a){var h=b?m:s(m,e,t),_=b||!n(v,e);if((!b&&(!u||~u.indexOf(e.replace(/\[[0-9]+\]/g,"[]")))||b)&&d({asyncErrors:i,initialized:c,trigger:b?"submit":"blur",blurredField:e,pristine:l,syncValidationPasses:_}))return(0,w.default)(function(){return a(h,f,o.props,e)},p,y,e)}},o.submitCompleted=function(e){return delete o.submitPromise,e},o.submitFailed=function(e){throw delete o.submitPromise,e},o.listenToSubmit=function(e){return(0,_.default)(e)?(o.submitPromise=e,e.then(o.submitCompleted,o.submitFailed)):e},o.submit=function(e){var t=o.props,r=t.onSubmit,n=t.blur,u=t.change,i=t.dispatch;return e&&!(0,C.default)(e)?(0,V.default)(function(){return!o.submitPromise&&o.listenToSubmit((0,D.default)(ce(e),y({},o.props,(0,E.bindActionCreators)({blur:n,change:u},i)),o.props.validExceptSubmit,o.asyncValidate,o.getFieldList({excludeFieldArray:!0})))}):o.submitPromise?void 0:o.innerOnSubmit&&o.innerOnSubmit!==o.submit?o.innerOnSubmit():o.listenToSubmit((0,D.default)(ce(r),y({},o.props,(0,E.bindActionCreators)({blur:n,change:u},i)),o.props.validExceptSubmit,o.asyncValidate,o.getFieldList({excludeFieldArray:!0})))},o.reset=function(){return o.props.reset()},a=r,i(o,a)}return a(d,r),p(d,[{key:"getChildContext",value:function(){var e=this;return{_reduxForm:y({},this.props,{getFormState:function(t){return n(e.props.getFormState(t),e.props.form)},asyncValidate:this.asyncValidate,getValues:this.getValues,sectionPrefix:void 0,register:this.register,unregister:this.unregister,registerInnerOnSubmit:function(t){return e.innerOnSubmit=t}})}}},{key:"initIfNeeded",value:function(e){var r=this.props.enableReinitialize;if(e){if((r||!e.initialized)&&!t(this.props.initialValues,e.initialValues)){var n=e.initialized&&this.props.keepDirtyOnReinitialize;this.props.initialize(e.initialValues,n,{lastInitialValues:this.props.initialValues})}}else!this.props.initialValues||this.props.initialized&&!r||this.props.initialize(this.props.initialValues,this.props.keepDirtyOnReinitialize)}},{key:"updateSyncErrorsIfNeeded",value:function(e,t,r){var n=this.props,o=n.error,u=n.updateSyncErrors,i=!(r&&Object.keys(r).length||o),a=!(e&&Object.keys(e).length||t);i&&a||B.default.deepEqual(r,e)&&B.default.deepEqual(o,t)||u(e,t)}},{key:"clearSubmitPromiseIfNeeded",value:function(e){var t=this.props.submitting;this.submitPromise&&t&&!e.submitting&&delete this.submitPromise}},{key:"submitIfNeeded",value:function(e){var t=this.props,r=t.clearSubmit;!t.triggerSubmit&&e.triggerSubmit&&(r(),this.submit())}},{key:"validateIfNeeded",value:function(t){var r=this.props,n=r.shouldValidate,o=r.validate,u=r.values,i=this.generateValidator();if(o||i){var a=void 0===t,s=Object.keys(this.getValidators());if(n({values:u,nextProps:t,props:this.props,initialRender:a,lastFieldValidatorKeys:this.lastFieldValidatorKeys,fieldValidatorKeys:s,structure:e})){var l=a||!t?this.props:t,d=(0,c.default)(o?o(l.values,l)||{}:{},i?i(l.values,l)||{}:{}),p=d._error,y=f(d,["_error"]);this.lastFieldValidatorKeys=s,this.updateSyncErrorsIfNeeded(y,p,l.syncErrors)}}}},{key:"updateSyncWarningsIfNeeded",value:function(e,t,r){var n=this.props,o=n.warning,u=n.syncWarnings,i=n.updateSyncWarnings,a=!(u&&Object.keys(u).length||o),f=!(e&&Object.keys(e).length||t);a&&f||B.default.deepEqual(r,e)&&B.default.deepEqual(o,t)||i(e,t)}},{key:"warnIfNeeded",value:function(t){var r=this.props,n=r.shouldValidate,o=r.warn,u=r.values,i=this.generateWarner();if(o||i){var a=void 0===t,s=Object.keys(this.getWarners());if(n({values:u,nextProps:t,props:this.props,initialRender:a,lastFieldValidatorKeys:this.lastFieldWarnerKeys,fieldValidatorKeys:s,structure:e})){var l=a||!t?this.props:t,d=(0,c.default)(o?o(l.values,l):{},i?i(l.values,l):{}),p=d._warning,y=f(d,["_warning"]);this.lastFieldWarnerKeys=s,this.updateSyncWarningsIfNeeded(y,p,l.syncWarnings)}}}},{key:"componentWillMount",value:function(){this.initIfNeeded(),this.validateIfNeeded(),this.warnIfNeeded()}},{key:"componentWillReceiveProps",value:function(e){this.initIfNeeded(e),this.validateIfNeeded(e),this.warnIfNeeded(e),this.clearSubmitPromiseIfNeeded(e),this.submitIfNeeded(e);var r=e.onChange,n=e.values,o=e.dispatch;r&&!t(n,this.props.values)&&r(n,o,e)}},{key:"shouldComponentUpdate",value:function(e){var r=this;if(!this.props.pure)return!0;var n=g.immutableProps,o=void 0===n?[]:n;return Object.keys(e).some(function(n){return~o.indexOf(n)?r.props[n]!==e[n]:!~se.indexOf(n)&&!t(r.props[n],e[n])})}},{key:"componentWillUnmount",value:function(){var e=this.props,t=e.destroyOnUnmount,r=e.destroy;t&&(this.destroyed=!0,r())}},{key:"render",value:function(){var e=this.props,t=e.anyTouched,r=e.asyncValidating,n=e.blur,u=e.change,i=e.clearSubmit,a=e.destroy,s=e.dirty,c=e.dispatch,l=e.error,d=e.form,p=e.initialize,v=e.initialized,m=e.initialValues,b=e.invalid,_=e.pristine,g=e.propNamespace,O=e.reset,R=e.submitting,j=e.submitFailed,P=e.submitSucceeded,A=e.touch,w=e.untouch,x=e.valid,F=e.warning,T=f(e,["anyTouched","arrayInsert","arrayMove","arrayPop","arrayPush","arrayRemove","arrayRemoveAll","arrayShift","arraySplice","arraySwap","arrayUnshift","asyncErrors","asyncValidate","asyncValidating","blur","change","clearSubmit","destroy","destroyOnUnmount","forceUnregisterOnUnmount","dirty","dispatch","enableReinitialize","error","focus","form","getFormState","initialize","initialized","initialValues","invalid","keepDirtyOnReinitialize","pristine","propNamespace","registeredFields","registerField","reset","setSubmitFailed","setSubmitSucceeded","shouldAsyncValidate","shouldValidate","startAsyncValidation","startSubmit","stopAsyncValidation","stopSubmit","submitting","submitFailed","submitSucceeded","touch","touchOnBlur","touchOnChange","persistentSubmitErrors","syncErrors","syncWarnings","unregisterField","untouch","updateSyncErrors","updateSyncWarnings","valid","validExceptSubmit","values","warning"]),I=y({anyTouched:t,asyncValidate:this.asyncValidate,asyncValidating:r},(0,E.bindActionCreators)({blur:n,change:u},c),{clearSubmit:i,destroy:a,dirty:s,dispatch:c,error:l,form:d,handleSubmit:this.submit,initialize:p,initialized:v,initialValues:m,invalid:b,pristine:_,reset:O,submitting:R,submitFailed:j,submitSucceeded:P,touch:A,untouch:w,valid:x,warning:F}),M=y({},g?o({},g,I):I,T);return G(h)&&(M.ref="wrapped"),(0,S.createElement)(h,M)}}]),d}(S.Component);j.displayName="Form("+(0,H.default)(h)+")",j.WrappedComponent=h,j.childContextTypes={_reduxForm:O.default.object.isRequired},j.propTypes={destroyOnUnmount:O.default.bool,forceUnregisterOnUnmount:O.default.bool,form:O.default.string.isRequired,initialValues:O.default.oneOfType([O.default.array,O.default.object]),getFormState:O.default.func,onSubmitFail:O.default.func,onSubmitSuccess:O.default.func,propNamespace:O.default.string,validate:O.default.func,warn:O.default.func,touchOnBlur:O.default.bool,touchOnChange:O.default.bool,triggerSubmit:O.default.bool,persistentSubmitErrors:O.default.bool,registeredFields:O.default.any};var P=(0,R.connect)(function(e,o){var u=o.form,i=o.getFormState,a=o.initialValues,f=o.enableReinitialize,s=o.keepDirtyOnReinitialize,c=n(i(e)||r,u)||r,l=n(c,"initial"),d=!!l,p=f&&d&&!t(a,l),y=p&&!s,v=a||l||r;p&&(v=l||r);var b=n(c,"values")||v;y&&(b=v);var h=y||t(v,b),_=n(c,"asyncErrors"),g=n(c,"syncErrors")||r,O=n(c,"syncWarnings")||r,S=n(c,"registeredFields"),R=m(u,i,!1)(e),E=m(u,i,!0)(e),j=!!n(c,"anyTouched"),P=!!n(c,"submitting"),A=!!n(c,"submitFailed"),w=!!n(c,"submitSucceeded"),x=n(c,"error"),F=n(c,"warning"),T=n(c,"triggerSubmit");return{anyTouched:j,asyncErrors:_,asyncValidating:n(c,"asyncValidating")||!1,dirty:!h,error:x,initialized:d,invalid:!R,pristine:h,registeredFields:S,submitting:P,submitFailed:A,submitSucceeded:w,syncErrors:g,syncWarnings:O,triggerSubmit:T,values:b,valid:R,validExceptSubmit:E,warning:F}},function(e,t){var r=function(e){return e.bind(null,t.form)},n=(0,d.default)(ae,r),o=(0,d.default)(fe,r),u=function(e,r){return oe(t.form,e,r,!!t.touchOnBlur)},i=function(e,r){return ue(t.form,e,r,!!t.touchOnChange,!!t.persistentSubmitErrors)},a=r(ie),f=(0,E.bindActionCreators)(n,e),s={insert:(0,E.bindActionCreators)(o.arrayInsert,e),move:(0,E.bindActionCreators)(o.arrayMove,e),pop:(0,E.bindActionCreators)(o.arrayPop,e),push:(0,E.bindActionCreators)(o.arrayPush,e),remove:(0,E.bindActionCreators)(o.arrayRemove,e),removeAll:(0,E.bindActionCreators)(o.arrayRemoveAll,e),shift:(0,E.bindActionCreators)(o.arrayShift,e),splice:(0,E.bindActionCreators)(o.arraySplice,e),swap:(0,E.bindActionCreators)(o.arraySwap,e),unshift:(0,E.bindActionCreators)(o.arrayUnshift,e)},c=y({},f,o,{blur:u,change:i,array:s,focus:a,dispatch:e});return function(){return c}},void 0,{withRef:!0}),A=(0,b.default)(P(j),h);return A.defaultProps=g,function(e){function t(){return u(this,t),i(this,(t.__proto__||Object.getPrototypeOf(t)).apply(this,arguments))}return a(t,e),p(t,[{key:"submit",value:function(){return this.refs.wrapped.getWrappedInstance().submit()}},{key:"reset",value:function(){return this.refs.wrapped.getWrappedInstance().reset()}},{key:"render",value:function(){var e=this.props,t=e.initialValues,r=f(e,["initialValues"]);return(0,S.createElement)(A,y({},r,{ref:"wrapped",initialValues:v(t)}))}},{key:"valid",get:function(){return this.refs.wrapped.getWrappedInstance().isValid()}},{key:"invalid",get:function(){return!this.valid}},{key:"pristine",get:function(){return this.refs.wrapped.getWrappedInstance().isPristine()}},{key:"dirty",get:function(){return!this.pristine}},{key:"values",get:function(){return this.refs.wrapped.getWrappedInstance().getValues()}},{key:"fieldList",get:function(){return this.refs.wrapped.getWrappedInstance().getFieldList()}},{key:"wrappedInstance",get:function(){return this.refs.wrapped.getWrappedInstance().refs.wrapped}}]),t}(S.Component)}}}},function(e,t,r){var n=r(133);e.exports=r(153)(function(e,t,r){n(e,t,r)})},function(e,t,r){function n(e,t,r,c,l){e!==t&&i(t,function(i,s){if(f(i))l||(l=new o),a(e,t,s,r,n,c,l);else{var d=c?c(e[s],i,s+"",e,t,l):void 0;void 0===d&&(d=i),u(e,s,d)}},s)}var o=r(25),u=r(33),i=r(30),a=r(134),f=r(10),s=r(38);e.exports=n},function(e,t,r){function n(e,t,r,n,h,_,g){var O=e[r],S=t[r],R=g.get(S);if(R)return void o(e,r,R);var E=_?_(O,S,r+"",e,t,g):void 0,j=void 0===E;if(j){var P=c(S),A=!P&&d(S),w=!P&&!A&&m(S);E=S,P||A||w?c(O)?E=O:l(O)?E=a(O):A?(j=!1,E=u(S,!0)):w?(j=!1,E=i(S,!0)):E=[]:v(S)||s(S)?(E=O,s(O)?E=b(O):(!y(O)||n&&p(O))&&(E=f(S))):j=!1}j&&(g.set(S,E),h(E,S,n,_,g),g.delete(S)),o(e,r,E)}var o=r(33),u=r(135),i=r(139),a=r(23),f=r(142),s=r(145),c=r(7),l=r(146),d=r(26),p=r(36),y=r(10),v=r(149),m=r(27),b=r(150);e.exports=n},function(e,t,r){(function(e){function n(e,t){if(t)return e.slice();var r=e.length,n=s?s(r):new e.constructor(r);return e.copy(n),n}var o=r(34),u="object"==typeof t&&t&&!t.nodeType&&t,i=u&&"object"==typeof e&&e&&!e.nodeType&&e,a=i&&i.exports===u,f=a?o.Buffer:void 0,s=f?f.allocUnsafe:void 0;e.exports=n}).call(t,r(136)(e))},function(e,t){e.exports=function(e){return e.webpackPolyfill||(e.deprecate=function(){},e.paths=[],e.children||(e.children=[]),Object.defineProperty(e,"loaded",{enumerable:!0,get:function(){return e.l}}),Object.defineProperty(e,"id",{enumerable:!0,get:function(){return e.i}}),e.webpackPolyfill=1),e}},function(e,t,r){(function(t){var r="object"==typeof t&&t&&t.Object===Object&&t;e.exports=r}).call(t,r(138))},function(e,t){var r;r=function(){return this}();try{r=r||Function("return this")()||(0,eval)("this")}catch(e){"object"==typeof window&&(r=window)}e.exports=r},function(e,t,r){function n(e,t){return new e.constructor(t?o(e.buffer):e.buffer,e.byteOffset,e.length)}var o=r(140);e.exports=n},function(e,t,r){function n(e){var t=new e.constructor(e.byteLength);return new o(t).set(new o(e)),t}var o=r(141);e.exports=n},function(e,t,r){e.exports=r(34).Uint8Array},function(e,t,r){function n(e){return"function"!=typeof e.constructor||i(e)?{}:o(u(e))}var o=r(143),u=r(35),i=r(144);e.exports=n},function(e,t,r){var n=r(10),o=Object.create;e.exports=function(){function e(){}return function(t){if(!n(t))return{};if(o)return o(t);e.prototype=t;var r=new e;return e.prototype=void 0,r}}()},function(e,t){function r(){return!1}e.exports=r},function(e,t){function r(){return!1}e.exports=r},function(e,t,r){function n(e){return u(e)&&o(e)}var o=r(147),u=r(13);e.exports=n},function(e,t,r){function n(e){return null!=e&&u(e.length)&&!o(e)}var o=r(36),u=r(148);e.exports=n},function(e,t){function r(e){return"number"==typeof e&&e>-1&&e%1==0&&n>=e}var n=9007199254740991;e.exports=r},function(e,t,r){function n(e){if(!i(e)||o(e)!=a)return!1;var t=u(e);if(null===t)return!0;var r=l.call(t,"constructor")&&t.constructor;return"function"==typeof r&&r instanceof r&&c.call(r)==d}var o=r(37),u=r(35),i=r(13),a="[object Object]",f=Function.prototype,s=Object.prototype,c=f.toString,l=s.hasOwnProperty,d=c.call(Object);e.exports=n},function(e,t,r){function n(e){return o(e,u(e))}var o=r(151),u=r(38);e.exports=n},function(e,t,r){function n(e,t,r,n){var i=!r;r||(r={});for(var a=-1,f=t.length;++a<f;){var s=t[a],c=n?n(r[s],e[s],s,r,e):void 0;void 0===c&&(c=e[s]),i?u(r,s,c):o(r,s,c)}return r}var o=r(152),u=r(9);e.exports=n},function(e,t,r){function n(e,t,r){var n=e[t];a.call(e,t)&&u(n,r)&&(void 0!==r||t in e)||o(e,t,r)}var o=r(9),u=r(11),i=Object.prototype,a=i.hasOwnProperty;e.exports=n},function(e,t,r){function n(e){return o(function(t,r){var n=-1,o=r.length,i=o>1?r[o-1]:void 0,a=o>2?r[2]:void 0;for(i=e.length>3&&"function"==typeof i?(o--,i):void 0,a&&u(r[0],r[1],a)&&(i=3>o?void 0:i,o=1),t=Object(t);++n<o;){var f=r[n];f&&e(t,f,n,i)}return t})}var o=r(154),u=r(159);e.exports=n},function(e,t,r){function n(e,t){return i(u(e,t,o),e+"")}var o=r(155),u=r(156),i=r(158);e.exports=n},function(e,t){function r(e){return e}e.exports=r},function(e,t,r){function n(e,t,r){return t=u(void 0===t?e.length-1:t,0),function(){for(var n=arguments,i=-1,a=u(n.length-t,0),f=Array(a);++i<a;)f[i]=n[t+i];i=-1;for(var s=Array(t+1);++i<t;)s[i]=n[i];return s[t]=r(f),o(e,this,s)}}var o=r(157),u=Math.max;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){function r(e){return e}e.exports=r},function(e,t){function r(){return!1}e.exports=r},function(e,t,r){"use strict";var n={childContextTypes:!0,contextTypes:!0,defaultProps:!0,displayName:!0,getDefaultProps:!0,mixins:!0,propTypes:!0,type:!0},o=Object.getOwnPropertySymbols,u=Object.prototype.hasOwnProperty,i=Object.prototype.propertyIsEnumerable,a=Object.getPrototypeOf,f=a&&a(Object);e.exports=function e(t,r,s){if("string"!=typeof r){if(f){var c=a(r);c&&c!==f&&e(t,c,s)}for(var l in r)if(!(n[l]||s&&s[l])&&u.call(r,l))try{t[l]=r[l]}catch(e){}if(o)for(var d=o(r),p=0;d.length>p;p++)if(!(n[d[p]]||s&&s[d[p]])&&i.call(r,d[p]))try{t[d[p]]=r[d[p]]}catch(e){}return t}return t}},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var n=r(15),o=function(e){return e&&e.__esModule?e:{default:e}}(n);t.default=function(e,t,r,n){t(n);var u=e();if(!(0,o.default)(u))throw Error("asyncValidate function passed to reduxForm must return a promise");var i=function(e){return function(t){if(t&&Object.keys(t).length)return r(t),t;if(e)throw r(),Error("Asynchronous validation promise was rejected without errors.");return r(),Promise.resolve()}};return u.then(i(!1),i(!0))}},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var n=r(40),o=function(e){return e&&e.__esModule?e:{default:e}}(n);t.default=function(e){return function(t){for(var r=arguments.length,n=Array(r>1?r-1:0),u=1;r>u;u++)n[u-1]=arguments[u];return(0,o.default)(t)?e.apply(void 0,n):e.apply(void 0,[t].concat(n))}}},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var n=r(0),o=function(e){return e&&e.__esModule?e:{default:e}}(n),u=function(e){return Array.isArray(e)?e:[e]},i=function(e,t,r,n){for(var o=u(n),i=0;o.length>i;i++){var a=o[i](e,t,r);if(a)return a}};t.default=function(e,t){var r=t.getIn;return function(t,n){var u={};return Object.keys(e).forEach(function(a){var f=r(t,a),s=i(f,t,n,e[a]);s&&(u=o.default.setIn(u,a,s))}),u}}},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);e.length>t;t++)r[t]=e[t];return r}return Array.from(e)}Object.defineProperty(t,"__esModule",{value:!0});var u=r(15),i=n(u),a=r(19),f=n(a);t.default=function(e,t,r,n,u){var a=t.dispatch,s=t.onSubmitFail,c=t.onSubmitSuccess,l=t.startSubmit,d=t.stopSubmit,p=t.setSubmitFailed,y=t.setSubmitSucceeded,v=t.syncErrors,m=t.touch,b=t.values,h=t.persistentSubmitErrors;if(m.apply(void 0,o(u)),r||h){var _=function(){var r=void 0;try{r=e(b,a,t)}catch(e){var n=e instanceof f.default?e.errors:void 0;if(d(n),p.apply(void 0,o(u)),s&&s(n,a,e,t),n||s)return n;throw e}return(0,i.default)(r)?(l(),r.then(function(e){return d(),y(),c&&c(e,a,t),e},function(e){var r=e instanceof f.default?e.errors:void 0;if(d(r),p.apply(void 0,o(u)),s&&s(r,a,e,t),r||s)return r;throw e})):(y(),c&&c(r,a,t),r)},g=n&&n();return g?g.then(function(e){if(e)throw e;return _()}).catch(function(e){return p.apply(void 0,o(u)),s&&s(e,a,null,t),Promise.reject(e)}):_()}return p.apply(void 0,o(u)),s&&s(v,a,null,t),v}},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.default=function(e){return e.displayName||e.name||"Component"}},function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{default:e}}Object.defineProperty(t,"__esModule",{value:!0}),t.default=(0,n(r(167)).default)(n(r(0)).default)},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){var r={};for(var n in e)0>t.indexOf(n)&&Object.prototype.hasOwnProperty.call(e,n)&&(r[n]=e[n]);return r}function i(e){function t(e){return e.plugin=function(e){var r=this;return t(function(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:i,n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{type:"NONE"};return Object.keys(e).reduce(function(r,o){var u=c(r,o),i=e[o](u,n,c(t,o));return i===u?r:p(r,o,i)},r(t,n))})},e}var r,n=e.deepEqual,i=e.empty,f=e.forEach,c=e.getIn,p=e.setIn,y=e.deleteIn,v=e.fromJS,m=e.keys,b=e.size,h=e.some,_=e.splice,g=(0,s.default)(e),O=function(e,t,r,n,o,u,i){var a=c(e,t+"."+r);return a||i?p(e,t+"."+r,_(a,n,o,u)):e},S=function(e,t,r,n,o,u,i){var a=c(e,t),f=l.default.getIn(a,r);return f||i?p(e,t,l.default.setIn(a,r,l.default.splice(f,n,o,u))):e},R=["values","fields","submitErrors","asyncErrors"],E=function(e,t,r,n,o){var u=e,a=null!=o?i:void 0;return u=O(u,"values",t,r,n,o,!0),u=O(u,"fields",t,r,n,a),u=S(u,"syncErrors",t,r,n,void 0),u=S(u,"syncWarnings",t,r,n,void 0),u=O(u,"submitErrors",t,r,n,void 0),u=O(u,"asyncErrors",t,r,n,void 0)},j=(r={},o(r,a.ARRAY_INSERT,function(e,t){var r=t.meta;return E(e,r.field,r.index,0,t.payload)}),o(r,a.ARRAY_MOVE,function(e,t){var r=t.meta,n=r.field,o=r.from,u=r.to,i=c(e,"values."+n),a=i?b(i):0,f=e;return a&&R.forEach(function(e){var t=e+"."+n;if(c(f,t)){var r=c(f,t+"["+o+"]");f=p(f,t,_(c(f,t),o,1)),f=p(f,t,_(c(f,t),u,0,r))}}),f}),o(r,a.ARRAY_POP,function(e,t){var r=t.meta.field,n=c(e,"values."+r),o=n?b(n):0;return o?E(e,r,o-1,1):e}),o(r,a.ARRAY_PUSH,function(e,t){var r=t.meta.field,n=t.payload,o=c(e,"values."+r),u=o?b(o):0;return E(e,r,u,0,n)}),o(r,a.ARRAY_REMOVE,function(e,t){var r=t.meta;return E(e,r.field,r.index,1)}),o(r,a.ARRAY_REMOVE_ALL,function(e,t){var r=t.meta.field,n=c(e,"values."+r),o=n?b(n):0;return o?E(e,r,0,o):e}),o(r,a.ARRAY_SHIFT,function(e,t){return E(e,t.meta.field,0,1)}),o(r,a.ARRAY_SPLICE,function(e,t){var r=t.meta;return E(e,r.field,r.index,r.removeNum,t.payload)}),o(r,a.ARRAY_SWAP,function(e,t){var r=t.meta,n=r.field,o=r.indexA,u=r.indexB,i=e;return R.forEach(function(e){var t=c(i,e+"."+n+"["+o+"]"),r=c(i,e+"."+n+"["+u+"]");void 0===t&&void 0===r||(i=p(i,e+"."+n+"["+o+"]",r),i=p(i,e+"."+n+"["+u+"]",t))}),i}),o(r,a.ARRAY_UNSHIFT,function(e,t){return E(e,t.meta.field,0,0,t.payload)}),o(r,a.AUTOFILL,function(e,t){var r=t.meta.field,n=t.payload,o=e;return o=g(o,"asyncErrors."+r),o=g(o,"submitErrors."+r),o=p(o,"fields."+r+".autofilled",!0),o=p(o,"values."+r,n)}),o(r,a.BLUR,function(e,t){var r=t.meta,n=r.field,o=r.touch,u=t.payload,i=e;return void 0===c(i,"initial."+n)&&""===u?i=g(i,"values."+n):void 0!==u&&(i=p(i,"values."+n,u)),n===c(i,"active")&&(i=y(i,"active")),i=y(i,"fields."+n+".active"),o&&(i=p(i,"fields."+n+".touched",!0),i=p(i,"anyTouched",!0)),i}),o(r,a.CHANGE,function(e,t){var r=t.meta,n=r.field,o=r.touch,u=r.persistentSubmitErrors,i=t.payload,a=e;return void 0===c(a,"initial."+n)&&""===i?a=g(a,"values."+n):void 0!==i&&(a=p(a,"values."+n,i)),a=g(a,"asyncErrors."+n),u||(a=g(a,"submitErrors."+n)),a=g(a,"fields."+n+".autofilled"),o&&(a=p(a,"fields."+n+".touched",!0),a=p(a,"anyTouched",!0)),a}),o(r,a.CLEAR_SUBMIT,function(e){return y(e,"triggerSubmit")}),o(r,a.CLEAR_SUBMIT_ERRORS,function(e){var t=e;return t=g(t,"submitErrors"),t=y(t,"error")}),o(r,a.CLEAR_ASYNC_ERROR,function(e,t){return y(e,"asyncErrors."+t.meta.field)}),o(r,a.FOCUS,function(e,t){var r=t.meta.field,n=e,o=c(e,"active");return n=y(n,"fields."+o+".active"),n=p(n,"fields."+r+".visited",!0),n=p(n,"fields."+r+".active",!0),n=p(n,"active",r)}),o(r,a.INITIALIZE,function(e,t){var r=t.payload,o=t.meta,u=o.keepDirty,a=o.keepSubmitSucceeded,s=v(r),l=i,d=c(e,"warning");d&&(l=p(l,"warning",d));var y=c(e,"syncWarnings");y&&(l=p(l,"syncWarnings",y));var b=c(e,"error");b&&(l=p(l,"error",b));var h=c(e,"syncErrors");h&&(l=p(l,"syncErrors",h));var _=c(e,"registeredFields");_&&(l=p(l,"registeredFields",_));var g=c(e,"values"),O=c(e,"initial"),S=s,R=g;return u&&_?n(S,O)||(f(m(_),function(e){var t=c(O,e),r=c(g,e);if(n(r,t)){var o=c(S,e);c(R,e)!==o&&(R=p(R,e,o))}}),f(m(S),function(e){if(void 0===c(O,e)){var t=c(S,e);R=p(R,e,t)}})):R=S,a&&c(e,"submitSucceeded")&&(l=p(l,"submitSucceeded",!0)),l=p(l,"values",R),l=p(l,"initial",S)}),o(r,a.REGISTER_FIELD,function(e,t){var r=t.payload,n=r.name,o=r.type,u="registeredFields['"+n+"']",i=c(e,u);if(i){var a=c(i,"count")+1;i=p(i,"count",a)}else i=v({name:n,type:o,count:1});return p(e,u,i)}),o(r,a.RESET,function(e){var t=i,r=c(e,"registeredFields");r&&(t=p(t,"registeredFields",r));var n=c(e,"initial");return n&&(t=p(t,"values",n),t=p(t,"initial",n)),t}),o(r,a.SUBMIT,function(e){return p(e,"triggerSubmit",!0)}),o(r,a.START_ASYNC_VALIDATION,function(e,t){return p(e,"asyncValidating",t.meta.field||!0)}),o(r,a.START_SUBMIT,function(e){return p(e,"submitting",!0)}),o(r,a.STOP_ASYNC_VALIDATION,function(e,t){var r=t.payload,n=e;if(n=y(n,"asyncValidating"),r&&Object.keys(r).length){var o=r._error,i=u(r,["_error"]);o&&(n=p(n,"error",o)),Object.keys(i).length&&(n=p(n,"asyncErrors",v(i)))}else n=y(n,"error");return n}),o(r,a.STOP_SUBMIT,function(e,t){var r=t.payload,n=e;if(n=y(n,"submitting"),n=y(n,"submitFailed"),n=y(n,"submitSucceeded"),r&&Object.keys(r).length){var o=r._error,i=u(r,["_error"]);n=o?p(n,"error",o):y(n,"error"),n=Object.keys(i).length?p(n,"submitErrors",v(i)):y(n,"submitErrors"),n=p(n,"submitFailed",!0)}else n=p(n,"submitSucceeded",!0),n=y(n,"error"),n=y(n,"submitErrors");return n}),o(r,a.SET_SUBMIT_FAILED,function(e,t){var r=t.meta.fields,n=e;return n=p(n,"submitFailed",!0),n=y(n,"submitSucceeded"),n=y(n,"submitting"),r.forEach(function(e){return n=p(n,"fields."+e+".touched",!0)}),r.length&&(n=p(n,"anyTouched",!0)),n}),o(r,a.SET_SUBMIT_SUCCEEDED,function(e){var t=e;return t=y(t,"submitFailed"),t=p(t,"submitSucceeded",!0)}),o(r,a.TOUCH,function(e,t){var r=t.meta.fields,n=e;return r.forEach(function(e){return n=p(n,"fields."+e+".touched",!0)}),n=p(n,"anyTouched",!0)}),o(r,a.UNREGISTER_FIELD,function(e,t){var r=t.payload,o=r.name,u=r.destroyOnUnmount,a=e,f="registeredFields['"+o+"']",s=c(a,f);if(!s)return a;var l=c(s,"count")-1;return 0>=l&&u?(a=y(a,f),n(c(a,"registeredFields"),i)&&(a=y(a,"registeredFields")),a=g(a,"syncErrors."+o),a=g(a,"submitErrors."+o),a=g(a,"asyncErrors."+o),a=g(a,"syncWarnings."+o)):(s=p(s,"count",l),a=p(a,f,s)),a}),o(r,a.UNTOUCH,function(e,t){var r=t.meta.fields,n=e;r.forEach(function(e){return n=y(n,"fields."+e+".touched")});var o=h(m(c(n,"registeredFields")),function(e){return c(n,"fields."+e+".touched")});return n=o?p(n,"anyTouched",!0):y(n,"anyTouched")}),o(r,a.UPDATE_SYNC_ERRORS,function(e,t){var r=t.payload,n=r.syncErrors,o=r.error,u=e;return o?(u=p(u,"error",o),u=p(u,"syncError",!0)):(u=y(u,"error"),u=y(u,"syncError")),u=Object.keys(n).length?p(u,"syncErrors",n):y(u,"syncErrors")}),o(r,a.UPDATE_SYNC_WARNINGS,function(e,t){var r=t.payload,n=r.syncWarnings,o=r.warning,u=e;return u=o?p(u,"warning",o):y(u,"warning"),u=Object.keys(n).length?p(u,"syncWarnings",n):y(u,"syncWarnings")}),r),P=function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:i,t=arguments[1],r=j[t.type];return r?r(e,t):e};return t(function(e){return function(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:i,r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{type:"NONE"},n=r&&r.meta&&r.meta.form;if(!n||!d(r))return t;if(r.type===a.DESTROY&&r.meta&&r.meta.form)return r.meta.form.reduce(function(e,t){return g(e,t)},t);var o=c(t,n),u=e(o,r);return u===o?t:p(t,n,u)}}(P))}Object.defineProperty(t,"__esModule",{value:!0});var a=r(16),f=r(168),s=n(f),c=r(0),l=n(c),d=function(e){return e&&e.type&&e.type.length>a.prefix.length&&e.type.substring(0,a.prefix.length)===a.prefix};t.default=i},function(e,t,r){"use strict";function n(e){var t=e.deepEqual,r=e.empty,n=e.getIn,o=e.deleteIn,i=e.setIn;return function e(a,f){if("]"===f[f.length-1]){var s=(0,u.default)(f);s.pop();return n(a,s.join("."))?i(a,f):a}var c=a;void 0!==n(a,f)&&(c=o(a,f));var l=f.lastIndexOf(".");if(l>0){var d=f.substring(0,l);if("]"!==d[d.length-1]){var p=n(c,d);if(t(p,r))return e(c,d)}}return c}}Object.defineProperty(t,"__esModule",{value:!0});var o=r(6),u=function(e){return e&&e.__esModule?e:{default:e}}(o);t.default=n},function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{default:e}}Object.defineProperty(t,"__esModule",{value:!0}),t.default=(0,n(r(170)).default)(n(r(0)).default)},function(e,t,r){"use strict";function n(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 o=Object.assign||function(e){for(var t=1;arguments.length>t;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},u=r(3);t.default=function(e){var t=e.getIn;return function(e){var r=o({prop:"values",getFormState:function(e){return t(e,"form")}},e),i=r.form,a=r.prop,f=r.getFormState;return(0,u.connect)(function(e){return n({},a,t(f(e),i+".values"))})}}}])});
files/videojs/5.0.0-rc.80/video.js
gregorypratt/jsdelivr
/** * @license * Video.js 5.0.0-rc.80 <http://videojs.com/> * Copyright Brightcove, Inc. <https://www.brightcove.com/> * Available under Apache License Version 2.0 * <https://github.com/videojs/video.js/blob/master/LICENSE> * * Includes vtt.js <https://github.com/mozilla/vtt.js> * Available under Apache License Version 2.0 * <https://github.com/mozilla/vtt.js/blob/master/LICENSE> */ (function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}g.videojs = f()}})(function(){var define,module,exports;return (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(_dereq_,module,exports){ (function (global){ var topLevel = typeof global !== 'undefined' ? global : typeof window !== 'undefined' ? window : {} var minDoc = _dereq_('min-document'); if (typeof document !== 'undefined') { module.exports = document; } else { var doccy = topLevel['__GLOBAL_DOCUMENT_CACHE@4']; if (!doccy) { doccy = topLevel['__GLOBAL_DOCUMENT_CACHE@4'] = minDoc; } module.exports = doccy; } }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) //# sourceMappingURL=data:application/json;charset:utf-8;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbIm5vZGVfbW9kdWxlcy9nbG9iYWwvZG9jdW1lbnQuanMiXSwibmFtZXMiOltdLCJtYXBwaW5ncyI6IjtBQUFBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBIiwiZmlsZSI6ImdlbmVyYXRlZC5qcyIsInNvdXJjZVJvb3QiOiIiLCJzb3VyY2VzQ29udGVudCI6WyJ2YXIgdG9wTGV2ZWwgPSB0eXBlb2YgZ2xvYmFsICE9PSAndW5kZWZpbmVkJyA/IGdsb2JhbCA6XG4gICAgdHlwZW9mIHdpbmRvdyAhPT0gJ3VuZGVmaW5lZCcgPyB3aW5kb3cgOiB7fVxudmFyIG1pbkRvYyA9IHJlcXVpcmUoJ21pbi1kb2N1bWVudCcpO1xuXG5pZiAodHlwZW9mIGRvY3VtZW50ICE9PSAndW5kZWZpbmVkJykge1xuICAgIG1vZHVsZS5leHBvcnRzID0gZG9jdW1lbnQ7XG59IGVsc2Uge1xuICAgIHZhciBkb2NjeSA9IHRvcExldmVsWydfX0dMT0JBTF9ET0NVTUVOVF9DQUNIRUA0J107XG5cbiAgICBpZiAoIWRvY2N5KSB7XG4gICAgICAgIGRvY2N5ID0gdG9wTGV2ZWxbJ19fR0xPQkFMX0RPQ1VNRU5UX0NBQ0hFQDQnXSA9IG1pbkRvYztcbiAgICB9XG5cbiAgICBtb2R1bGUuZXhwb3J0cyA9IGRvY2N5O1xufVxuIl19 },{"min-document":3}],2:[function(_dereq_,module,exports){ (function (global){ if (typeof window !== "undefined") { module.exports = window; } else if (typeof global !== "undefined") { module.exports = global; } else if (typeof self !== "undefined"){ module.exports = self; } else { module.exports = {}; } }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) //# sourceMappingURL=data:application/json;charset:utf-8;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbIm5vZGVfbW9kdWxlcy9nbG9iYWwvd2luZG93LmpzIl0sIm5hbWVzIjpbXSwibWFwcGluZ3MiOiI7QUFBQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQSIsImZpbGUiOiJnZW5lcmF0ZWQuanMiLCJzb3VyY2VSb290IjoiIiwic291cmNlc0NvbnRlbnQiOlsiaWYgKHR5cGVvZiB3aW5kb3cgIT09IFwidW5kZWZpbmVkXCIpIHtcbiAgICBtb2R1bGUuZXhwb3J0cyA9IHdpbmRvdztcbn0gZWxzZSBpZiAodHlwZW9mIGdsb2JhbCAhPT0gXCJ1bmRlZmluZWRcIikge1xuICAgIG1vZHVsZS5leHBvcnRzID0gZ2xvYmFsO1xufSBlbHNlIGlmICh0eXBlb2Ygc2VsZiAhPT0gXCJ1bmRlZmluZWRcIil7XG4gICAgbW9kdWxlLmV4cG9ydHMgPSBzZWxmO1xufSBlbHNlIHtcbiAgICBtb2R1bGUuZXhwb3J0cyA9IHt9O1xufVxuIl19 },{}],3:[function(_dereq_,module,exports){ },{}],4:[function(_dereq_,module,exports){ /** Used as the `TypeError` message for "Functions" methods. */ var FUNC_ERROR_TEXT = 'Expected a function'; /* Native method references for those with the same name as other `lodash` methods. */ var nativeMax = Math.max; /** * Creates a function that invokes `func` with the `this` binding of the * created function and arguments from `start` and beyond provided as an array. * * **Note:** This method is based on the [rest parameter](https://developer.mozilla.org/Web/JavaScript/Reference/Functions/rest_parameters). * * @static * @memberOf _ * @category Function * @param {Function} func The function to apply a rest parameter to. * @param {number} [start=func.length-1] The start position of the rest parameter. * @returns {Function} Returns the new function. * @example * * var say = _.restParam(function(what, names) { * return what + ' ' + _.initial(names).join(', ') + * (_.size(names) > 1 ? ', & ' : '') + _.last(names); * }); * * say('hello', 'fred', 'barney', 'pebbles'); * // => 'hello fred, barney, & pebbles' */ function restParam(func, start) { if (typeof func != 'function') { throw new TypeError(FUNC_ERROR_TEXT); } start = nativeMax(start === undefined ? (func.length - 1) : (+start || 0), 0); return function() { var args = arguments, index = -1, length = nativeMax(args.length - start, 0), rest = Array(length); while (++index < length) { rest[index] = args[start + index]; } switch (start) { case 0: return func.call(this, rest); case 1: return func.call(this, args[0], rest); case 2: return func.call(this, args[0], args[1], rest); } var otherArgs = Array(start + 1); index = -1; while (++index < start) { otherArgs[index] = args[index]; } otherArgs[start] = rest; return func.apply(this, otherArgs); }; } module.exports = restParam; },{}],5:[function(_dereq_,module,exports){ /** * Copies the values of `source` to `array`. * * @private * @param {Array} source The array to copy values from. * @param {Array} [array=[]] The array to copy values to. * @returns {Array} Returns `array`. */ function arrayCopy(source, array) { var index = -1, length = source.length; array || (array = Array(length)); while (++index < length) { array[index] = source[index]; } return array; } module.exports = arrayCopy; },{}],6:[function(_dereq_,module,exports){ /** * A specialized version of `_.forEach` for arrays without support for callback * shorthands and `this` binding. * * @private * @param {Array} array The array to iterate over. * @param {Function} iteratee The function invoked per iteration. * @returns {Array} Returns `array`. */ function arrayEach(array, iteratee) { var index = -1, length = array.length; while (++index < length) { if (iteratee(array[index], index, array) === false) { break; } } return array; } module.exports = arrayEach; },{}],7:[function(_dereq_,module,exports){ /** * Copies properties of `source` to `object`. * * @private * @param {Object} source The object to copy properties from. * @param {Array} props The property names to copy. * @param {Object} [object={}] The object to copy properties to. * @returns {Object} Returns `object`. */ function baseCopy(source, props, object) { object || (object = {}); var index = -1, length = props.length; while (++index < length) { var key = props[index]; object[key] = source[key]; } return object; } module.exports = baseCopy; },{}],8:[function(_dereq_,module,exports){ var createBaseFor = _dereq_('./createBaseFor'); /** * The base implementation of `baseForIn` and `baseForOwn` which iterates * over `object` properties returned by `keysFunc` invoking `iteratee` for * each property. Iteratee functions may exit iteration early by explicitly * returning `false`. * * @private * @param {Object} object The object to iterate over. * @param {Function} iteratee The function invoked per iteration. * @param {Function} keysFunc The function to get the keys of `object`. * @returns {Object} Returns `object`. */ var baseFor = createBaseFor(); module.exports = baseFor; },{"./createBaseFor":15}],9:[function(_dereq_,module,exports){ var baseFor = _dereq_('./baseFor'), keysIn = _dereq_('../object/keysIn'); /** * The base implementation of `_.forIn` without support for callback * shorthands and `this` binding. * * @private * @param {Object} object The object to iterate over. * @param {Function} iteratee The function invoked per iteration. * @returns {Object} Returns `object`. */ function baseForIn(object, iteratee) { return baseFor(object, iteratee, keysIn); } module.exports = baseForIn; },{"../object/keysIn":36,"./baseFor":8}],10:[function(_dereq_,module,exports){ var arrayEach = _dereq_('./arrayEach'), baseMergeDeep = _dereq_('./baseMergeDeep'), isArray = _dereq_('../lang/isArray'), isArrayLike = _dereq_('./isArrayLike'), isObject = _dereq_('../lang/isObject'), isObjectLike = _dereq_('./isObjectLike'), isTypedArray = _dereq_('../lang/isTypedArray'), keys = _dereq_('../object/keys'); /** * The base implementation of `_.merge` without support for argument juggling, * multiple sources, and `this` binding `customizer` functions. * * @private * @param {Object} object The destination object. * @param {Object} source The source object. * @param {Function} [customizer] The function to customize merged values. * @param {Array} [stackA=[]] Tracks traversed source objects. * @param {Array} [stackB=[]] Associates values with source counterparts. * @returns {Object} Returns `object`. */ function baseMerge(object, source, customizer, stackA, stackB) { if (!isObject(object)) { return object; } var isSrcArr = isArrayLike(source) && (isArray(source) || isTypedArray(source)), props = isSrcArr ? undefined : keys(source); arrayEach(props || source, function(srcValue, key) { if (props) { key = srcValue; srcValue = source[key]; } if (isObjectLike(srcValue)) { stackA || (stackA = []); stackB || (stackB = []); baseMergeDeep(object, source, key, baseMerge, customizer, stackA, stackB); } else { var value = object[key], result = customizer ? customizer(value, srcValue, key, object, source) : undefined, isCommon = result === undefined; if (isCommon) { result = srcValue; } if ((result !== undefined || (isSrcArr && !(key in object))) && (isCommon || (result === result ? (result !== value) : (value === value)))) { object[key] = result; } } }); return object; } module.exports = baseMerge; },{"../lang/isArray":27,"../lang/isObject":30,"../lang/isTypedArray":33,"../object/keys":35,"./arrayEach":6,"./baseMergeDeep":11,"./isArrayLike":18,"./isObjectLike":23}],11:[function(_dereq_,module,exports){ var arrayCopy = _dereq_('./arrayCopy'), isArguments = _dereq_('../lang/isArguments'), isArray = _dereq_('../lang/isArray'), isArrayLike = _dereq_('./isArrayLike'), isPlainObject = _dereq_('../lang/isPlainObject'), isTypedArray = _dereq_('../lang/isTypedArray'), toPlainObject = _dereq_('../lang/toPlainObject'); /** * A specialized version of `baseMerge` for arrays and objects which performs * deep merges and tracks traversed objects enabling objects with circular * references to be merged. * * @private * @param {Object} object The destination object. * @param {Object} source The source object. * @param {string} key The key of the value to merge. * @param {Function} mergeFunc The function to merge values. * @param {Function} [customizer] The function to customize merged values. * @param {Array} [stackA=[]] Tracks traversed source objects. * @param {Array} [stackB=[]] Associates values with source counterparts. * @returns {boolean} Returns `true` if the objects are equivalent, else `false`. */ function baseMergeDeep(object, source, key, mergeFunc, customizer, stackA, stackB) { var length = stackA.length, srcValue = source[key]; while (length--) { if (stackA[length] == srcValue) { object[key] = stackB[length]; return; } } var value = object[key], result = customizer ? customizer(value, srcValue, key, object, source) : undefined, isCommon = result === undefined; if (isCommon) { result = srcValue; if (isArrayLike(srcValue) && (isArray(srcValue) || isTypedArray(srcValue))) { result = isArray(value) ? value : (isArrayLike(value) ? arrayCopy(value) : []); } else if (isPlainObject(srcValue) || isArguments(srcValue)) { result = isArguments(value) ? toPlainObject(value) : (isPlainObject(value) ? value : {}); } else { isCommon = false; } } // Add the source value to the stack of traversed objects and associate // it with its merged value. stackA.push(srcValue); stackB.push(result); if (isCommon) { // Recursively merge objects and arrays (susceptible to call stack limits). object[key] = mergeFunc(result, srcValue, customizer, stackA, stackB); } else if (result === result ? (result !== value) : (value === value)) { object[key] = result; } } module.exports = baseMergeDeep; },{"../lang/isArguments":26,"../lang/isArray":27,"../lang/isPlainObject":31,"../lang/isTypedArray":33,"../lang/toPlainObject":34,"./arrayCopy":5,"./isArrayLike":18}],12:[function(_dereq_,module,exports){ var toObject = _dereq_('./toObject'); /** * The base implementation of `_.property` without support for deep paths. * * @private * @param {string} key The key of the property to get. * @returns {Function} Returns the new function. */ function baseProperty(key) { return function(object) { return object == null ? undefined : toObject(object)[key]; }; } module.exports = baseProperty; },{"./toObject":25}],13:[function(_dereq_,module,exports){ var identity = _dereq_('../utility/identity'); /** * A specialized version of `baseCallback` which only supports `this` binding * and specifying the number of arguments to provide to `func`. * * @private * @param {Function} func The function to bind. * @param {*} thisArg The `this` binding of `func`. * @param {number} [argCount] The number of arguments to provide to `func`. * @returns {Function} Returns the callback. */ function bindCallback(func, thisArg, argCount) { if (typeof func != 'function') { return identity; } if (thisArg === undefined) { return func; } switch (argCount) { case 1: return function(value) { return func.call(thisArg, value); }; case 3: return function(value, index, collection) { return func.call(thisArg, value, index, collection); }; case 4: return function(accumulator, value, index, collection) { return func.call(thisArg, accumulator, value, index, collection); }; case 5: return function(value, other, key, object, source) { return func.call(thisArg, value, other, key, object, source); }; } return function() { return func.apply(thisArg, arguments); }; } module.exports = bindCallback; },{"../utility/identity":39}],14:[function(_dereq_,module,exports){ var bindCallback = _dereq_('./bindCallback'), isIterateeCall = _dereq_('./isIterateeCall'), restParam = _dereq_('../function/restParam'); /** * Creates a `_.assign`, `_.defaults`, or `_.merge` function. * * @private * @param {Function} assigner The function to assign values. * @returns {Function} Returns the new assigner function. */ function createAssigner(assigner) { return restParam(function(object, sources) { var index = -1, length = object == null ? 0 : sources.length, customizer = length > 2 ? sources[length - 2] : undefined, guard = length > 2 ? sources[2] : undefined, thisArg = length > 1 ? sources[length - 1] : undefined; if (typeof customizer == 'function') { customizer = bindCallback(customizer, thisArg, 5); length -= 2; } else { customizer = typeof thisArg == 'function' ? thisArg : undefined; length -= (customizer ? 1 : 0); } if (guard && isIterateeCall(sources[0], sources[1], guard)) { customizer = length < 3 ? undefined : customizer; length = 1; } while (++index < length) { var source = sources[index]; if (source) { assigner(object, source, customizer); } } return object; }); } module.exports = createAssigner; },{"../function/restParam":4,"./bindCallback":13,"./isIterateeCall":21}],15:[function(_dereq_,module,exports){ var toObject = _dereq_('./toObject'); /** * Creates a base function for `_.forIn` or `_.forInRight`. * * @private * @param {boolean} [fromRight] Specify iterating from right to left. * @returns {Function} Returns the new base function. */ function createBaseFor(fromRight) { return function(object, iteratee, keysFunc) { var iterable = toObject(object), props = keysFunc(object), length = props.length, index = fromRight ? length : -1; while ((fromRight ? index-- : ++index < length)) { var key = props[index]; if (iteratee(iterable[key], key, iterable) === false) { break; } } return object; }; } module.exports = createBaseFor; },{"./toObject":25}],16:[function(_dereq_,module,exports){ var baseProperty = _dereq_('./baseProperty'); /** * Gets the "length" property value of `object`. * * **Note:** This function is used to avoid a [JIT bug](https://bugs.webkit.org/show_bug.cgi?id=142792) * that affects Safari on at least iOS 8.1-8.3 ARM64. * * @private * @param {Object} object The object to query. * @returns {*} Returns the "length" value. */ var getLength = baseProperty('length'); module.exports = getLength; },{"./baseProperty":12}],17:[function(_dereq_,module,exports){ var isNative = _dereq_('../lang/isNative'); /** * Gets the native function at `key` of `object`. * * @private * @param {Object} object The object to query. * @param {string} key The key of the method to get. * @returns {*} Returns the function if it's native, else `undefined`. */ function getNative(object, key) { var value = object == null ? undefined : object[key]; return isNative(value) ? value : undefined; } module.exports = getNative; },{"../lang/isNative":29}],18:[function(_dereq_,module,exports){ var getLength = _dereq_('./getLength'), isLength = _dereq_('./isLength'); /** * Checks if `value` is array-like. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is array-like, else `false`. */ function isArrayLike(value) { return value != null && isLength(getLength(value)); } module.exports = isArrayLike; },{"./getLength":16,"./isLength":22}],19:[function(_dereq_,module,exports){ /** * Checks if `value` is a host object in IE < 9. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a host object, else `false`. */ var isHostObject = (function() { try { Object({ 'toString': 0 } + ''); } catch(e) { return function() { return false; }; } return function(value) { // IE < 9 presents many host objects as `Object` objects that can coerce // to strings despite having improperly defined `toString` methods. return typeof value.toString != 'function' && typeof (value + '') == 'string'; }; }()); module.exports = isHostObject; },{}],20:[function(_dereq_,module,exports){ /** Used to detect unsigned integer values. */ var reIsUint = /^\d+$/; /** * Used as the [maximum length](http://ecma-international.org/ecma-262/6.0/#sec-number.max_safe_integer) * of an array-like value. */ var MAX_SAFE_INTEGER = 9007199254740991; /** * Checks if `value` is a valid array-like index. * * @private * @param {*} value The value to check. * @param {number} [length=MAX_SAFE_INTEGER] The upper bounds of a valid index. * @returns {boolean} Returns `true` if `value` is a valid index, else `false`. */ function isIndex(value, length) { value = (typeof value == 'number' || reIsUint.test(value)) ? +value : -1; length = length == null ? MAX_SAFE_INTEGER : length; return value > -1 && value % 1 == 0 && value < length; } module.exports = isIndex; },{}],21:[function(_dereq_,module,exports){ var isArrayLike = _dereq_('./isArrayLike'), isIndex = _dereq_('./isIndex'), isObject = _dereq_('../lang/isObject'); /** * Checks if the provided arguments are from an iteratee call. * * @private * @param {*} value The potential iteratee value argument. * @param {*} index The potential iteratee index or key argument. * @param {*} object The potential iteratee object argument. * @returns {boolean} Returns `true` if the arguments are from an iteratee call, else `false`. */ function isIterateeCall(value, index, object) { if (!isObject(object)) { return false; } var type = typeof index; if (type == 'number' ? (isArrayLike(object) && isIndex(index, object.length)) : (type == 'string' && index in object)) { var other = object[index]; return value === value ? (value === other) : (other !== other); } return false; } module.exports = isIterateeCall; },{"../lang/isObject":30,"./isArrayLike":18,"./isIndex":20}],22:[function(_dereq_,module,exports){ /** * Used as the [maximum length](http://ecma-international.org/ecma-262/6.0/#sec-number.max_safe_integer) * of an array-like value. */ var MAX_SAFE_INTEGER = 9007199254740991; /** * Checks if `value` is a valid array-like length. * * **Note:** This function is based on [`ToLength`](http://ecma-international.org/ecma-262/6.0/#sec-tolength). * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a valid length, else `false`. */ function isLength(value) { return typeof value == 'number' && value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER; } module.exports = isLength; },{}],23:[function(_dereq_,module,exports){ /** * Checks if `value` is object-like. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is object-like, else `false`. */ function isObjectLike(value) { return !!value && typeof value == 'object'; } module.exports = isObjectLike; },{}],24:[function(_dereq_,module,exports){ var isArguments = _dereq_('../lang/isArguments'), isArray = _dereq_('../lang/isArray'), isIndex = _dereq_('./isIndex'), isLength = _dereq_('./isLength'), isString = _dereq_('../lang/isString'), keysIn = _dereq_('../object/keysIn'); /** Used for native method references. */ var objectProto = Object.prototype; /** Used to check objects for own properties. */ var hasOwnProperty = objectProto.hasOwnProperty; /** * A fallback implementation of `Object.keys` which creates an array of the * own enumerable property names of `object`. * * @private * @param {Object} object The object to query. * @returns {Array} Returns the array of property names. */ function shimKeys(object) { var props = keysIn(object), propsLength = props.length, length = propsLength && object.length; var allowIndexes = !!length && isLength(length) && (isArray(object) || isArguments(object) || isString(object)); var index = -1, result = []; while (++index < propsLength) { var key = props[index]; if ((allowIndexes && isIndex(key, length)) || hasOwnProperty.call(object, key)) { result.push(key); } } return result; } module.exports = shimKeys; },{"../lang/isArguments":26,"../lang/isArray":27,"../lang/isString":32,"../object/keysIn":36,"./isIndex":20,"./isLength":22}],25:[function(_dereq_,module,exports){ var isObject = _dereq_('../lang/isObject'), isString = _dereq_('../lang/isString'), support = _dereq_('../support'); /** * Converts `value` to an object if it's not one. * * @private * @param {*} value The value to process. * @returns {Object} Returns the object. */ function toObject(value) { if (support.unindexedChars && isString(value)) { var index = -1, length = value.length, result = Object(value); while (++index < length) { result[index] = value.charAt(index); } return result; } return isObject(value) ? value : Object(value); } module.exports = toObject; },{"../lang/isObject":30,"../lang/isString":32,"../support":38}],26:[function(_dereq_,module,exports){ var isArrayLike = _dereq_('../internal/isArrayLike'), isObjectLike = _dereq_('../internal/isObjectLike'); /** Used for native method references. */ var objectProto = Object.prototype; /** Used to check objects for own properties. */ var hasOwnProperty = objectProto.hasOwnProperty; /** Native method references. */ var propertyIsEnumerable = objectProto.propertyIsEnumerable; /** * Checks if `value` is classified as an `arguments` object. * * @static * @memberOf _ * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is correctly classified, else `false`. * @example * * _.isArguments(function() { return arguments; }()); * // => true * * _.isArguments([1, 2, 3]); * // => false */ function isArguments(value) { return isObjectLike(value) && isArrayLike(value) && hasOwnProperty.call(value, 'callee') && !propertyIsEnumerable.call(value, 'callee'); } module.exports = isArguments; },{"../internal/isArrayLike":18,"../internal/isObjectLike":23}],27:[function(_dereq_,module,exports){ var getNative = _dereq_('../internal/getNative'), isLength = _dereq_('../internal/isLength'), isObjectLike = _dereq_('../internal/isObjectLike'); /** `Object#toString` result references. */ var arrayTag = '[object Array]'; /** Used for native method references. */ var objectProto = Object.prototype; /** * Used to resolve the [`toStringTag`](http://ecma-international.org/ecma-262/6.0/#sec-object.prototype.tostring) * of values. */ var objToString = objectProto.toString; /* Native method references for those with the same name as other `lodash` methods. */ var nativeIsArray = getNative(Array, 'isArray'); /** * Checks if `value` is classified as an `Array` object. * * @static * @memberOf _ * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is correctly classified, else `false`. * @example * * _.isArray([1, 2, 3]); * // => true * * _.isArray(function() { return arguments; }()); * // => false */ var isArray = nativeIsArray || function(value) { return isObjectLike(value) && isLength(value.length) && objToString.call(value) == arrayTag; }; module.exports = isArray; },{"../internal/getNative":17,"../internal/isLength":22,"../internal/isObjectLike":23}],28:[function(_dereq_,module,exports){ var isObject = _dereq_('./isObject'); /** `Object#toString` result references. */ var funcTag = '[object Function]'; /** Used for native method references. */ var objectProto = Object.prototype; /** * Used to resolve the [`toStringTag`](http://ecma-international.org/ecma-262/6.0/#sec-object.prototype.tostring) * of values. */ var objToString = objectProto.toString; /** * Checks if `value` is classified as a `Function` object. * * @static * @memberOf _ * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is correctly classified, else `false`. * @example * * _.isFunction(_); * // => true * * _.isFunction(/abc/); * // => false */ function isFunction(value) { // The use of `Object#toString` avoids issues with the `typeof` operator // in older versions of Chrome and Safari which return 'function' for regexes // and Safari 8 which returns 'object' for typed array constructors. return isObject(value) && objToString.call(value) == funcTag; } module.exports = isFunction; },{"./isObject":30}],29:[function(_dereq_,module,exports){ var isFunction = _dereq_('./isFunction'), isHostObject = _dereq_('../internal/isHostObject'), isObjectLike = _dereq_('../internal/isObjectLike'); /** Used to detect host constructors (Safari > 5). */ var reIsHostCtor = /^\[object .+?Constructor\]$/; /** Used for native method references. */ var objectProto = Object.prototype; /** Used to resolve the decompiled source of functions. */ var fnToString = Function.prototype.toString; /** Used to check objects for own properties. */ var hasOwnProperty = objectProto.hasOwnProperty; /** Used to detect if a method is native. */ var reIsNative = RegExp('^' + fnToString.call(hasOwnProperty).replace(/[\\^$.*+?()[\]{}|]/g, '\\$&') .replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g, '$1.*?') + '$' ); /** * Checks if `value` is a native function. * * @static * @memberOf _ * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a native function, else `false`. * @example * * _.isNative(Array.prototype.push); * // => true * * _.isNative(_); * // => false */ function isNative(value) { if (value == null) { return false; } if (isFunction(value)) { return reIsNative.test(fnToString.call(value)); } return isObjectLike(value) && (isHostObject(value) ? reIsNative : reIsHostCtor).test(value); } module.exports = isNative; },{"../internal/isHostObject":19,"../internal/isObjectLike":23,"./isFunction":28}],30:[function(_dereq_,module,exports){ /** * Checks if `value` is the [language type](https://es5.github.io/#x8) of `Object`. * (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`) * * @static * @memberOf _ * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is an object, else `false`. * @example * * _.isObject({}); * // => true * * _.isObject([1, 2, 3]); * // => true * * _.isObject(1); * // => false */ function isObject(value) { // Avoid a V8 JIT bug in Chrome 19-20. // See https://code.google.com/p/v8/issues/detail?id=2291 for more details. var type = typeof value; return !!value && (type == 'object' || type == 'function'); } module.exports = isObject; },{}],31:[function(_dereq_,module,exports){ var baseForIn = _dereq_('../internal/baseForIn'), isArguments = _dereq_('./isArguments'), isHostObject = _dereq_('../internal/isHostObject'), isObjectLike = _dereq_('../internal/isObjectLike'), support = _dereq_('../support'); /** `Object#toString` result references. */ var objectTag = '[object Object]'; /** Used for native method references. */ var objectProto = Object.prototype; /** Used to check objects for own properties. */ var hasOwnProperty = objectProto.hasOwnProperty; /** * Used to resolve the [`toStringTag`](http://ecma-international.org/ecma-262/6.0/#sec-object.prototype.tostring) * of values. */ var objToString = objectProto.toString; /** * Checks if `value` is a plain object, that is, an object created by the * `Object` constructor or one with a `[[Prototype]]` of `null`. * * **Note:** This method assumes objects created by the `Object` constructor * have no inherited enumerable properties. * * @static * @memberOf _ * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a plain object, else `false`. * @example * * function Foo() { * this.a = 1; * } * * _.isPlainObject(new Foo); * // => false * * _.isPlainObject([1, 2, 3]); * // => false * * _.isPlainObject({ 'x': 0, 'y': 0 }); * // => true * * _.isPlainObject(Object.create(null)); * // => true */ function isPlainObject(value) { var Ctor; // Exit early for non `Object` objects. if (!(isObjectLike(value) && objToString.call(value) == objectTag && !isHostObject(value) && !isArguments(value)) || (!hasOwnProperty.call(value, 'constructor') && (Ctor = value.constructor, typeof Ctor == 'function' && !(Ctor instanceof Ctor)))) { return false; } // IE < 9 iterates inherited properties before own properties. If the first // iterated property is an object's own property then there are no inherited // enumerable properties. var result; if (support.ownLast) { baseForIn(value, function(subValue, key, object) { result = hasOwnProperty.call(object, key); return false; }); return result !== false; } // In most environments an object's own properties are iterated before // its inherited properties. If the last iterated property is an object's // own property then there are no inherited enumerable properties. baseForIn(value, function(subValue, key) { result = key; }); return result === undefined || hasOwnProperty.call(value, result); } module.exports = isPlainObject; },{"../internal/baseForIn":9,"../internal/isHostObject":19,"../internal/isObjectLike":23,"../support":38,"./isArguments":26}],32:[function(_dereq_,module,exports){ var isObjectLike = _dereq_('../internal/isObjectLike'); /** `Object#toString` result references. */ var stringTag = '[object String]'; /** Used for native method references. */ var objectProto = Object.prototype; /** * Used to resolve the [`toStringTag`](http://ecma-international.org/ecma-262/6.0/#sec-object.prototype.tostring) * of values. */ var objToString = objectProto.toString; /** * Checks if `value` is classified as a `String` primitive or object. * * @static * @memberOf _ * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is correctly classified, else `false`. * @example * * _.isString('abc'); * // => true * * _.isString(1); * // => false */ function isString(value) { return typeof value == 'string' || (isObjectLike(value) && objToString.call(value) == stringTag); } module.exports = isString; },{"../internal/isObjectLike":23}],33:[function(_dereq_,module,exports){ var isLength = _dereq_('../internal/isLength'), isObjectLike = _dereq_('../internal/isObjectLike'); /** `Object#toString` result references. */ var argsTag = '[object Arguments]', arrayTag = '[object Array]', boolTag = '[object Boolean]', dateTag = '[object Date]', errorTag = '[object Error]', funcTag = '[object Function]', mapTag = '[object Map]', numberTag = '[object Number]', objectTag = '[object Object]', regexpTag = '[object RegExp]', setTag = '[object Set]', stringTag = '[object String]', weakMapTag = '[object WeakMap]'; var arrayBufferTag = '[object ArrayBuffer]', float32Tag = '[object Float32Array]', float64Tag = '[object Float64Array]', int8Tag = '[object Int8Array]', int16Tag = '[object Int16Array]', int32Tag = '[object Int32Array]', uint8Tag = '[object Uint8Array]', uint8ClampedTag = '[object Uint8ClampedArray]', uint16Tag = '[object Uint16Array]', uint32Tag = '[object Uint32Array]'; /** Used to identify `toStringTag` values of typed arrays. */ var typedArrayTags = {}; typedArrayTags[float32Tag] = typedArrayTags[float64Tag] = typedArrayTags[int8Tag] = typedArrayTags[int16Tag] = typedArrayTags[int32Tag] = typedArrayTags[uint8Tag] = typedArrayTags[uint8ClampedTag] = typedArrayTags[uint16Tag] = typedArrayTags[uint32Tag] = true; typedArrayTags[argsTag] = typedArrayTags[arrayTag] = typedArrayTags[arrayBufferTag] = typedArrayTags[boolTag] = typedArrayTags[dateTag] = typedArrayTags[errorTag] = typedArrayTags[funcTag] = typedArrayTags[mapTag] = typedArrayTags[numberTag] = typedArrayTags[objectTag] = typedArrayTags[regexpTag] = typedArrayTags[setTag] = typedArrayTags[stringTag] = typedArrayTags[weakMapTag] = false; /** Used for native method references. */ var objectProto = Object.prototype; /** * Used to resolve the [`toStringTag`](http://ecma-international.org/ecma-262/6.0/#sec-object.prototype.tostring) * of values. */ var objToString = objectProto.toString; /** * Checks if `value` is classified as a typed array. * * @static * @memberOf _ * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is correctly classified, else `false`. * @example * * _.isTypedArray(new Uint8Array); * // => true * * _.isTypedArray([]); * // => false */ function isTypedArray(value) { return isObjectLike(value) && isLength(value.length) && !!typedArrayTags[objToString.call(value)]; } module.exports = isTypedArray; },{"../internal/isLength":22,"../internal/isObjectLike":23}],34:[function(_dereq_,module,exports){ var baseCopy = _dereq_('../internal/baseCopy'), keysIn = _dereq_('../object/keysIn'); /** * Converts `value` to a plain object flattening inherited enumerable * properties of `value` to own properties of the plain object. * * @static * @memberOf _ * @category Lang * @param {*} value The value to convert. * @returns {Object} Returns the converted plain object. * @example * * function Foo() { * this.b = 2; * } * * Foo.prototype.c = 3; * * _.assign({ 'a': 1 }, new Foo); * // => { 'a': 1, 'b': 2 } * * _.assign({ 'a': 1 }, _.toPlainObject(new Foo)); * // => { 'a': 1, 'b': 2, 'c': 3 } */ function toPlainObject(value) { return baseCopy(value, keysIn(value)); } module.exports = toPlainObject; },{"../internal/baseCopy":7,"../object/keysIn":36}],35:[function(_dereq_,module,exports){ var getNative = _dereq_('../internal/getNative'), isArrayLike = _dereq_('../internal/isArrayLike'), isObject = _dereq_('../lang/isObject'), shimKeys = _dereq_('../internal/shimKeys'), support = _dereq_('../support'); /* Native method references for those with the same name as other `lodash` methods. */ var nativeKeys = getNative(Object, 'keys'); /** * Creates an array of the own enumerable property names of `object`. * * **Note:** Non-object values are coerced to objects. See the * [ES spec](http://ecma-international.org/ecma-262/6.0/#sec-object.keys) * for more details. * * @static * @memberOf _ * @category Object * @param {Object} object The object to query. * @returns {Array} Returns the array of property names. * @example * * function Foo() { * this.a = 1; * this.b = 2; * } * * Foo.prototype.c = 3; * * _.keys(new Foo); * // => ['a', 'b'] (iteration order is not guaranteed) * * _.keys('hi'); * // => ['0', '1'] */ var keys = !nativeKeys ? shimKeys : function(object) { var Ctor = object == null ? undefined : object.constructor; if ((typeof Ctor == 'function' && Ctor.prototype === object) || (typeof object == 'function' ? support.enumPrototypes : isArrayLike(object))) { return shimKeys(object); } return isObject(object) ? nativeKeys(object) : []; }; module.exports = keys; },{"../internal/getNative":17,"../internal/isArrayLike":18,"../internal/shimKeys":24,"../lang/isObject":30,"../support":38}],36:[function(_dereq_,module,exports){ var arrayEach = _dereq_('../internal/arrayEach'), isArguments = _dereq_('../lang/isArguments'), isArray = _dereq_('../lang/isArray'), isFunction = _dereq_('../lang/isFunction'), isIndex = _dereq_('../internal/isIndex'), isLength = _dereq_('../internal/isLength'), isObject = _dereq_('../lang/isObject'), isString = _dereq_('../lang/isString'), support = _dereq_('../support'); /** `Object#toString` result references. */ var arrayTag = '[object Array]', boolTag = '[object Boolean]', dateTag = '[object Date]', errorTag = '[object Error]', funcTag = '[object Function]', numberTag = '[object Number]', objectTag = '[object Object]', regexpTag = '[object RegExp]', stringTag = '[object String]'; /** Used to fix the JScript `[[DontEnum]]` bug. */ var shadowProps = [ 'constructor', 'hasOwnProperty', 'isPrototypeOf', 'propertyIsEnumerable', 'toLocaleString', 'toString', 'valueOf' ]; /** Used for native method references. */ var errorProto = Error.prototype, objectProto = Object.prototype, stringProto = String.prototype; /** Used to check objects for own properties. */ var hasOwnProperty = objectProto.hasOwnProperty; /** * Used to resolve the [`toStringTag`](http://ecma-international.org/ecma-262/6.0/#sec-object.prototype.tostring) * of values. */ var objToString = objectProto.toString; /** Used to avoid iterating over non-enumerable properties in IE < 9. */ var nonEnumProps = {}; nonEnumProps[arrayTag] = nonEnumProps[dateTag] = nonEnumProps[numberTag] = { 'constructor': true, 'toLocaleString': true, 'toString': true, 'valueOf': true }; nonEnumProps[boolTag] = nonEnumProps[stringTag] = { 'constructor': true, 'toString': true, 'valueOf': true }; nonEnumProps[errorTag] = nonEnumProps[funcTag] = nonEnumProps[regexpTag] = { 'constructor': true, 'toString': true }; nonEnumProps[objectTag] = { 'constructor': true }; arrayEach(shadowProps, function(key) { for (var tag in nonEnumProps) { if (hasOwnProperty.call(nonEnumProps, tag)) { var props = nonEnumProps[tag]; props[key] = hasOwnProperty.call(props, key); } } }); /** * Creates an array of the own and inherited enumerable property names of `object`. * * **Note:** Non-object values are coerced to objects. * * @static * @memberOf _ * @category Object * @param {Object} object The object to query. * @returns {Array} Returns the array of property names. * @example * * function Foo() { * this.a = 1; * this.b = 2; * } * * Foo.prototype.c = 3; * * _.keysIn(new Foo); * // => ['a', 'b', 'c'] (iteration order is not guaranteed) */ function keysIn(object) { if (object == null) { return []; } if (!isObject(object)) { object = Object(object); } var length = object.length; length = (length && isLength(length) && (isArray(object) || isArguments(object) || isString(object)) && length) || 0; var Ctor = object.constructor, index = -1, proto = (isFunction(Ctor) && Ctor.prototype) || objectProto, isProto = proto === object, result = Array(length), skipIndexes = length > 0, skipErrorProps = support.enumErrorProps && (object === errorProto || object instanceof Error), skipProto = support.enumPrototypes && isFunction(object); while (++index < length) { result[index] = (index + ''); } // lodash skips the `constructor` property when it infers it's iterating // over a `prototype` object because IE < 9 can't set the `[[Enumerable]]` // attribute of an existing property and the `constructor` property of a // prototype defaults to non-enumerable. for (var key in object) { if (!(skipProto && key == 'prototype') && !(skipErrorProps && (key == 'message' || key == 'name')) && !(skipIndexes && isIndex(key, length)) && !(key == 'constructor' && (isProto || !hasOwnProperty.call(object, key)))) { result.push(key); } } if (support.nonEnumShadows && object !== objectProto) { var tag = object === stringProto ? stringTag : (object === errorProto ? errorTag : objToString.call(object)), nonEnums = nonEnumProps[tag] || nonEnumProps[objectTag]; if (tag == objectTag) { proto = objectProto; } length = shadowProps.length; while (length--) { key = shadowProps[length]; var nonEnum = nonEnums[key]; if (!(isProto && nonEnum) && (nonEnum ? hasOwnProperty.call(object, key) : object[key] !== proto[key])) { result.push(key); } } } return result; } module.exports = keysIn; },{"../internal/arrayEach":6,"../internal/isIndex":20,"../internal/isLength":22,"../lang/isArguments":26,"../lang/isArray":27,"../lang/isFunction":28,"../lang/isObject":30,"../lang/isString":32,"../support":38}],37:[function(_dereq_,module,exports){ var baseMerge = _dereq_('../internal/baseMerge'), createAssigner = _dereq_('../internal/createAssigner'); /** * Recursively merges own enumerable properties of the source object(s), that * don't resolve to `undefined` into the destination object. Subsequent sources * overwrite property assignments of previous sources. If `customizer` is * provided it's invoked to produce the merged values of the destination and * source properties. If `customizer` returns `undefined` merging is handled * by the method instead. The `customizer` is bound to `thisArg` and invoked * with five arguments: (objectValue, sourceValue, key, object, source). * * @static * @memberOf _ * @category Object * @param {Object} object The destination object. * @param {...Object} [sources] The source objects. * @param {Function} [customizer] The function to customize assigned values. * @param {*} [thisArg] The `this` binding of `customizer`. * @returns {Object} Returns `object`. * @example * * var users = { * 'data': [{ 'user': 'barney' }, { 'user': 'fred' }] * }; * * var ages = { * 'data': [{ 'age': 36 }, { 'age': 40 }] * }; * * _.merge(users, ages); * // => { 'data': [{ 'user': 'barney', 'age': 36 }, { 'user': 'fred', 'age': 40 }] } * * // using a customizer callback * var object = { * 'fruits': ['apple'], * 'vegetables': ['beet'] * }; * * var other = { * 'fruits': ['banana'], * 'vegetables': ['carrot'] * }; * * _.merge(object, other, function(a, b) { * if (_.isArray(a)) { * return a.concat(b); * } * }); * // => { 'fruits': ['apple', 'banana'], 'vegetables': ['beet', 'carrot'] } */ var merge = createAssigner(baseMerge); module.exports = merge; },{"../internal/baseMerge":10,"../internal/createAssigner":14}],38:[function(_dereq_,module,exports){ /** Used for native method references. */ var arrayProto = Array.prototype, errorProto = Error.prototype, objectProto = Object.prototype; /** Native method references. */ var propertyIsEnumerable = objectProto.propertyIsEnumerable, splice = arrayProto.splice; /** * An object environment feature flags. * * @static * @memberOf _ * @type Object */ var support = {}; (function(x) { var Ctor = function() { this.x = x; }, object = { '0': x, 'length': x }, props = []; Ctor.prototype = { 'valueOf': x, 'y': x }; for (var key in new Ctor) { props.push(key); } /** * Detect if `name` or `message` properties of `Error.prototype` are * enumerable by default (IE < 9, Safari < 5.1). * * @memberOf _.support * @type boolean */ support.enumErrorProps = propertyIsEnumerable.call(errorProto, 'message') || propertyIsEnumerable.call(errorProto, 'name'); /** * Detect if `prototype` properties are enumerable by default. * * Firefox < 3.6, Opera > 9.50 - Opera < 11.60, and Safari < 5.1 * (if the prototype or a property on the prototype has been set) * incorrectly set the `[[Enumerable]]` value of a function's `prototype` * property to `true`. * * @memberOf _.support * @type boolean */ support.enumPrototypes = propertyIsEnumerable.call(Ctor, 'prototype'); /** * Detect if properties shadowing those on `Object.prototype` are non-enumerable. * * In IE < 9 an object's own properties, shadowing non-enumerable ones, * are made non-enumerable as well (a.k.a the JScript `[[DontEnum]]` bug). * * @memberOf _.support * @type boolean */ support.nonEnumShadows = !/valueOf/.test(props); /** * Detect if own properties are iterated after inherited properties (IE < 9). * * @memberOf _.support * @type boolean */ support.ownLast = props[0] != 'x'; /** * Detect if `Array#shift` and `Array#splice` augment array-like objects * correctly. * * Firefox < 10, compatibility modes of IE 8, and IE < 9 have buggy Array * `shift()` and `splice()` functions that fail to remove the last element, * `value[0]`, of array-like objects even though the "length" property is * set to `0`. The `shift()` method is buggy in compatibility modes of IE 8, * while `splice()` is buggy regardless of mode in IE < 9. * * @memberOf _.support * @type boolean */ support.spliceObjects = (splice.call(object, 0, 1), !object[0]); /** * Detect lack of support for accessing string characters by index. * * IE < 8 can't access characters by index. IE 8 can only access characters * by index on string literals, not string objects. * * @memberOf _.support * @type boolean */ support.unindexedChars = ('x'[0] + Object('x')[0]) != 'xx'; }(1, 0)); module.exports = support; },{}],39:[function(_dereq_,module,exports){ /** * This method returns the first argument provided to it. * * @static * @memberOf _ * @category Utility * @param {*} value Any value. * @returns {*} Returns `value`. * @example * * var object = { 'user': 'fred' }; * * _.identity(object) === object; * // => true */ function identity(value) { return value; } module.exports = identity; },{}],40:[function(_dereq_,module,exports){ 'use strict'; // modified from https://github.com/es-shims/es6-shim var keys = _dereq_('object-keys'); var canBeObject = function (obj) { return typeof obj !== 'undefined' && obj !== null; }; var hasSymbols = typeof Symbol === 'function' && typeof Symbol() === 'symbol'; var defineProperties = _dereq_('define-properties'); var toObject = Object; var push = Array.prototype.push; var propIsEnumerable = Object.prototype.propertyIsEnumerable; var assignShim = function assign(target, source1) { if (!canBeObject(target)) { throw new TypeError('target must be an object'); } var objTarget = toObject(target); var s, source, i, props, syms; for (s = 1; s < arguments.length; ++s) { source = toObject(arguments[s]); props = keys(source); if (hasSymbols && Object.getOwnPropertySymbols) { syms = Object.getOwnPropertySymbols(source); for (i = 0; i < syms.length; ++i) { if (propIsEnumerable.call(source, syms[i])) { push.call(props, syms[i]); } } } for (i = 0; i < props.length; ++i) { objTarget[props[i]] = source[props[i]]; } } return objTarget; }; defineProperties(assignShim, { shim: function shimObjectAssign() { var assignHasPendingExceptions = function () { if (!Object.assign || !Object.preventExtensions) { return false; } // Firefox 37 still has "pending exception" logic in its Object.assign implementation, // which is 72% slower than our shim, and Firefox 40's native implementation. var thrower = Object.preventExtensions({ 1: 2 }); try { Object.assign(thrower, 'xy'); } catch (e) { return thrower[1] === 'y'; } }; defineProperties( Object, { assign: assignShim }, { assign: assignHasPendingExceptions } ); return Object.assign || assignShim; } }); module.exports = assignShim; },{"define-properties":41,"object-keys":43}],41:[function(_dereq_,module,exports){ 'use strict'; var keys = _dereq_('object-keys'); var foreach = _dereq_('foreach'); var hasSymbols = typeof Symbol === 'function' && typeof Symbol() === 'symbol'; var toStr = Object.prototype.toString; var isFunction = function (fn) { return typeof fn === 'function' && toStr.call(fn) === '[object Function]'; }; var arePropertyDescriptorsSupported = function () { var obj = {}; try { Object.defineProperty(obj, 'x', { value: obj, enumerable: false }); /* eslint-disable no-unused-vars */ for (var _ in obj) { return false; } /* eslint-enable no-unused-vars */ return obj.x === obj; } catch (e) { /* this is IE 8. */ return false; } }; var supportsDescriptors = Object.defineProperty && arePropertyDescriptorsSupported(); var defineProperty = function (object, name, value, predicate) { if (name in object && (!isFunction(predicate) || !predicate())) { return; } if (supportsDescriptors) { Object.defineProperty(object, name, { configurable: true, enumerable: false, writable: true, value: value }); } else { object[name] = value; } }; var defineProperties = function (object, map) { var predicates = arguments.length > 2 ? arguments[2] : {}; var props = keys(map); if (hasSymbols) { props = props.concat(Object.getOwnPropertySymbols(map)); } foreach(props, function (name) { defineProperty(object, name, map[name], predicates[name]); }); }; defineProperties.supportsDescriptors = !!supportsDescriptors; module.exports = defineProperties; },{"foreach":42,"object-keys":43}],42:[function(_dereq_,module,exports){ var hasOwn = Object.prototype.hasOwnProperty; var toString = Object.prototype.toString; module.exports = function forEach (obj, fn, ctx) { if (toString.call(fn) !== '[object Function]') { throw new TypeError('iterator must be a function'); } var l = obj.length; if (l === +l) { for (var i = 0; i < l; i++) { fn.call(ctx, obj[i], i, obj); } } else { for (var k in obj) { if (hasOwn.call(obj, k)) { fn.call(ctx, obj[k], k, obj); } } } }; },{}],43:[function(_dereq_,module,exports){ 'use strict'; // modified from https://github.com/es-shims/es5-shim var has = Object.prototype.hasOwnProperty; var toStr = Object.prototype.toString; var slice = Array.prototype.slice; var isArgs = _dereq_('./isArguments'); var hasDontEnumBug = !({ 'toString': null }).propertyIsEnumerable('toString'); var hasProtoEnumBug = function () {}.propertyIsEnumerable('prototype'); var dontEnums = [ 'toString', 'toLocaleString', 'valueOf', 'hasOwnProperty', 'isPrototypeOf', 'propertyIsEnumerable', 'constructor' ]; var equalsConstructorPrototype = function (o) { var ctor = o.constructor; return ctor && ctor.prototype === o; }; var blacklistedKeys = { $window: true, $console: true, $parent: true, $self: true, $frames: true, $webkitIndexedDB: true, $webkitStorageInfo: true }; var hasAutomationEqualityBug = (function () { /* global window */ if (typeof window === 'undefined') { return false; } for (var k in window) { if (!blacklistedKeys['$' + k] && has.call(window, k) && window[k] !== null && typeof window[k] === 'object') { try { equalsConstructorPrototype(window[k]); } catch (e) { return true; } } } return false; }()); var equalsConstructorPrototypeIfNotBuggy = function (o) { /* global window */ if (typeof window === 'undefined' && !hasAutomationEqualityBug) { return equalsConstructorPrototype(o); } try { return equalsConstructorPrototype(o); } catch (e) { return false; } }; var keysShim = function keys(object) { var isObject = object !== null && typeof object === 'object'; var isFunction = toStr.call(object) === '[object Function]'; var isArguments = isArgs(object); var isString = isObject && toStr.call(object) === '[object String]'; var theKeys = []; if (!isObject && !isFunction && !isArguments) { throw new TypeError('Object.keys called on a non-object'); } var skipProto = hasProtoEnumBug && isFunction; if (isString && object.length > 0 && !has.call(object, 0)) { for (var i = 0; i < object.length; ++i) { theKeys.push(String(i)); } } if (isArguments && object.length > 0) { for (var j = 0; j < object.length; ++j) { theKeys.push(String(j)); } } else { for (var name in object) { if (!(skipProto && name === 'prototype') && has.call(object, name)) { theKeys.push(String(name)); } } } if (hasDontEnumBug) { var skipConstructor = equalsConstructorPrototypeIfNotBuggy(object); for (var k = 0; k < dontEnums.length; ++k) { if (!(skipConstructor && dontEnums[k] === 'constructor') && has.call(object, dontEnums[k])) { theKeys.push(dontEnums[k]); } } } return theKeys; }; keysShim.shim = function shimObjectKeys() { if (!Object.keys) { Object.keys = keysShim; } else { var keysWorksWithArguments = (function () { // Safari 5.0 bug return (Object.keys(arguments) || '').length === 2; }(1, 2)); if (!keysWorksWithArguments) { var originalKeys = Object.keys; Object.keys = function keys(object) { if (isArgs(object)) { return originalKeys(slice.call(object)); } else { return originalKeys(object); } }; } } return Object.keys || keysShim; }; module.exports = keysShim; },{"./isArguments":44}],44:[function(_dereq_,module,exports){ 'use strict'; var toStr = Object.prototype.toString; module.exports = function isArguments(value) { var str = toStr.call(value); var isArgs = str === '[object Arguments]'; if (!isArgs) { isArgs = str !== '[object Array]' && value !== null && typeof value === 'object' && typeof value.length === 'number' && value.length >= 0 && toStr.call(value.callee) === '[object Function]'; } return isArgs; }; },{}],45:[function(_dereq_,module,exports){ module.exports = SafeParseTuple function SafeParseTuple(obj, reviver) { var json var error = null try { json = JSON.parse(obj, reviver) } catch (err) { error = err } return [error, json] } },{}],46:[function(_dereq_,module,exports){ /** * @file big-play-button.js */ 'use strict'; exports.__esModule = true; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var _buttonJs = _dereq_('./button.js'); var _buttonJs2 = _interopRequireDefault(_buttonJs); var _componentJs = _dereq_('./component.js'); var _componentJs2 = _interopRequireDefault(_componentJs); /** * Initial play button. Shows before the video has played. The hiding of the * big play button is done via CSS and player states. * * @param {Object} player Main Player * @param {Object=} options Object of option names and values * @extends Button * @class BigPlayButton */ var BigPlayButton = (function (_Button) { _inherits(BigPlayButton, _Button); function BigPlayButton(player, options) { _classCallCheck(this, BigPlayButton); _Button.call(this, player, options); } /** * Allow sub components to stack CSS class names * * @return {String} The constructed class name * @method buildCSSClass */ BigPlayButton.prototype.buildCSSClass = function buildCSSClass() { return 'vjs-big-play-button'; }; /** * Handles click for play * * @method handleClick */ BigPlayButton.prototype.handleClick = function handleClick() { this.player_.play(); }; return BigPlayButton; })(_buttonJs2['default']); BigPlayButton.prototype.controlText_ = 'Play Video'; _componentJs2['default'].registerComponent('BigPlayButton', BigPlayButton); exports['default'] = BigPlayButton; module.exports = exports['default']; },{"./button.js":47,"./component.js":48}],47:[function(_dereq_,module,exports){ /** * @file button.js */ 'use strict'; exports.__esModule = true; function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj['default'] = obj; return newObj; } } function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var _component = _dereq_('./component'); var _component2 = _interopRequireDefault(_component); var _utilsDomJs = _dereq_('./utils/dom.js'); var Dom = _interopRequireWildcard(_utilsDomJs); var _utilsEventsJs = _dereq_('./utils/events.js'); var Events = _interopRequireWildcard(_utilsEventsJs); var _utilsFnJs = _dereq_('./utils/fn.js'); var Fn = _interopRequireWildcard(_utilsFnJs); var _globalDocument = _dereq_('global/document'); var _globalDocument2 = _interopRequireDefault(_globalDocument); var _objectAssign = _dereq_('object.assign'); var _objectAssign2 = _interopRequireDefault(_objectAssign); /** * Base class for all buttons * * @param {Object} player Main Player * @param {Object=} options Object of option names and values * @extends Component * @class Button */ var Button = (function (_Component) { _inherits(Button, _Component); function Button(player, options) { _classCallCheck(this, Button); _Component.call(this, player, options); this.emitTapEvents(); this.on('tap', this.handleClick); this.on('click', this.handleClick); this.on('focus', this.handleFocus); this.on('blur', this.handleBlur); } /** * Create the component's DOM element * * @param {String=} type Element's node type. e.g. 'div' * @param {Object=} props An object of element attributes that should be set on the element Tag name * @return {Element} * @method createEl */ Button.prototype.createEl = function createEl() { var tag = arguments.length <= 0 || arguments[0] === undefined ? 'button' : arguments[0]; var props = arguments.length <= 1 || arguments[1] === undefined ? {} : arguments[1]; // Add standard Aria and Tabindex info props = _objectAssign2['default']({ className: this.buildCSSClass(), 'role': 'button', 'type': 'button', // Necessary since the default button type is "submit" 'aria-live': 'polite', // let the screen reader user know that the text of the button may change tabIndex: 0 }, props); var el = _Component.prototype.createEl.call(this, tag, props); this.controlTextEl_ = Dom.createEl('span', { className: 'vjs-control-text' }); el.appendChild(this.controlTextEl_); this.controlText(this.controlText_); return el; }; /** * Controls text - both request and localize * * @param {String} text Text for button * @return {String} * @method controlText */ Button.prototype.controlText = function controlText(text) { if (!text) return this.controlText_ || 'Need Text'; this.controlText_ = text; this.controlTextEl_.innerHTML = this.localize(this.controlText_); return this; }; /** * Allows sub components to stack CSS class names * * @return {String} * @method buildCSSClass */ Button.prototype.buildCSSClass = function buildCSSClass() { return 'vjs-control vjs-button ' + _Component.prototype.buildCSSClass.call(this); }; /** * Handle Click - Override with specific functionality for button * * @method handleClick */ Button.prototype.handleClick = function handleClick() {}; /** * Handle Focus - Add keyboard functionality to element * * @method handleFocus */ Button.prototype.handleFocus = function handleFocus() { Events.on(_globalDocument2['default'], 'keydown', Fn.bind(this, this.handleKeyPress)); }; /** * Handle KeyPress (document level) - Trigger click when keys are pressed * * @method handleKeyPress */ Button.prototype.handleKeyPress = function handleKeyPress(event) { // Check for space bar (32) or enter (13) keys if (event.which === 32 || event.which === 13) { event.preventDefault(); this.handleClick(event); } }; /** * Handle Blur - Remove keyboard triggers * * @method handleBlur */ Button.prototype.handleBlur = function handleBlur() { Events.off(_globalDocument2['default'], 'keydown', Fn.bind(this, this.handleKeyPress)); }; return Button; })(_component2['default']); _component2['default'].registerComponent('Button', Button); exports['default'] = Button; module.exports = exports['default']; },{"./component":48,"./utils/dom.js":107,"./utils/events.js":108,"./utils/fn.js":109,"global/document":1,"object.assign":40}],48:[function(_dereq_,module,exports){ /** * @file component.js * * Player Component - Base class for all UI objects */ 'use strict'; exports.__esModule = true; function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj['default'] = obj; return newObj; } } function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } var _globalWindow = _dereq_('global/window'); var _globalWindow2 = _interopRequireDefault(_globalWindow); var _utilsDomJs = _dereq_('./utils/dom.js'); var Dom = _interopRequireWildcard(_utilsDomJs); var _utilsFnJs = _dereq_('./utils/fn.js'); var Fn = _interopRequireWildcard(_utilsFnJs); var _utilsGuidJs = _dereq_('./utils/guid.js'); var Guid = _interopRequireWildcard(_utilsGuidJs); var _utilsEventsJs = _dereq_('./utils/events.js'); var Events = _interopRequireWildcard(_utilsEventsJs); var _utilsLogJs = _dereq_('./utils/log.js'); var _utilsLogJs2 = _interopRequireDefault(_utilsLogJs); var _utilsToTitleCaseJs = _dereq_('./utils/to-title-case.js'); var _utilsToTitleCaseJs2 = _interopRequireDefault(_utilsToTitleCaseJs); var _objectAssign = _dereq_('object.assign'); var _objectAssign2 = _interopRequireDefault(_objectAssign); var _utilsMergeOptionsJs = _dereq_('./utils/merge-options.js'); var _utilsMergeOptionsJs2 = _interopRequireDefault(_utilsMergeOptionsJs); /** * Base UI Component class * Components are embeddable UI objects that are represented by both a * javascript object and an element in the DOM. They can be children of other * components, and can have many children themselves. * ```js * // adding a button to the player * var button = player.addChild('button'); * button.el(); // -> button element * ``` * ```html * <div class="video-js"> * <div class="vjs-button">Button</div> * </div> * ``` * Components are also event targets. * ```js * button.on('click', function(){ * console.log('Button Clicked!'); * }); * button.trigger('customevent'); * ``` * * @param {Object} player Main Player * @param {Object=} options Object of option names and values * @param {Function=} ready Ready callback function * @class Component */ var Component = (function () { function Component(player, options, ready) { _classCallCheck(this, Component); // The component might be the player itself and we can't pass `this` to super if (!player && this.play) { this.player_ = player = this; // eslint-disable-line } else { this.player_ = player; } // Make a copy of prototype.options_ to protect against overriding defaults this.options_ = _utilsMergeOptionsJs2['default']({}, this.options_); // Updated options with supplied options options = this.options_ = _utilsMergeOptionsJs2['default'](this.options_, options); // Get ID from options or options element if one is supplied this.id_ = options.id || options.el && options.el.id; // If there was no ID from the options, generate one if (!this.id_) { // Don't require the player ID function in the case of mock players var id = player && player.id && player.id() || 'no_player'; this.id_ = id + '_component_' + Guid.newGUID(); } this.name_ = options.name || null; // Create element if one wasn't provided in options if (options.el) { this.el_ = options.el; } else if (options.createEl !== false) { this.el_ = this.createEl(); } this.children_ = []; this.childIndex_ = {}; this.childNameIndex_ = {}; // Add any child components in options if (options.initChildren !== false) { this.initChildren(); } this.ready(ready); // Don't want to trigger ready here or it will before init is actually // finished for all children that run this constructor if (options.reportTouchActivity !== false) { this.enableTouchActivity(); } } /** * Dispose of the component and all child components * * @method dispose */ Component.prototype.dispose = function dispose() { this.trigger({ type: 'dispose', bubbles: false }); // Dispose all children. if (this.children_) { for (var i = this.children_.length - 1; i >= 0; i--) { if (this.children_[i].dispose) { this.children_[i].dispose(); } } } // Delete child references this.children_ = null; this.childIndex_ = null; this.childNameIndex_ = null; // Remove all event listeners. this.off(); // Remove element from DOM if (this.el_.parentNode) { this.el_.parentNode.removeChild(this.el_); } Dom.removeElData(this.el_); this.el_ = null; }; /** * Return the component's player * * @return {Player} * @method player */ Component.prototype.player = function player() { return this.player_; }; /** * Deep merge of options objects * Whenever a property is an object on both options objects * the two properties will be merged using mergeOptions. * This is used for merging options for child components. We * want it to be easy to override individual options on a child * component without having to rewrite all the other default options. * ```js * Parent.prototype.options_ = { * children: { * 'childOne': { 'foo': 'bar', 'asdf': 'fdsa' }, * 'childTwo': {}, * 'childThree': {} * } * } * newOptions = { * children: { * 'childOne': { 'foo': 'baz', 'abc': '123' } * 'childTwo': null, * 'childFour': {} * } * } * * this.options(newOptions); * ``` * RESULT * ```js * { * children: { * 'childOne': { 'foo': 'baz', 'asdf': 'fdsa', 'abc': '123' }, * 'childTwo': null, // Disabled. Won't be initialized. * 'childThree': {}, * 'childFour': {} * } * } * ``` * * @param {Object} obj Object of new option values * @return {Object} A NEW object of this.options_ and obj merged * @method options */ Component.prototype.options = function options(obj) { _utilsLogJs2['default'].warn('this.options() has been deprecated and will be moved to the constructor in 6.0'); if (!obj) { return this.options_; } this.options_ = _utilsMergeOptionsJs2['default'](this.options_, obj); return this.options_; }; /** * Get the component's DOM element * ```js * var domEl = myComponent.el(); * ``` * * @return {Element} * @method el */ Component.prototype.el = function el() { return this.el_; }; /** * Create the component's DOM element * * @param {String=} tagName Element's node type. e.g. 'div' * @param {Object=} attributes An object of element attributes that should be set on the element * @return {Element} * @method createEl */ Component.prototype.createEl = function createEl(tagName, attributes) { return Dom.createEl(tagName, attributes); }; Component.prototype.localize = function localize(string) { var code = this.player_.language && this.player_.language(); var languages = this.player_.languages && this.player_.languages(); if (!code || !languages) { return string; } var language = languages[code]; if (language && language[string]) { return language[string]; } var primaryCode = code.split('-')[0]; var primaryLang = languages[primaryCode]; if (primaryLang && primaryLang[string]) { return primaryLang[string]; } return string; }; /** * Return the component's DOM element where children are inserted. * Will either be the same as el() or a new element defined in createEl(). * * @return {Element} * @method contentEl */ Component.prototype.contentEl = function contentEl() { return this.contentEl_ || this.el_; }; /** * Get the component's ID * ```js * var id = myComponent.id(); * ``` * * @return {String} * @method id */ Component.prototype.id = function id() { return this.id_; }; /** * Get the component's name. The name is often used to reference the component. * ```js * var name = myComponent.name(); * ``` * * @return {String} * @method name */ Component.prototype.name = function name() { return this.name_; }; /** * Get an array of all child components * ```js * var kids = myComponent.children(); * ``` * * @return {Array} The children * @method children */ Component.prototype.children = function children() { return this.children_; }; /** * Returns a child component with the provided ID * * @return {Component} * @method getChildById */ Component.prototype.getChildById = function getChildById(id) { return this.childIndex_[id]; }; /** * Returns a child component with the provided name * * @return {Component} * @method getChild */ Component.prototype.getChild = function getChild(name) { return this.childNameIndex_[name]; }; /** * Adds a child component inside this component * ```js * myComponent.el(); * // -> <div class='my-component'></div> * myComponent.children(); * // [empty array] * * var myButton = myComponent.addChild('MyButton'); * // -> <div class='my-component'><div class="my-button">myButton<div></div> * // -> myButton === myComonent.children()[0]; * ``` * Pass in options for child constructors and options for children of the child * ```js * var myButton = myComponent.addChild('MyButton', { * text: 'Press Me', * children: { * buttonChildExample: { * buttonChildOption: true * } * } * }); * ``` * * @param {String|Component} child The class name or instance of a child to add * @param {Object=} options Options, including options to be passed to children of the child. * @return {Component} The child component (created by this process if a string was used) * @method addChild */ Component.prototype.addChild = function addChild(child) { var options = arguments.length <= 1 || arguments[1] === undefined ? {} : arguments[1]; var component = undefined; var componentName = undefined; // If child is a string, create nt with options if (typeof child === 'string') { componentName = child; // Options can also be specified as a boolean, so convert to an empty object if false. if (!options) { options = {}; } // Same as above, but true is deprecated so show a warning. if (options === true) { _utilsLogJs2['default'].warn('Initializing a child component with `true` is deprecated. Children should be defined in an array when possible, but if necessary use an object instead of `true`.'); options = {}; } // If no componentClass in options, assume componentClass is the name lowercased // (e.g. playButton) var componentClassName = options.componentClass || _utilsToTitleCaseJs2['default'](componentName); // Set name through options options.name = componentName; // Create a new object & element for this controls set // If there's no .player_, this is a player var ComponentClass = Component.getComponent(componentClassName); component = new ComponentClass(this.player_ || this, options); // child is a component instance } else { component = child; } this.children_.push(component); if (typeof component.id === 'function') { this.childIndex_[component.id()] = component; } // If a name wasn't used to create the component, check if we can use the // name function of the component componentName = componentName || component.name && component.name(); if (componentName) { this.childNameIndex_[componentName] = component; } // Add the UI object's element to the container div (box) // Having an element is not required if (typeof component.el === 'function' && component.el()) { this.contentEl().appendChild(component.el()); } // Return so it can stored on parent object if desired. return component; }; /** * Remove a child component from this component's list of children, and the * child component's element from this component's element * * @param {Component} component Component to remove * @method removeChild */ Component.prototype.removeChild = function removeChild(component) { if (typeof component === 'string') { component = this.getChild(component); } if (!component || !this.children_) { return; } var childFound = false; for (var i = this.children_.length - 1; i >= 0; i--) { if (this.children_[i] === component) { childFound = true; this.children_.splice(i, 1); break; } } if (!childFound) { return; } this.childIndex_[component.id()] = null; this.childNameIndex_[component.name()] = null; var compEl = component.el(); if (compEl && compEl.parentNode === this.contentEl()) { this.contentEl().removeChild(component.el()); } }; /** * Add and initialize default child components from options * ```js * // when an instance of MyComponent is created, all children in options * // will be added to the instance by their name strings and options * MyComponent.prototype.options_.children = { * myChildComponent: { * myChildOption: true * } * } * ``` * // Or when creating the component * ```js * var myComp = new MyComponent(player, { * children: { * myChildComponent: { * myChildOption: true * } * } * }); * ``` * The children option can also be an Array of child names or * child options objects (that also include a 'name' key). * ```js * var myComp = new MyComponent(player, { * children: [ * 'button', * { * name: 'button', * someOtherOption: true * } * ] * }); * ``` * * @method initChildren */ Component.prototype.initChildren = function initChildren() { var _this = this; var children = this.options_.children; if (children) { (function () { // `this` is `parent` var parentOptions = _this.options_; var handleAdd = function handleAdd(name, opts) { // Allow options for children to be set at the parent options // e.g. videojs(id, { controlBar: false }); // instead of videojs(id, { children: { controlBar: false }); if (parentOptions[name] !== undefined) { opts = parentOptions[name]; } // Allow for disabling default components // e.g. options['children']['posterImage'] = false if (opts === false) { return; } // Allow options to be passed as a simple boolean if no configuration // is necessary. if (opts === true) { opts = {}; } // We also want to pass the original player options to each component as well so they don't need to // reach back into the player for options later. opts.playerOptions = _this.options_.playerOptions; // Create and add the child component. // Add a direct reference to the child by name on the parent instance. // If two of the same component are used, different names should be supplied // for each _this[name] = _this.addChild(name, opts); }; // Allow for an array of children details to passed in the options if (Array.isArray(children)) { for (var i = 0; i < children.length; i++) { var child = children[i]; var _name = undefined; var opts = undefined; if (typeof child === 'string') { // ['myComponent'] _name = child; opts = {}; } else { // [{ name: 'myComponent', otherOption: true }] _name = child.name; opts = child; } handleAdd(_name, opts); } } else { Object.getOwnPropertyNames(children).forEach(function (name) { handleAdd(name, children[name]); }); } })(); } }; /** * Allows sub components to stack CSS class names * * @return {String} The constructed class name * @method buildCSSClass */ Component.prototype.buildCSSClass = function buildCSSClass() { // Child classes can include a function that does: // return 'CLASS NAME' + this._super(); return ''; }; /** * Add an event listener to this component's element * ```js * var myFunc = function(){ * var myComponent = this; * // Do something when the event is fired * }; * * myComponent.on('eventType', myFunc); * ``` * The context of myFunc will be myComponent unless previously bound. * Alternatively, you can add a listener to another element or component. * ```js * myComponent.on(otherElement, 'eventName', myFunc); * myComponent.on(otherComponent, 'eventName', myFunc); * ``` * The benefit of using this over `VjsEvents.on(otherElement, 'eventName', myFunc)` * and `otherComponent.on('eventName', myFunc)` is that this way the listeners * will be automatically cleaned up when either component is disposed. * It will also bind myComponent as the context of myFunc. * **NOTE**: When using this on elements in the page other than window * and document (both permanent), if you remove the element from the DOM * you need to call `myComponent.trigger(el, 'dispose')` on it to clean up * references to it and allow the browser to garbage collect it. * * @param {String|Component} first The event type or other component * @param {Function|String} second The event handler or event type * @param {Function} third The event handler * @return {Component} * @method on */ Component.prototype.on = function on(first, second, third) { var _this2 = this; if (typeof first === 'string' || Array.isArray(first)) { Events.on(this.el_, first, Fn.bind(this, second)); // Targeting another component or element } else { (function () { var target = first; var type = second; var fn = Fn.bind(_this2, third); // When this component is disposed, remove the listener from the other component var removeOnDispose = function removeOnDispose() { return _this2.off(target, type, fn); }; // Use the same function ID so we can remove it later it using the ID // of the original listener removeOnDispose.guid = fn.guid; _this2.on('dispose', removeOnDispose); // If the other component is disposed first we need to clean the reference // to the other component in this component's removeOnDispose listener // Otherwise we create a memory leak. var cleanRemover = function cleanRemover() { return _this2.off('dispose', removeOnDispose); }; // Add the same function ID so we can easily remove it later cleanRemover.guid = fn.guid; // Check if this is a DOM node if (first.nodeName) { // Add the listener to the other element Events.on(target, type, fn); Events.on(target, 'dispose', cleanRemover); // Should be a component // Not using `instanceof Component` because it makes mock players difficult } else if (typeof first.on === 'function') { // Add the listener to the other component target.on(type, fn); target.on('dispose', cleanRemover); } })(); } return this; }; /** * Remove an event listener from this component's element * ```js * myComponent.off('eventType', myFunc); * ``` * If myFunc is excluded, ALL listeners for the event type will be removed. * If eventType is excluded, ALL listeners will be removed from the component. * Alternatively you can use `off` to remove listeners that were added to other * elements or components using `myComponent.on(otherComponent...`. * In this case both the event type and listener function are REQUIRED. * ```js * myComponent.off(otherElement, 'eventType', myFunc); * myComponent.off(otherComponent, 'eventType', myFunc); * ``` * * @param {String=|Component} first The event type or other component * @param {Function=|String} second The listener function or event type * @param {Function=} third The listener for other component * @return {Component} * @method off */ Component.prototype.off = function off(first, second, third) { if (!first || typeof first === 'string' || Array.isArray(first)) { Events.off(this.el_, first, second); } else { var target = first; var type = second; // Ensure there's at least a guid, even if the function hasn't been used var fn = Fn.bind(this, third); // Remove the dispose listener on this component, // which was given the same guid as the event listener this.off('dispose', fn); if (first.nodeName) { // Remove the listener Events.off(target, type, fn); // Remove the listener for cleaning the dispose listener Events.off(target, 'dispose', fn); } else { target.off(type, fn); target.off('dispose', fn); } } return this; }; /** * Add an event listener to be triggered only once and then removed * ```js * myComponent.one('eventName', myFunc); * ``` * Alternatively you can add a listener to another element or component * that will be triggered only once. * ```js * myComponent.one(otherElement, 'eventName', myFunc); * myComponent.one(otherComponent, 'eventName', myFunc); * ``` * * @param {String|Component} first The event type or other component * @param {Function|String} second The listener function or event type * @param {Function=} third The listener function for other component * @return {Component} * @method one */ Component.prototype.one = function one(first, second, third) { var _this3 = this, _arguments = arguments; if (typeof first === 'string' || Array.isArray(first)) { Events.one(this.el_, first, Fn.bind(this, second)); } else { (function () { var target = first; var type = second; var fn = Fn.bind(_this3, third); var newFunc = function newFunc() { _this3.off(target, type, newFunc); fn.apply(null, _arguments); }; // Keep the same function ID so we can remove it later newFunc.guid = fn.guid; _this3.on(target, type, newFunc); })(); } return this; }; /** * Trigger an event on an element * ```js * myComponent.trigger('eventName'); * myComponent.trigger({'type':'eventName'}); * myComponent.trigger('eventName', {data: 'some data'}); * myComponent.trigger({'type':'eventName'}, {data: 'some data'}); * ``` * * @param {Event|Object|String} event A string (the type) or an event object with a type attribute * @param {Object} [hash] data hash to pass along with the event * @return {Component} self * @method trigger */ Component.prototype.trigger = function trigger(event, hash) { Events.trigger(this.el_, event, hash); return this; }; /** * Bind a listener to the component's ready state. * Different from event listeners in that if the ready event has already happened * it will trigger the function immediately. * * @param {Function} fn Ready listener * @param {Boolean} sync Exec the listener synchronously if component is ready * @return {Component} * @method ready */ Component.prototype.ready = function ready(fn) { var sync = arguments.length <= 1 || arguments[1] === undefined ? false : arguments[1]; if (fn) { if (this.isReady_) { if (sync) { fn.call(this); } else { // Call the function asynchronously by default for consistency this.setTimeout(fn, 1); } } else { this.readyQueue_ = this.readyQueue_ || []; this.readyQueue_.push(fn); } } return this; }; /** * Trigger the ready listeners * * @return {Component} * @method triggerReady */ Component.prototype.triggerReady = function triggerReady() { this.isReady_ = true; // Ensure ready is triggerd asynchronously this.setTimeout(function () { var readyQueue = this.readyQueue_; if (readyQueue && readyQueue.length > 0) { readyQueue.forEach(function (fn) { fn.call(this); }, this); // Reset Ready Queue this.readyQueue_ = []; } // Allow for using event listeners also this.trigger('ready'); }, 1); }; /** * Check if a component's element has a CSS class name * * @param {String} classToCheck Classname to check * @return {Component} * @method hasClass */ Component.prototype.hasClass = function hasClass(classToCheck) { return Dom.hasElClass(this.el_, classToCheck); }; /** * Add a CSS class name to the component's element * * @param {String} classToAdd Classname to add * @return {Component} * @method addClass */ Component.prototype.addClass = function addClass(classToAdd) { Dom.addElClass(this.el_, classToAdd); return this; }; /** * Remove and return a CSS class name from the component's element * * @param {String} classToRemove Classname to remove * @return {Component} * @method removeClass */ Component.prototype.removeClass = function removeClass(classToRemove) { Dom.removeElClass(this.el_, classToRemove); return this; }; /** * Show the component element if hidden * * @return {Component} * @method show */ Component.prototype.show = function show() { this.removeClass('vjs-hidden'); return this; }; /** * Hide the component element if currently showing * * @return {Component} * @method hide */ Component.prototype.hide = function hide() { this.addClass('vjs-hidden'); return this; }; /** * Lock an item in its visible state * To be used with fadeIn/fadeOut. * * @return {Component} * @private * @method lockShowing */ Component.prototype.lockShowing = function lockShowing() { this.addClass('vjs-lock-showing'); return this; }; /** * Unlock an item to be hidden * To be used with fadeIn/fadeOut. * * @return {Component} * @private * @method unlockShowing */ Component.prototype.unlockShowing = function unlockShowing() { this.removeClass('vjs-lock-showing'); return this; }; /** * Set or get the width of the component (CSS values) * Setting the video tag dimension values only works with values in pixels. * Percent values will not work. * Some percents can be used, but width()/height() will return the number + %, * not the actual computed width/height. * * @param {Number|String=} num Optional width number * @param {Boolean} skipListeners Skip the 'resize' event trigger * @return {Component} This component, when setting the width * @return {Number|String} The width, when getting * @method width */ Component.prototype.width = function width(num, skipListeners) { return this.dimension('width', num, skipListeners); }; /** * Get or set the height of the component (CSS values) * Setting the video tag dimension values only works with values in pixels. * Percent values will not work. * Some percents can be used, but width()/height() will return the number + %, * not the actual computed width/height. * * @param {Number|String=} num New component height * @param {Boolean=} skipListeners Skip the resize event trigger * @return {Component} This component, when setting the height * @return {Number|String} The height, when getting * @method height */ Component.prototype.height = function height(num, skipListeners) { return this.dimension('height', num, skipListeners); }; /** * Set both width and height at the same time * * @param {Number|String} width Width of player * @param {Number|String} height Height of player * @return {Component} The component * @method dimensions */ Component.prototype.dimensions = function dimensions(width, height) { // Skip resize listeners on width for optimization return this.width(width, true).height(height); }; /** * Get or set width or height * This is the shared code for the width() and height() methods. * All for an integer, integer + 'px' or integer + '%'; * Known issue: Hidden elements officially have a width of 0. We're defaulting * to the style.width value and falling back to computedStyle which has the * hidden element issue. Info, but probably not an efficient fix: * http://www.foliotek.com/devblog/getting-the-width-of-a-hidden-element-with-jquery-using-width/ * * @param {String} widthOrHeight 'width' or 'height' * @param {Number|String=} num New dimension * @param {Boolean=} skipListeners Skip resize event trigger * @return {Component} The component if a dimension was set * @return {Number|String} The dimension if nothing was set * @private * @method dimension */ Component.prototype.dimension = function dimension(widthOrHeight, num, skipListeners) { if (num !== undefined) { // Set to zero if null or literally NaN (NaN !== NaN) if (num === null || num !== num) { num = 0; } // Check if using css width/height (% or px) and adjust if (('' + num).indexOf('%') !== -1 || ('' + num).indexOf('px') !== -1) { this.el_.style[widthOrHeight] = num; } else if (num === 'auto') { this.el_.style[widthOrHeight] = ''; } else { this.el_.style[widthOrHeight] = num + 'px'; } // skipListeners allows us to avoid triggering the resize event when setting both width and height if (!skipListeners) { this.trigger('resize'); } // Return component return this; } // Not setting a value, so getting it // Make sure element exists if (!this.el_) { return 0; } // Get dimension value from style var val = this.el_.style[widthOrHeight]; var pxIndex = val.indexOf('px'); if (pxIndex !== -1) { // Return the pixel value with no 'px' return parseInt(val.slice(0, pxIndex), 10); } // No px so using % or no style was set, so falling back to offsetWidth/height // If component has display:none, offset will return 0 // TODO: handle display:none and no dimension style using px return parseInt(this.el_['offset' + _utilsToTitleCaseJs2['default'](widthOrHeight)], 10); }; /** * Emit 'tap' events when touch events are supported * This is used to support toggling the controls through a tap on the video. * We're requiring them to be enabled because otherwise every component would * have this extra overhead unnecessarily, on mobile devices where extra * overhead is especially bad. * * @private * @method emitTapEvents */ Component.prototype.emitTapEvents = function emitTapEvents() { // Track the start time so we can determine how long the touch lasted var touchStart = 0; var firstTouch = null; // Maximum movement allowed during a touch event to still be considered a tap // Other popular libs use anywhere from 2 (hammer.js) to 15, so 10 seems like a nice, round number. var tapMovementThreshold = 10; // The maximum length a touch can be while still being considered a tap var touchTimeThreshold = 200; var couldBeTap = undefined; this.on('touchstart', function (event) { // If more than one finger, don't consider treating this as a click if (event.touches.length === 1) { // Copy the touches object to prevent modifying the original firstTouch = _objectAssign2['default']({}, event.touches[0]); // Record start time so we can detect a tap vs. "touch and hold" touchStart = new Date().getTime(); // Reset couldBeTap tracking couldBeTap = true; } }); this.on('touchmove', function (event) { // If more than one finger, don't consider treating this as a click if (event.touches.length > 1) { couldBeTap = false; } else if (firstTouch) { // Some devices will throw touchmoves for all but the slightest of taps. // So, if we moved only a small distance, this could still be a tap var xdiff = event.touches[0].pageX - firstTouch.pageX; var ydiff = event.touches[0].pageY - firstTouch.pageY; var touchDistance = Math.sqrt(xdiff * xdiff + ydiff * ydiff); if (touchDistance > tapMovementThreshold) { couldBeTap = false; } } }); var noTap = function noTap() { couldBeTap = false; }; // TODO: Listen to the original target. http://youtu.be/DujfpXOKUp8?t=13m8s this.on('touchleave', noTap); this.on('touchcancel', noTap); // When the touch ends, measure how long it took and trigger the appropriate // event this.on('touchend', function (event) { firstTouch = null; // Proceed only if the touchmove/leave/cancel event didn't happen if (couldBeTap === true) { // Measure how long the touch lasted var touchTime = new Date().getTime() - touchStart; // Make sure the touch was less than the threshold to be considered a tap if (touchTime < touchTimeThreshold) { // Don't let browser turn this into a click event.preventDefault(); this.trigger('tap'); // It may be good to copy the touchend event object and change the // type to tap, if the other event properties aren't exact after // Events.fixEvent runs (e.g. event.target) } } }); }; /** * Report user touch activity when touch events occur * User activity is used to determine when controls should show/hide. It's * relatively simple when it comes to mouse events, because any mouse event * should show the controls. So we capture mouse events that bubble up to the * player and report activity when that happens. * With touch events it isn't as easy. We can't rely on touch events at the * player level, because a tap (touchstart + touchend) on the video itself on * mobile devices is meant to turn controls off (and on). User activity is * checked asynchronously, so what could happen is a tap event on the video * turns the controls off, then the touchend event bubbles up to the player, * which if it reported user activity, would turn the controls right back on. * (We also don't want to completely block touch events from bubbling up) * Also a touchmove, touch+hold, and anything other than a tap is not supposed * to turn the controls back on on a mobile device. * Here we're setting the default component behavior to report user activity * whenever touch events happen, and this can be turned off by components that * want touch events to act differently. * * @method enableTouchActivity */ Component.prototype.enableTouchActivity = function enableTouchActivity() { // Don't continue if the root player doesn't support reporting user activity if (!this.player() || !this.player().reportUserActivity) { return; } // listener for reporting that the user is active var report = Fn.bind(this.player(), this.player().reportUserActivity); var touchHolding = undefined; this.on('touchstart', function () { report(); // For as long as the they are touching the device or have their mouse down, // we consider them active even if they're not moving their finger or mouse. // So we want to continue to update that they are active this.clearInterval(touchHolding); // report at the same interval as activityCheck touchHolding = this.setInterval(report, 250); }); var touchEnd = function touchEnd(event) { report(); // stop the interval that maintains activity if the touch is holding this.clearInterval(touchHolding); }; this.on('touchmove', report); this.on('touchend', touchEnd); this.on('touchcancel', touchEnd); }; /** * Creates timeout and sets up disposal automatically. * * @param {Function} fn The function to run after the timeout. * @param {Number} timeout Number of ms to delay before executing specified function. * @return {Number} Returns the timeout ID * @method setTimeout */ Component.prototype.setTimeout = function setTimeout(fn, timeout) { fn = Fn.bind(this, fn); // window.setTimeout would be preferable here, but due to some bizarre issue with Sinon and/or Phantomjs, we can't. var timeoutId = _globalWindow2['default'].setTimeout(fn, timeout); var disposeFn = function disposeFn() { this.clearTimeout(timeoutId); }; disposeFn.guid = 'vjs-timeout-' + timeoutId; this.on('dispose', disposeFn); return timeoutId; }; /** * Clears a timeout and removes the associated dispose listener * * @param {Number} timeoutId The id of the timeout to clear * @return {Number} Returns the timeout ID * @method clearTimeout */ Component.prototype.clearTimeout = function clearTimeout(timeoutId) { _globalWindow2['default'].clearTimeout(timeoutId); var disposeFn = function disposeFn() {}; disposeFn.guid = 'vjs-timeout-' + timeoutId; this.off('dispose', disposeFn); return timeoutId; }; /** * Creates an interval and sets up disposal automatically. * * @param {Function} fn The function to run every N seconds. * @param {Number} interval Number of ms to delay before executing specified function. * @return {Number} Returns the interval ID * @method setInterval */ Component.prototype.setInterval = function setInterval(fn, interval) { fn = Fn.bind(this, fn); var intervalId = _globalWindow2['default'].setInterval(fn, interval); var disposeFn = function disposeFn() { this.clearInterval(intervalId); }; disposeFn.guid = 'vjs-interval-' + intervalId; this.on('dispose', disposeFn); return intervalId; }; /** * Clears an interval and removes the associated dispose listener * * @param {Number} intervalId The id of the interval to clear * @return {Number} Returns the interval ID * @method clearInterval */ Component.prototype.clearInterval = function clearInterval(intervalId) { _globalWindow2['default'].clearInterval(intervalId); var disposeFn = function disposeFn() {}; disposeFn.guid = 'vjs-interval-' + intervalId; this.off('dispose', disposeFn); return intervalId; }; /** * Registers a component * * @param {String} name Name of the component to register * @param {Object} comp The component to register * @static * @method registerComponent */ Component.registerComponent = function registerComponent(name, comp) { if (!Component.components_) { Component.components_ = {}; } Component.components_[name] = comp; return comp; }; /** * Gets a component by name * * @param {String} name Name of the component to get * @return {Component} * @static * @method getComponent */ Component.getComponent = function getComponent(name) { if (Component.components_ && Component.components_[name]) { return Component.components_[name]; } if (_globalWindow2['default'] && _globalWindow2['default'].videojs && _globalWindow2['default'].videojs[name]) { _utilsLogJs2['default'].warn('The ' + name + ' component was added to the videojs object when it should be registered using videojs.registerComponent(name, component)'); return _globalWindow2['default'].videojs[name]; } }; /** * Sets up the constructor using the supplied init method * or uses the init of the parent object * * @param {Object} props An object of properties * @static * @deprecated * @method extend */ Component.extend = function extend(props) { props = props || {}; _utilsLogJs2['default'].warn('Component.extend({}) has been deprecated, use videojs.extends(Component, {}) instead'); // Set up the constructor using the supplied init method // or using the init of the parent object // Make sure to check the unobfuscated version for external libs var init = props.init || props.init || this.prototype.init || this.prototype.init || function () {}; // In Resig's simple class inheritance (previously used) the constructor // is a function that calls `this.init.apply(arguments)` // However that would prevent us from using `ParentObject.call(this);` // in a Child constructor because the `this` in `this.init` // would still refer to the Child and cause an infinite loop. // We would instead have to do // `ParentObject.prototype.init.apply(this, arguments);` // Bleh. We're not creating a _super() function, so it's good to keep // the parent constructor reference simple. var subObj = function subObj() { init.apply(this, arguments); }; // Inherit from this object's prototype subObj.prototype = Object.create(this.prototype); // Reset the constructor property for subObj otherwise // instances of subObj would have the constructor of the parent Object subObj.prototype.constructor = subObj; // Make the class extendable subObj.extend = Component.extend; // Extend subObj's prototype with functions and other properties from props for (var _name2 in props) { if (props.hasOwnProperty(_name2)) { subObj.prototype[_name2] = props[_name2]; } } return subObj; }; return Component; })(); Component.registerComponent('Component', Component); exports['default'] = Component; module.exports = exports['default']; },{"./utils/dom.js":107,"./utils/events.js":108,"./utils/fn.js":109,"./utils/guid.js":111,"./utils/log.js":112,"./utils/merge-options.js":113,"./utils/to-title-case.js":116,"global/window":2,"object.assign":40}],49:[function(_dereq_,module,exports){ /** * @file control-bar.js */ 'use strict'; exports.__esModule = true; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var _componentJs = _dereq_('../component.js'); var _componentJs2 = _interopRequireDefault(_componentJs); // Required children var _playToggleJs = _dereq_('./play-toggle.js'); var _playToggleJs2 = _interopRequireDefault(_playToggleJs); var _timeControlsCurrentTimeDisplayJs = _dereq_('./time-controls/current-time-display.js'); var _timeControlsCurrentTimeDisplayJs2 = _interopRequireDefault(_timeControlsCurrentTimeDisplayJs); var _timeControlsDurationDisplayJs = _dereq_('./time-controls/duration-display.js'); var _timeControlsDurationDisplayJs2 = _interopRequireDefault(_timeControlsDurationDisplayJs); var _timeControlsTimeDividerJs = _dereq_('./time-controls/time-divider.js'); var _timeControlsTimeDividerJs2 = _interopRequireDefault(_timeControlsTimeDividerJs); var _timeControlsRemainingTimeDisplayJs = _dereq_('./time-controls/remaining-time-display.js'); var _timeControlsRemainingTimeDisplayJs2 = _interopRequireDefault(_timeControlsRemainingTimeDisplayJs); var _liveDisplayJs = _dereq_('./live-display.js'); var _liveDisplayJs2 = _interopRequireDefault(_liveDisplayJs); var _progressControlProgressControlJs = _dereq_('./progress-control/progress-control.js'); var _progressControlProgressControlJs2 = _interopRequireDefault(_progressControlProgressControlJs); var _fullscreenToggleJs = _dereq_('./fullscreen-toggle.js'); var _fullscreenToggleJs2 = _interopRequireDefault(_fullscreenToggleJs); var _volumeControlVolumeControlJs = _dereq_('./volume-control/volume-control.js'); var _volumeControlVolumeControlJs2 = _interopRequireDefault(_volumeControlVolumeControlJs); var _volumeMenuButtonJs = _dereq_('./volume-menu-button.js'); var _volumeMenuButtonJs2 = _interopRequireDefault(_volumeMenuButtonJs); var _muteToggleJs = _dereq_('./mute-toggle.js'); var _muteToggleJs2 = _interopRequireDefault(_muteToggleJs); var _textTrackControlsChaptersButtonJs = _dereq_('./text-track-controls/chapters-button.js'); var _textTrackControlsChaptersButtonJs2 = _interopRequireDefault(_textTrackControlsChaptersButtonJs); var _textTrackControlsSubtitlesButtonJs = _dereq_('./text-track-controls/subtitles-button.js'); var _textTrackControlsSubtitlesButtonJs2 = _interopRequireDefault(_textTrackControlsSubtitlesButtonJs); var _textTrackControlsCaptionsButtonJs = _dereq_('./text-track-controls/captions-button.js'); var _textTrackControlsCaptionsButtonJs2 = _interopRequireDefault(_textTrackControlsCaptionsButtonJs); var _playbackRateMenuPlaybackRateMenuButtonJs = _dereq_('./playback-rate-menu/playback-rate-menu-button.js'); var _playbackRateMenuPlaybackRateMenuButtonJs2 = _interopRequireDefault(_playbackRateMenuPlaybackRateMenuButtonJs); var _spacerControlsCustomControlSpacerJs = _dereq_('./spacer-controls/custom-control-spacer.js'); var _spacerControlsCustomControlSpacerJs2 = _interopRequireDefault(_spacerControlsCustomControlSpacerJs); /** * Container of main controls * * @extends Component * @class ControlBar */ var ControlBar = (function (_Component) { _inherits(ControlBar, _Component); function ControlBar() { _classCallCheck(this, ControlBar); _Component.apply(this, arguments); } /** * Create the component's DOM element * * @return {Element} * @method createEl */ ControlBar.prototype.createEl = function createEl() { return _Component.prototype.createEl.call(this, 'div', { className: 'vjs-control-bar' }); }; return ControlBar; })(_componentJs2['default']); ControlBar.prototype.options_ = { loadEvent: 'play', children: ['playToggle', 'volumeMenuButton', 'currentTimeDisplay', 'timeDivider', 'durationDisplay', 'progressControl', 'liveDisplay', 'remainingTimeDisplay', 'customControlSpacer', 'playbackRateMenuButton', 'muteToggle', 'volumeControl', 'chaptersButton', 'subtitlesButton', 'captionsButton', 'fullscreenToggle'] }; _componentJs2['default'].registerComponent('ControlBar', ControlBar); exports['default'] = ControlBar; module.exports = exports['default']; },{"../component.js":48,"./fullscreen-toggle.js":50,"./live-display.js":51,"./mute-toggle.js":52,"./play-toggle.js":53,"./playback-rate-menu/playback-rate-menu-button.js":54,"./progress-control/progress-control.js":58,"./spacer-controls/custom-control-spacer.js":60,"./text-track-controls/captions-button.js":63,"./text-track-controls/chapters-button.js":64,"./text-track-controls/subtitles-button.js":67,"./time-controls/current-time-display.js":70,"./time-controls/duration-display.js":71,"./time-controls/remaining-time-display.js":72,"./time-controls/time-divider.js":73,"./volume-control/volume-control.js":75,"./volume-menu-button.js":77}],50:[function(_dereq_,module,exports){ /** * @file fullscreen-toggle.js */ 'use strict'; exports.__esModule = true; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var _buttonJs = _dereq_('../button.js'); var _buttonJs2 = _interopRequireDefault(_buttonJs); var _componentJs = _dereq_('../component.js'); var _componentJs2 = _interopRequireDefault(_componentJs); /** * Toggle fullscreen video * * @extends Button * @class FullscreenToggle */ var FullscreenToggle = (function (_Button) { _inherits(FullscreenToggle, _Button); function FullscreenToggle() { _classCallCheck(this, FullscreenToggle); _Button.apply(this, arguments); } /** * Allow sub components to stack CSS class names * * @return {String} The constructed class name * @method buildCSSClass */ FullscreenToggle.prototype.buildCSSClass = function buildCSSClass() { return 'vjs-fullscreen-control ' + _Button.prototype.buildCSSClass.call(this); }; /** * Handles click for full screen * * @method handleClick */ FullscreenToggle.prototype.handleClick = function handleClick() { if (!this.player_.isFullscreen()) { this.player_.requestFullscreen(); this.controlText('Non-Fullscreen'); } else { this.player_.exitFullscreen(); this.controlText('Fullscreen'); } }; return FullscreenToggle; })(_buttonJs2['default']); FullscreenToggle.prototype.controlText_ = 'Fullscreen'; _componentJs2['default'].registerComponent('FullscreenToggle', FullscreenToggle); exports['default'] = FullscreenToggle; module.exports = exports['default']; },{"../button.js":47,"../component.js":48}],51:[function(_dereq_,module,exports){ /** * @file live-display.js */ 'use strict'; exports.__esModule = true; function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj['default'] = obj; return newObj; } } function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var _component = _dereq_('../component'); var _component2 = _interopRequireDefault(_component); var _utilsDomJs = _dereq_('../utils/dom.js'); var Dom = _interopRequireWildcard(_utilsDomJs); /** * Displays the live indicator * TODO - Future make it click to snap to live * * @extends Component * @class LiveDisplay */ var LiveDisplay = (function (_Component) { _inherits(LiveDisplay, _Component); function LiveDisplay(player, options) { _classCallCheck(this, LiveDisplay); _Component.call(this, player, options); this.updateShowing(); this.on(this.player(), 'durationchange', this.updateShowing); } /** * Create the component's DOM element * * @return {Element} * @method createEl */ LiveDisplay.prototype.createEl = function createEl() { var el = _Component.prototype.createEl.call(this, 'div', { className: 'vjs-live-control vjs-control' }); this.contentEl_ = Dom.createEl('div', { className: 'vjs-live-display', innerHTML: '<span class="vjs-control-text">' + this.localize('Stream Type') + '</span>' + this.localize('LIVE'), 'aria-live': 'off' }); el.appendChild(this.contentEl_); return el; }; LiveDisplay.prototype.updateShowing = function updateShowing() { if (this.player().duration() === Infinity) { this.show(); } else { this.hide(); } }; return LiveDisplay; })(_component2['default']); _component2['default'].registerComponent('LiveDisplay', LiveDisplay); exports['default'] = LiveDisplay; module.exports = exports['default']; },{"../component":48,"../utils/dom.js":107}],52:[function(_dereq_,module,exports){ /** * @file mute-toggle.js */ 'use strict'; exports.__esModule = true; function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj['default'] = obj; return newObj; } } function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var _button = _dereq_('../button'); var _button2 = _interopRequireDefault(_button); var _component = _dereq_('../component'); var _component2 = _interopRequireDefault(_component); var _utilsDomJs = _dereq_('../utils/dom.js'); var Dom = _interopRequireWildcard(_utilsDomJs); /** * A button component for muting the audio * * @param {Player|Object} player * @param {Object=} options * @extends Button * @class MuteToggle */ var MuteToggle = (function (_Button) { _inherits(MuteToggle, _Button); function MuteToggle(player, options) { _classCallCheck(this, MuteToggle); _Button.call(this, player, options); this.on(player, 'volumechange', this.update); // hide mute toggle if the current tech doesn't support volume control if (player.tech && player.tech['featuresVolumeControl'] === false) { this.addClass('vjs-hidden'); } this.on(player, 'loadstart', function () { this.update(); // We need to update the button to account for a default muted state. if (player.tech['featuresVolumeControl'] === false) { this.addClass('vjs-hidden'); } else { this.removeClass('vjs-hidden'); } }); } /** * Allow sub components to stack CSS class names * * @return {String} The constructed class name * @method buildCSSClass */ MuteToggle.prototype.buildCSSClass = function buildCSSClass() { return 'vjs-mute-control ' + _Button.prototype.buildCSSClass.call(this); }; /** * Handle click on mute * * @method handleClick */ MuteToggle.prototype.handleClick = function handleClick() { this.player_.muted(this.player_.muted() ? false : true); }; /** * Update volume * * @method update */ MuteToggle.prototype.update = function update() { var vol = this.player_.volume(), level = 3; if (vol === 0 || this.player_.muted()) { level = 0; } else if (vol < 0.33) { level = 1; } else if (vol < 0.67) { level = 2; } // Don't rewrite the button text if the actual text doesn't change. // This causes unnecessary and confusing information for screen reader users. // This check is needed because this function gets called every time the volume level is changed. var toMute = this.player_.muted() ? 'Unmute' : 'Mute'; var localizedMute = this.localize(toMute); if (this.controlText() !== localizedMute) { this.controlText(localizedMute); } /* TODO improve muted icon classes */ for (var i = 0; i < 4; i++) { Dom.removeElClass(this.el_, 'vjs-vol-' + i); } Dom.addElClass(this.el_, 'vjs-vol-' + level); }; return MuteToggle; })(_button2['default']); MuteToggle.prototype.controlText_ = 'Mute'; _component2['default'].registerComponent('MuteToggle', MuteToggle); exports['default'] = MuteToggle; module.exports = exports['default']; },{"../button":47,"../component":48,"../utils/dom.js":107}],53:[function(_dereq_,module,exports){ /** * @file play-toggle.js */ 'use strict'; exports.__esModule = true; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var _buttonJs = _dereq_('../button.js'); var _buttonJs2 = _interopRequireDefault(_buttonJs); var _componentJs = _dereq_('../component.js'); var _componentJs2 = _interopRequireDefault(_componentJs); /** * Button to toggle between play and pause * * @param {Player|Object} player * @param {Object=} options * @extends Button * @class PlayToggle */ var PlayToggle = (function (_Button) { _inherits(PlayToggle, _Button); function PlayToggle(player, options) { _classCallCheck(this, PlayToggle); _Button.call(this, player, options); this.on(player, 'play', this.handlePlay); this.on(player, 'pause', this.handlePause); } /** * Allow sub components to stack CSS class names * * @return {String} The constructed class name * @method buildCSSClass */ PlayToggle.prototype.buildCSSClass = function buildCSSClass() { return 'vjs-play-control ' + _Button.prototype.buildCSSClass.call(this); }; /** * Handle click to toggle between play and pause * * @method handleClick */ PlayToggle.prototype.handleClick = function handleClick() { if (this.player_.paused()) { this.player_.play(); } else { this.player_.pause(); } }; /** * Add the vjs-playing class to the element so it can change appearance * * @method handlePlay */ PlayToggle.prototype.handlePlay = function handlePlay() { this.removeClass('vjs-paused'); this.addClass('vjs-playing'); this.controlText('Pause'); // change the button text to "Pause" }; /** * Add the vjs-paused class to the element so it can change appearance * * @method handlePause */ PlayToggle.prototype.handlePause = function handlePause() { this.removeClass('vjs-playing'); this.addClass('vjs-paused'); this.controlText('Play'); // change the button text to "Play" }; return PlayToggle; })(_buttonJs2['default']); PlayToggle.prototype.controlText_ = 'Play'; _componentJs2['default'].registerComponent('PlayToggle', PlayToggle); exports['default'] = PlayToggle; module.exports = exports['default']; },{"../button.js":47,"../component.js":48}],54:[function(_dereq_,module,exports){ /** * @file playback-rate-menu-button.js */ 'use strict'; exports.__esModule = true; function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj['default'] = obj; return newObj; } } function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var _menuMenuButtonJs = _dereq_('../../menu/menu-button.js'); var _menuMenuButtonJs2 = _interopRequireDefault(_menuMenuButtonJs); var _menuMenuJs = _dereq_('../../menu/menu.js'); var _menuMenuJs2 = _interopRequireDefault(_menuMenuJs); var _playbackRateMenuItemJs = _dereq_('./playback-rate-menu-item.js'); var _playbackRateMenuItemJs2 = _interopRequireDefault(_playbackRateMenuItemJs); var _componentJs = _dereq_('../../component.js'); var _componentJs2 = _interopRequireDefault(_componentJs); var _utilsDomJs = _dereq_('../../utils/dom.js'); var Dom = _interopRequireWildcard(_utilsDomJs); /** * The component for controlling the playback rate * * @param {Player|Object} player * @param {Object=} options * @extends MenuButton * @class PlaybackRateMenuButton */ var PlaybackRateMenuButton = (function (_MenuButton) { _inherits(PlaybackRateMenuButton, _MenuButton); function PlaybackRateMenuButton(player, options) { _classCallCheck(this, PlaybackRateMenuButton); _MenuButton.call(this, player, options); this.updateVisibility(); this.updateLabel(); this.on(player, 'loadstart', this.updateVisibility); this.on(player, 'ratechange', this.updateLabel); } /** * Create the component's DOM element * * @return {Element} * @method createEl */ PlaybackRateMenuButton.prototype.createEl = function createEl() { var el = _MenuButton.prototype.createEl.call(this); this.labelEl_ = Dom.createEl('div', { className: 'vjs-playback-rate-value', innerHTML: 1.0 }); el.appendChild(this.labelEl_); return el; }; /** * Allow sub components to stack CSS class names * * @return {String} The constructed class name * @method buildCSSClass */ PlaybackRateMenuButton.prototype.buildCSSClass = function buildCSSClass() { return 'vjs-playback-rate ' + _MenuButton.prototype.buildCSSClass.call(this); }; /** * Create the playback rate menu * * @return {Menu} Menu object populated with items * @method createMenu */ PlaybackRateMenuButton.prototype.createMenu = function createMenu() { var menu = new _menuMenuJs2['default'](this.player()); var rates = this.playbackRates(); if (rates) { for (var i = rates.length - 1; i >= 0; i--) { menu.addChild(new _playbackRateMenuItemJs2['default'](this.player(), { 'rate': rates[i] + 'x' })); } } return menu; }; /** * Updates ARIA accessibility attributes * * @method updateARIAAttributes */ PlaybackRateMenuButton.prototype.updateARIAAttributes = function updateARIAAttributes() { // Current playback rate this.el().setAttribute('aria-valuenow', this.player().playbackRate()); }; /** * Handle menu item click * * @method handleClick */ PlaybackRateMenuButton.prototype.handleClick = function handleClick() { // select next rate option var currentRate = this.player().playbackRate(); var rates = this.playbackRates(); // this will select first one if the last one currently selected var newRate = rates[0]; for (var i = 0; i < rates.length; i++) { if (rates[i] > currentRate) { newRate = rates[i]; break; } } this.player().playbackRate(newRate); }; /** * Get possible playback rates * * @return {Array} Possible playback rates * @method playbackRates */ PlaybackRateMenuButton.prototype.playbackRates = function playbackRates() { return this.options_['playbackRates'] || this.options_.playerOptions && this.options_.playerOptions['playbackRates']; }; /** * Get supported playback rates * * @return {Array} Supported playback rates * @method playbackRateSupported */ PlaybackRateMenuButton.prototype.playbackRateSupported = function playbackRateSupported() { return this.player().tech && this.player().tech['featuresPlaybackRate'] && this.playbackRates() && this.playbackRates().length > 0; }; /** * Hide playback rate controls when they're no playback rate options to select * * @method updateVisibility */ PlaybackRateMenuButton.prototype.updateVisibility = function updateVisibility() { if (this.playbackRateSupported()) { this.removeClass('vjs-hidden'); } else { this.addClass('vjs-hidden'); } }; /** * Update button label when rate changed * * @method updateLabel */ PlaybackRateMenuButton.prototype.updateLabel = function updateLabel() { if (this.playbackRateSupported()) { this.labelEl_.innerHTML = this.player().playbackRate() + 'x'; } }; return PlaybackRateMenuButton; })(_menuMenuButtonJs2['default']); PlaybackRateMenuButton.prototype.controlText_ = 'Playback Rate'; _componentJs2['default'].registerComponent('PlaybackRateMenuButton', PlaybackRateMenuButton); exports['default'] = PlaybackRateMenuButton; module.exports = exports['default']; },{"../../component.js":48,"../../menu/menu-button.js":84,"../../menu/menu.js":86,"../../utils/dom.js":107,"./playback-rate-menu-item.js":55}],55:[function(_dereq_,module,exports){ /** * @file playback-rate-menu-item.js */ 'use strict'; exports.__esModule = true; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var _menuMenuItemJs = _dereq_('../../menu/menu-item.js'); var _menuMenuItemJs2 = _interopRequireDefault(_menuMenuItemJs); var _componentJs = _dereq_('../../component.js'); var _componentJs2 = _interopRequireDefault(_componentJs); /** * The specific menu item type for selecting a playback rate * * @param {Player|Object} player * @param {Object=} options * @extends MenuItem * @class PlaybackRateMenuItem */ var PlaybackRateMenuItem = (function (_MenuItem) { _inherits(PlaybackRateMenuItem, _MenuItem); function PlaybackRateMenuItem(player, options) { _classCallCheck(this, PlaybackRateMenuItem); var label = options['rate']; var rate = parseFloat(label, 10); // Modify options for parent MenuItem class's init. options['label'] = label; options['selected'] = rate === 1; _MenuItem.call(this, player, options); this.label = label; this.rate = rate; this.on(player, 'ratechange', this.update); } /** * Handle click on menu item * * @method handleClick */ PlaybackRateMenuItem.prototype.handleClick = function handleClick() { _MenuItem.prototype.handleClick.call(this); this.player().playbackRate(this.rate); }; /** * Update playback rate with selected rate * * @method update */ PlaybackRateMenuItem.prototype.update = function update() { this.selected(this.player().playbackRate() === this.rate); }; return PlaybackRateMenuItem; })(_menuMenuItemJs2['default']); PlaybackRateMenuItem.prototype.contentElType = 'button'; _componentJs2['default'].registerComponent('PlaybackRateMenuItem', PlaybackRateMenuItem); exports['default'] = PlaybackRateMenuItem; module.exports = exports['default']; },{"../../component.js":48,"../../menu/menu-item.js":85}],56:[function(_dereq_,module,exports){ /** * @file load-progress-bar.js */ 'use strict'; exports.__esModule = true; function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj['default'] = obj; return newObj; } } function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var _componentJs = _dereq_('../../component.js'); var _componentJs2 = _interopRequireDefault(_componentJs); var _utilsDomJs = _dereq_('../../utils/dom.js'); var Dom = _interopRequireWildcard(_utilsDomJs); /** * Shows load progress * * @param {Player|Object} player * @param {Object=} options * @extends Component * @class LoadProgressBar */ var LoadProgressBar = (function (_Component) { _inherits(LoadProgressBar, _Component); function LoadProgressBar(player, options) { _classCallCheck(this, LoadProgressBar); _Component.call(this, player, options); this.on(player, 'progress', this.update); } /** * Create the component's DOM element * * @return {Element} * @method createEl */ LoadProgressBar.prototype.createEl = function createEl() { return _Component.prototype.createEl.call(this, 'div', { className: 'vjs-load-progress', innerHTML: '<span class="vjs-control-text"><span>' + this.localize('Loaded') + '</span>: 0%</span>' }); }; /** * Update progress bar * * @method update */ LoadProgressBar.prototype.update = function update() { var buffered = this.player_.buffered(); var duration = this.player_.duration(); var bufferedEnd = this.player_.bufferedEnd(); var children = this.el_.children; // get the percent width of a time compared to the total end var percentify = function percentify(time, end) { var percent = time / end || 0; // no NaN return (percent >= 1 ? 1 : percent) * 100 + '%'; }; // update the width of the progress bar this.el_.style.width = percentify(bufferedEnd, duration); // add child elements to represent the individual buffered time ranges for (var i = 0; i < buffered.length; i++) { var start = buffered.start(i); var end = buffered.end(i); var part = children[i]; if (!part) { part = this.el_.appendChild(Dom.createEl()); } // set the percent based on the width of the progress bar (bufferedEnd) part.style.left = percentify(start, bufferedEnd); part.style.width = percentify(end - start, bufferedEnd); } // remove unused buffered range elements for (var i = children.length; i > buffered.length; i--) { this.el_.removeChild(children[i - 1]); } }; return LoadProgressBar; })(_componentJs2['default']); _componentJs2['default'].registerComponent('LoadProgressBar', LoadProgressBar); exports['default'] = LoadProgressBar; module.exports = exports['default']; },{"../../component.js":48,"../../utils/dom.js":107}],57:[function(_dereq_,module,exports){ /** * @file play-progress-bar.js */ 'use strict'; exports.__esModule = true; function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj['default'] = obj; return newObj; } } function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var _componentJs = _dereq_('../../component.js'); var _componentJs2 = _interopRequireDefault(_componentJs); var _utilsFnJs = _dereq_('../../utils/fn.js'); var Fn = _interopRequireWildcard(_utilsFnJs); var _utilsFormatTimeJs = _dereq_('../../utils/format-time.js'); var _utilsFormatTimeJs2 = _interopRequireDefault(_utilsFormatTimeJs); /** * Shows play progress * * @param {Player|Object} player * @param {Object=} options * @extends Component * @class PlayProgressBar */ var PlayProgressBar = (function (_Component) { _inherits(PlayProgressBar, _Component); function PlayProgressBar(player, options) { _classCallCheck(this, PlayProgressBar); _Component.call(this, player, options); this.updateDataAttr(); this.on(player, 'timeupdate', this.updateDataAttr); player.ready(Fn.bind(this, this.updateDataAttr)); } /** * Create the component's DOM element * * @return {Element} * @method createEl */ PlayProgressBar.prototype.createEl = function createEl() { return _Component.prototype.createEl.call(this, 'div', { className: 'vjs-play-progress', innerHTML: '<span class="vjs-control-text"><span>' + this.localize('Progress') + '</span>: 0%</span>' }); }; PlayProgressBar.prototype.updateDataAttr = function updateDataAttr() { var time = this.player_.scrubbing() ? this.player_.getCache().currentTime : this.player_.currentTime(); this.el_.setAttribute('data-current-time', _utilsFormatTimeJs2['default'](time, this.player_.duration())); }; return PlayProgressBar; })(_componentJs2['default']); _componentJs2['default'].registerComponent('PlayProgressBar', PlayProgressBar); exports['default'] = PlayProgressBar; module.exports = exports['default']; },{"../../component.js":48,"../../utils/fn.js":109,"../../utils/format-time.js":110}],58:[function(_dereq_,module,exports){ /** * @file progress-control.js */ 'use strict'; exports.__esModule = true; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var _componentJs = _dereq_('../../component.js'); var _componentJs2 = _interopRequireDefault(_componentJs); var _seekBarJs = _dereq_('./seek-bar.js'); var _seekBarJs2 = _interopRequireDefault(_seekBarJs); /** * The Progress Control component contains the seek bar, load progress, * and play progress * * @param {Player|Object} player * @param {Object=} options * @extends Component * @class ProgressControl */ var ProgressControl = (function (_Component) { _inherits(ProgressControl, _Component); function ProgressControl() { _classCallCheck(this, ProgressControl); _Component.apply(this, arguments); } /** * Create the component's DOM element * * @return {Element} * @method createEl */ ProgressControl.prototype.createEl = function createEl() { return _Component.prototype.createEl.call(this, 'div', { className: 'vjs-progress-control vjs-control' }); }; return ProgressControl; })(_componentJs2['default']); ProgressControl.prototype.options_ = { children: { 'seekBar': {} } }; _componentJs2['default'].registerComponent('ProgressControl', ProgressControl); exports['default'] = ProgressControl; module.exports = exports['default']; },{"../../component.js":48,"./seek-bar.js":59}],59:[function(_dereq_,module,exports){ /** * @file seek-bar.js */ 'use strict'; exports.__esModule = true; function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj['default'] = obj; return newObj; } } function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var _sliderSliderJs = _dereq_('../../slider/slider.js'); var _sliderSliderJs2 = _interopRequireDefault(_sliderSliderJs); var _componentJs = _dereq_('../../component.js'); var _componentJs2 = _interopRequireDefault(_componentJs); var _loadProgressBarJs = _dereq_('./load-progress-bar.js'); var _loadProgressBarJs2 = _interopRequireDefault(_loadProgressBarJs); var _playProgressBarJs = _dereq_('./play-progress-bar.js'); var _playProgressBarJs2 = _interopRequireDefault(_playProgressBarJs); var _utilsFnJs = _dereq_('../../utils/fn.js'); var Fn = _interopRequireWildcard(_utilsFnJs); var _utilsFormatTimeJs = _dereq_('../../utils/format-time.js'); var _utilsFormatTimeJs2 = _interopRequireDefault(_utilsFormatTimeJs); /** * Seek Bar and holder for the progress bars * * @param {Player|Object} player * @param {Object=} options * @extends Slider * @class SeekBar */ var SeekBar = (function (_Slider) { _inherits(SeekBar, _Slider); function SeekBar(player, options) { _classCallCheck(this, SeekBar); _Slider.call(this, player, options); this.on(player, 'timeupdate', this.updateARIAAttributes); player.ready(Fn.bind(this, this.updateARIAAttributes)); } /** * Create the component's DOM element * * @return {Element} * @method createEl */ SeekBar.prototype.createEl = function createEl() { return _Slider.prototype.createEl.call(this, 'div', { className: 'vjs-progress-holder', 'aria-label': 'video progress bar' }); }; /** * Update ARIA accessibility attributes * * @method updateARIAAttributes */ SeekBar.prototype.updateARIAAttributes = function updateARIAAttributes() { // Allows for smooth scrubbing, when player can't keep up. var time = this.player_.scrubbing() ? this.player_.getCache().currentTime : this.player_.currentTime(); this.el_.setAttribute('aria-valuenow', (this.getPercent() * 100).toFixed(2)); // machine readable value of progress bar (percentage complete) this.el_.setAttribute('aria-valuetext', _utilsFormatTimeJs2['default'](time, this.player_.duration())); // human readable value of progress bar (time complete) }; /** * Get percentage of video played * * @return {Number} Percentage played * @method getPercent */ SeekBar.prototype.getPercent = function getPercent() { var percent = this.player_.currentTime() / this.player_.duration(); return percent >= 1 ? 1 : percent; }; /** * Handle mouse down on seek bar * * @method handleMouseDown */ SeekBar.prototype.handleMouseDown = function handleMouseDown(event) { _Slider.prototype.handleMouseDown.call(this, event); this.player_.scrubbing(true); this.videoWasPlaying = !this.player_.paused(); this.player_.pause(); }; /** * Handle mouse move on seek bar * * @method handleMouseMove */ SeekBar.prototype.handleMouseMove = function handleMouseMove(event) { var newTime = this.calculateDistance(event) * this.player_.duration(); // Don't let video end while scrubbing. if (newTime === this.player_.duration()) { newTime = newTime - 0.1; } // Set new time (tell player to seek to new time) this.player_.currentTime(newTime); }; /** * Handle mouse up on seek bar * * @method handleMouseUp */ SeekBar.prototype.handleMouseUp = function handleMouseUp(event) { _Slider.prototype.handleMouseUp.call(this, event); this.player_.scrubbing(false); if (this.videoWasPlaying) { this.player_.play(); } }; /** * Move more quickly fast forward for keyboard-only users * * @method stepForward */ SeekBar.prototype.stepForward = function stepForward() { this.player_.currentTime(this.player_.currentTime() + 5); // more quickly fast forward for keyboard-only users }; /** * Move more quickly rewind for keyboard-only users * * @method stepBack */ SeekBar.prototype.stepBack = function stepBack() { this.player_.currentTime(this.player_.currentTime() - 5); // more quickly rewind for keyboard-only users }; return SeekBar; })(_sliderSliderJs2['default']); SeekBar.prototype.options_ = { children: { 'loadProgressBar': {}, 'playProgressBar': {} }, 'barName': 'playProgressBar' }; SeekBar.prototype.playerEvent = 'timeupdate'; _componentJs2['default'].registerComponent('SeekBar', SeekBar); exports['default'] = SeekBar; module.exports = exports['default']; },{"../../component.js":48,"../../slider/slider.js":91,"../../utils/fn.js":109,"../../utils/format-time.js":110,"./load-progress-bar.js":56,"./play-progress-bar.js":57}],60:[function(_dereq_,module,exports){ /** * @file custom-control-spacer.js */ 'use strict'; exports.__esModule = true; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var _spacerJs = _dereq_('./spacer.js'); var _spacerJs2 = _interopRequireDefault(_spacerJs); var _componentJs = _dereq_('../../component.js'); var _componentJs2 = _interopRequireDefault(_componentJs); /** * Spacer specifically meant to be used as an insertion point for new plugins, etc. * * @extends Spacer * @class CustomControlSpacer */ var CustomControlSpacer = (function (_Spacer) { _inherits(CustomControlSpacer, _Spacer); function CustomControlSpacer() { _classCallCheck(this, CustomControlSpacer); _Spacer.apply(this, arguments); } /** * Allow sub components to stack CSS class names * * @return {String} The constructed class name * @method buildCSSClass */ CustomControlSpacer.prototype.buildCSSClass = function buildCSSClass() { return 'vjs-custom-control-spacer ' + _Spacer.prototype.buildCSSClass.call(this); }; /** * Create the component's DOM element * * @return {Element} * @method createEl */ CustomControlSpacer.prototype.createEl = function createEl() { var el = _Spacer.prototype.createEl.call(this, { className: this.buildCSSClass() }); // No-flex/table-cell mode requires there be some content // in the cell to fill the remaining space of the table. el.innerHTML = '&nbsp;'; return el; }; return CustomControlSpacer; })(_spacerJs2['default']); _componentJs2['default'].registerComponent('CustomControlSpacer', CustomControlSpacer); exports['default'] = CustomControlSpacer; module.exports = exports['default']; },{"../../component.js":48,"./spacer.js":61}],61:[function(_dereq_,module,exports){ /** * @file spacer.js */ 'use strict'; exports.__esModule = true; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var _componentJs = _dereq_('../../component.js'); var _componentJs2 = _interopRequireDefault(_componentJs); /** * Just an empty spacer element that can be used as an append point for plugins, etc. * Also can be used to create space between elements when necessary. * * @extends Component * @class Spacer */ var Spacer = (function (_Component) { _inherits(Spacer, _Component); function Spacer() { _classCallCheck(this, Spacer); _Component.apply(this, arguments); } /** * Allow sub components to stack CSS class names * * @return {String} The constructed class name * @method buildCSSClass */ Spacer.prototype.buildCSSClass = function buildCSSClass() { return 'vjs-spacer ' + _Component.prototype.buildCSSClass.call(this); }; /** * Create the component's DOM element * * @param {Object} props An object of properties * @return {Element} * @method createEl */ Spacer.prototype.createEl = function createEl(props) { return _Component.prototype.createEl.call(this, 'div', { className: this.buildCSSClass() }); }; return Spacer; })(_componentJs2['default']); _componentJs2['default'].registerComponent('Spacer', Spacer); exports['default'] = Spacer; module.exports = exports['default']; },{"../../component.js":48}],62:[function(_dereq_,module,exports){ /** * @file caption-settings-menu-item.js */ 'use strict'; exports.__esModule = true; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var _textTrackMenuItemJs = _dereq_('./text-track-menu-item.js'); var _textTrackMenuItemJs2 = _interopRequireDefault(_textTrackMenuItemJs); var _componentJs = _dereq_('../../component.js'); var _componentJs2 = _interopRequireDefault(_componentJs); /** * The menu item for caption track settings menu * * @param {Player|Object} player * @param {Object=} options * @extends TextTrackMenuItem * @class CaptionSettingsMenuItem */ var CaptionSettingsMenuItem = (function (_TextTrackMenuItem) { _inherits(CaptionSettingsMenuItem, _TextTrackMenuItem); function CaptionSettingsMenuItem(player, options) { _classCallCheck(this, CaptionSettingsMenuItem); options['track'] = { 'kind': options['kind'], 'player': player, 'label': options['kind'] + ' settings', 'default': false, mode: 'disabled' }; _TextTrackMenuItem.call(this, player, options); this.addClass('vjs-texttrack-settings'); } /** * Handle click on menu item * * @method handleClick */ CaptionSettingsMenuItem.prototype.handleClick = function handleClick() { this.player().getChild('textTrackSettings').show(); }; return CaptionSettingsMenuItem; })(_textTrackMenuItemJs2['default']); _componentJs2['default'].registerComponent('CaptionSettingsMenuItem', CaptionSettingsMenuItem); exports['default'] = CaptionSettingsMenuItem; module.exports = exports['default']; },{"../../component.js":48,"./text-track-menu-item.js":69}],63:[function(_dereq_,module,exports){ /** * @file captions-button.js */ 'use strict'; exports.__esModule = true; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var _textTrackButtonJs = _dereq_('./text-track-button.js'); var _textTrackButtonJs2 = _interopRequireDefault(_textTrackButtonJs); var _componentJs = _dereq_('../../component.js'); var _componentJs2 = _interopRequireDefault(_componentJs); var _captionSettingsMenuItemJs = _dereq_('./caption-settings-menu-item.js'); var _captionSettingsMenuItemJs2 = _interopRequireDefault(_captionSettingsMenuItemJs); /** * The button component for toggling and selecting captions * * @param {Object} player Player object * @param {Object=} options Object of option names and values * @param {Function=} ready Ready callback function * @extends TextTrackButton * @class CaptionsButton */ var CaptionsButton = (function (_TextTrackButton) { _inherits(CaptionsButton, _TextTrackButton); function CaptionsButton(player, options, ready) { _classCallCheck(this, CaptionsButton); _TextTrackButton.call(this, player, options, ready); this.el_.setAttribute('aria-label', 'Captions Menu'); } /** * Allow sub components to stack CSS class names * * @return {String} The constructed class name * @method buildCSSClass */ CaptionsButton.prototype.buildCSSClass = function buildCSSClass() { return 'vjs-captions-button ' + _TextTrackButton.prototype.buildCSSClass.call(this); }; /** * Update caption menu items * * @method update */ CaptionsButton.prototype.update = function update() { var threshold = 2; _TextTrackButton.prototype.update.call(this); // if native, then threshold is 1 because no settings button if (this.player().tech && this.player().tech['featuresNativeTextTracks']) { threshold = 1; } if (this.items && this.items.length > threshold) { this.show(); } else { this.hide(); } }; /** * Create caption menu items * * @return {Array} Array of menu items * @method createItems */ CaptionsButton.prototype.createItems = function createItems() { var items = []; if (!(this.player().tech && this.player().tech['featuresNativeTextTracks'])) { items.push(new _captionSettingsMenuItemJs2['default'](this.player_, { 'kind': this.kind_ })); } return _TextTrackButton.prototype.createItems.call(this, items); }; return CaptionsButton; })(_textTrackButtonJs2['default']); CaptionsButton.prototype.kind_ = 'captions'; CaptionsButton.prototype.controlText_ = 'Captions'; _componentJs2['default'].registerComponent('CaptionsButton', CaptionsButton); exports['default'] = CaptionsButton; module.exports = exports['default']; },{"../../component.js":48,"./caption-settings-menu-item.js":62,"./text-track-button.js":68}],64:[function(_dereq_,module,exports){ /** * @file chapters-button.js */ 'use strict'; exports.__esModule = true; function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj['default'] = obj; return newObj; } } function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var _textTrackButtonJs = _dereq_('./text-track-button.js'); var _textTrackButtonJs2 = _interopRequireDefault(_textTrackButtonJs); var _componentJs = _dereq_('../../component.js'); var _componentJs2 = _interopRequireDefault(_componentJs); var _textTrackMenuItemJs = _dereq_('./text-track-menu-item.js'); var _textTrackMenuItemJs2 = _interopRequireDefault(_textTrackMenuItemJs); var _chaptersTrackMenuItemJs = _dereq_('./chapters-track-menu-item.js'); var _chaptersTrackMenuItemJs2 = _interopRequireDefault(_chaptersTrackMenuItemJs); var _menuMenuJs = _dereq_('../../menu/menu.js'); var _menuMenuJs2 = _interopRequireDefault(_menuMenuJs); var _utilsDomJs = _dereq_('../../utils/dom.js'); var Dom = _interopRequireWildcard(_utilsDomJs); var _utilsFnJs = _dereq_('../../utils/fn.js'); var Fn = _interopRequireWildcard(_utilsFnJs); var _utilsToTitleCaseJs = _dereq_('../../utils/to-title-case.js'); var _utilsToTitleCaseJs2 = _interopRequireDefault(_utilsToTitleCaseJs); var _globalWindow = _dereq_('global/window'); var _globalWindow2 = _interopRequireDefault(_globalWindow); /** * The button component for toggling and selecting chapters * Chapters act much differently than other text tracks * Cues are navigation vs. other tracks of alternative languages * * @param {Object} player Player object * @param {Object=} options Object of option names and values * @param {Function=} ready Ready callback function * @extends TextTrackButton * @class ChaptersButton */ var ChaptersButton = (function (_TextTrackButton) { _inherits(ChaptersButton, _TextTrackButton); function ChaptersButton(player, options, ready) { _classCallCheck(this, ChaptersButton); _TextTrackButton.call(this, player, options, ready); this.el_.setAttribute('aria-label', 'Chapters Menu'); } /** * Allow sub components to stack CSS class names * * @return {String} The constructed class name * @method buildCSSClass */ ChaptersButton.prototype.buildCSSClass = function buildCSSClass() { return 'vjs-chapters-button ' + _TextTrackButton.prototype.buildCSSClass.call(this); }; /** * Create a menu item for each text track * * @return {Array} Array of menu items * @method createItems */ ChaptersButton.prototype.createItems = function createItems() { var items = []; var tracks = this.player_.textTracks(); if (!tracks) { return items; } for (var i = 0; i < tracks.length; i++) { var track = tracks[i]; if (track['kind'] === this.kind_) { items.push(new _textTrackMenuItemJs2['default'](this.player_, { 'track': track })); } } return items; }; /** * Create menu from chapter buttons * * @return {Menu} Menu of chapter buttons * @method createMenu */ ChaptersButton.prototype.createMenu = function createMenu() { var tracks = this.player_.textTracks() || []; var chaptersTrack = undefined; var items = this.items = []; for (var i = 0, l = tracks.length; i < l; i++) { var track = tracks[i]; if (track['kind'] === this.kind_) { if (!track.cues) { track['mode'] = 'hidden'; /* jshint loopfunc:true */ // TODO see if we can figure out a better way of doing this https://github.com/videojs/video.js/issues/1864 _globalWindow2['default'].setTimeout(Fn.bind(this, function () { this.createMenu(); }), 100); /* jshint loopfunc:false */ } else { chaptersTrack = track; break; } } } var menu = this.menu; if (menu === undefined) { menu = new _menuMenuJs2['default'](this.player_); menu.contentEl().appendChild(Dom.createEl('li', { className: 'vjs-menu-title', innerHTML: _utilsToTitleCaseJs2['default'](this.kind_), tabIndex: -1 })); } if (chaptersTrack) { var cues = chaptersTrack['cues'], cue = undefined; for (var i = 0, l = cues.length; i < l; i++) { cue = cues[i]; var mi = new _chaptersTrackMenuItemJs2['default'](this.player_, { 'track': chaptersTrack, 'cue': cue }); items.push(mi); menu.addChild(mi); } this.addChild(menu); } if (this.items.length > 0) { this.show(); } return menu; }; return ChaptersButton; })(_textTrackButtonJs2['default']); ChaptersButton.prototype.kind_ = 'chapters'; ChaptersButton.prototype.controlText_ = 'Chapters'; _componentJs2['default'].registerComponent('ChaptersButton', ChaptersButton); exports['default'] = ChaptersButton; module.exports = exports['default']; },{"../../component.js":48,"../../menu/menu.js":86,"../../utils/dom.js":107,"../../utils/fn.js":109,"../../utils/to-title-case.js":116,"./chapters-track-menu-item.js":65,"./text-track-button.js":68,"./text-track-menu-item.js":69,"global/window":2}],65:[function(_dereq_,module,exports){ /** * @file chapters-track-menu-item.js */ 'use strict'; exports.__esModule = true; function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj['default'] = obj; return newObj; } } function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var _menuMenuItemJs = _dereq_('../../menu/menu-item.js'); var _menuMenuItemJs2 = _interopRequireDefault(_menuMenuItemJs); var _componentJs = _dereq_('../../component.js'); var _componentJs2 = _interopRequireDefault(_componentJs); var _utilsFnJs = _dereq_('../../utils/fn.js'); var Fn = _interopRequireWildcard(_utilsFnJs); /** * The chapter track menu item * * @param {Player|Object} player * @param {Object=} options * @extends MenuItem * @class ChaptersTrackMenuItem */ var ChaptersTrackMenuItem = (function (_MenuItem) { _inherits(ChaptersTrackMenuItem, _MenuItem); function ChaptersTrackMenuItem(player, options) { _classCallCheck(this, ChaptersTrackMenuItem); var track = options['track']; var cue = options['cue']; var currentTime = player.currentTime(); // Modify options for parent MenuItem class's init. options['label'] = cue.text; options['selected'] = cue['startTime'] <= currentTime && currentTime < cue['endTime']; _MenuItem.call(this, player, options); this.track = track; this.cue = cue; track.addEventListener('cuechange', Fn.bind(this, this.update)); } /** * Handle click on menu item * * @method handleClick */ ChaptersTrackMenuItem.prototype.handleClick = function handleClick() { _MenuItem.prototype.handleClick.call(this); this.player_.currentTime(this.cue.startTime); this.update(this.cue.startTime); }; /** * Update chapter menu item * * @method update */ ChaptersTrackMenuItem.prototype.update = function update() { var cue = this.cue; var currentTime = this.player_.currentTime(); // vjs.log(currentTime, cue.startTime); this.selected(cue['startTime'] <= currentTime && currentTime < cue['endTime']); }; return ChaptersTrackMenuItem; })(_menuMenuItemJs2['default']); _componentJs2['default'].registerComponent('ChaptersTrackMenuItem', ChaptersTrackMenuItem); exports['default'] = ChaptersTrackMenuItem; module.exports = exports['default']; },{"../../component.js":48,"../../menu/menu-item.js":85,"../../utils/fn.js":109}],66:[function(_dereq_,module,exports){ /** * @file off-text-track-menu-item.js */ 'use strict'; exports.__esModule = true; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var _textTrackMenuItemJs = _dereq_('./text-track-menu-item.js'); var _textTrackMenuItemJs2 = _interopRequireDefault(_textTrackMenuItemJs); var _componentJs = _dereq_('../../component.js'); var _componentJs2 = _interopRequireDefault(_componentJs); /** * A special menu item for turning of a specific type of text track * * @param {Player|Object} player * @param {Object=} options * @extends TextTrackMenuItem * @class OffTextTrackMenuItem */ var OffTextTrackMenuItem = (function (_TextTrackMenuItem) { _inherits(OffTextTrackMenuItem, _TextTrackMenuItem); function OffTextTrackMenuItem(player, options) { _classCallCheck(this, OffTextTrackMenuItem); // Create pseudo track info // Requires options['kind'] options['track'] = { 'kind': options['kind'], 'player': player, 'label': options['kind'] + ' off', 'default': false, 'mode': 'disabled' }; _TextTrackMenuItem.call(this, player, options); this.selected(true); } /** * Handle text track change * * @param {Object} event Event object * @method handleTracksChange */ OffTextTrackMenuItem.prototype.handleTracksChange = function handleTracksChange(event) { var tracks = this.player().textTracks(); var selected = true; for (var i = 0, l = tracks.length; i < l; i++) { var track = tracks[i]; if (track['kind'] === this.track['kind'] && track['mode'] === 'showing') { selected = false; break; } } this.selected(selected); }; return OffTextTrackMenuItem; })(_textTrackMenuItemJs2['default']); _componentJs2['default'].registerComponent('OffTextTrackMenuItem', OffTextTrackMenuItem); exports['default'] = OffTextTrackMenuItem; module.exports = exports['default']; },{"../../component.js":48,"./text-track-menu-item.js":69}],67:[function(_dereq_,module,exports){ /** * @file subtitles-button.js */ 'use strict'; exports.__esModule = true; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var _textTrackButtonJs = _dereq_('./text-track-button.js'); var _textTrackButtonJs2 = _interopRequireDefault(_textTrackButtonJs); var _componentJs = _dereq_('../../component.js'); var _componentJs2 = _interopRequireDefault(_componentJs); /** * The button component for toggling and selecting subtitles * * @param {Object} player Player object * @param {Object=} options Object of option names and values * @param {Function=} ready Ready callback function * @extends TextTrackButton * @class SubtitlesButton */ var SubtitlesButton = (function (_TextTrackButton) { _inherits(SubtitlesButton, _TextTrackButton); function SubtitlesButton(player, options, ready) { _classCallCheck(this, SubtitlesButton); _TextTrackButton.call(this, player, options, ready); this.el_.setAttribute('aria-label', 'Subtitles Menu'); } /** * Allow sub components to stack CSS class names * * @return {String} The constructed class name * @method buildCSSClass */ SubtitlesButton.prototype.buildCSSClass = function buildCSSClass() { return 'vjs-subtitles-button ' + _TextTrackButton.prototype.buildCSSClass.call(this); }; return SubtitlesButton; })(_textTrackButtonJs2['default']); SubtitlesButton.prototype.kind_ = 'subtitles'; SubtitlesButton.prototype.controlText_ = 'Subtitles'; _componentJs2['default'].registerComponent('SubtitlesButton', SubtitlesButton); exports['default'] = SubtitlesButton; module.exports = exports['default']; },{"../../component.js":48,"./text-track-button.js":68}],68:[function(_dereq_,module,exports){ /** * @file text-track-button.js */ 'use strict'; exports.__esModule = true; function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj['default'] = obj; return newObj; } } function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var _menuMenuButtonJs = _dereq_('../../menu/menu-button.js'); var _menuMenuButtonJs2 = _interopRequireDefault(_menuMenuButtonJs); var _componentJs = _dereq_('../../component.js'); var _componentJs2 = _interopRequireDefault(_componentJs); var _utilsFnJs = _dereq_('../../utils/fn.js'); var Fn = _interopRequireWildcard(_utilsFnJs); var _textTrackMenuItemJs = _dereq_('./text-track-menu-item.js'); var _textTrackMenuItemJs2 = _interopRequireDefault(_textTrackMenuItemJs); var _offTextTrackMenuItemJs = _dereq_('./off-text-track-menu-item.js'); var _offTextTrackMenuItemJs2 = _interopRequireDefault(_offTextTrackMenuItemJs); /** * The base class for buttons that toggle specific text track types (e.g. subtitles) * * @param {Player|Object} player * @param {Object=} options * @extends MenuButton * @class TextTrackButton */ var TextTrackButton = (function (_MenuButton) { _inherits(TextTrackButton, _MenuButton); function TextTrackButton(player, options) { _classCallCheck(this, TextTrackButton); _MenuButton.call(this, player, options); var tracks = this.player_.textTracks(); if (this.items.length <= 1) { this.hide(); } if (!tracks) { return; } var updateHandler = Fn.bind(this, this.update); tracks.addEventListener('removetrack', updateHandler); tracks.addEventListener('addtrack', updateHandler); this.player_.on('dispose', function () { tracks.removeEventListener('removetrack', updateHandler); tracks.removeEventListener('addtrack', updateHandler); }); } // Create a menu item for each text track TextTrackButton.prototype.createItems = function createItems() { var items = arguments.length <= 0 || arguments[0] === undefined ? [] : arguments[0]; // Add an OFF menu item to turn all tracks off items.push(new _offTextTrackMenuItemJs2['default'](this.player_, { 'kind': this.kind_ })); var tracks = this.player_.textTracks(); if (!tracks) { return items; } for (var i = 0; i < tracks.length; i++) { var track = tracks[i]; // only add tracks that are of the appropriate kind and have a label if (track['kind'] === this.kind_) { items.push(new _textTrackMenuItemJs2['default'](this.player_, { 'track': track })); } } return items; }; return TextTrackButton; })(_menuMenuButtonJs2['default']); _componentJs2['default'].registerComponent('TextTrackButton', TextTrackButton); exports['default'] = TextTrackButton; module.exports = exports['default']; },{"../../component.js":48,"../../menu/menu-button.js":84,"../../utils/fn.js":109,"./off-text-track-menu-item.js":66,"./text-track-menu-item.js":69}],69:[function(_dereq_,module,exports){ /** * @file text-track-menu-item.js */ 'use strict'; exports.__esModule = true; function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj['default'] = obj; return newObj; } } function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var _menuMenuItemJs = _dereq_('../../menu/menu-item.js'); var _menuMenuItemJs2 = _interopRequireDefault(_menuMenuItemJs); var _componentJs = _dereq_('../../component.js'); var _componentJs2 = _interopRequireDefault(_componentJs); var _utilsFnJs = _dereq_('../../utils/fn.js'); var Fn = _interopRequireWildcard(_utilsFnJs); var _globalWindow = _dereq_('global/window'); var _globalWindow2 = _interopRequireDefault(_globalWindow); var _globalDocument = _dereq_('global/document'); var _globalDocument2 = _interopRequireDefault(_globalDocument); /** * The specific menu item type for selecting a language within a text track kind * * @param {Player|Object} player * @param {Object=} options * @extends MenuItem * @class TextTrackMenuItem */ var TextTrackMenuItem = (function (_MenuItem) { _inherits(TextTrackMenuItem, _MenuItem); function TextTrackMenuItem(player, options) { var _this = this; _classCallCheck(this, TextTrackMenuItem); var track = options['track']; var tracks = player.textTracks(); // Modify options for parent MenuItem class's init. options['label'] = track['label'] || track['language'] || 'Unknown'; options['selected'] = track['default'] || track['mode'] === 'showing'; _MenuItem.call(this, player, options); this.track = track; if (tracks) { (function () { var changeHandler = Fn.bind(_this, _this.handleTracksChange); tracks.addEventListener('change', changeHandler); _this.on('dispose', function () { tracks.removeEventListener('change', changeHandler); }); })(); } // iOS7 doesn't dispatch change events to TextTrackLists when an // associated track's mode changes. Without something like // Object.observe() (also not present on iOS7), it's not // possible to detect changes to the mode attribute and polyfill // the change event. As a poor substitute, we manually dispatch // change events whenever the controls modify the mode. if (tracks && tracks.onchange === undefined) { (function () { var event = undefined; _this.on(['tap', 'click'], function () { if (typeof _globalWindow2['default'].Event !== 'object') { // Android 2.3 throws an Illegal Constructor error for window.Event try { event = new _globalWindow2['default'].Event('change'); } catch (err) {} } if (!event) { event = _globalDocument2['default'].createEvent('Event'); event.initEvent('change', true, true); } tracks.dispatchEvent(event); }); })(); } } /** * Handle click on text track * * @method handleClick */ TextTrackMenuItem.prototype.handleClick = function handleClick(event) { var kind = this.track['kind']; var tracks = this.player_.textTracks(); _MenuItem.prototype.handleClick.call(this, event); if (!tracks) return; for (var i = 0; i < tracks.length; i++) { var track = tracks[i]; if (track['kind'] !== kind) { continue; } if (track === this.track) { track['mode'] = 'showing'; } else { track['mode'] = 'disabled'; } } }; /** * Handle text track change * * @method handleTracksChange */ TextTrackMenuItem.prototype.handleTracksChange = function handleTracksChange(event) { this.selected(this.track['mode'] === 'showing'); }; return TextTrackMenuItem; })(_menuMenuItemJs2['default']); _componentJs2['default'].registerComponent('TextTrackMenuItem', TextTrackMenuItem); exports['default'] = TextTrackMenuItem; module.exports = exports['default']; },{"../../component.js":48,"../../menu/menu-item.js":85,"../../utils/fn.js":109,"global/document":1,"global/window":2}],70:[function(_dereq_,module,exports){ /** * @file current-time-display.js */ 'use strict'; exports.__esModule = true; function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj['default'] = obj; return newObj; } } function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var _componentJs = _dereq_('../../component.js'); var _componentJs2 = _interopRequireDefault(_componentJs); var _utilsDomJs = _dereq_('../../utils/dom.js'); var Dom = _interopRequireWildcard(_utilsDomJs); var _utilsFormatTimeJs = _dereq_('../../utils/format-time.js'); var _utilsFormatTimeJs2 = _interopRequireDefault(_utilsFormatTimeJs); /** * Displays the current time * * @param {Player|Object} player * @param {Object=} options * @extends Component * @class CurrentTimeDisplay */ var CurrentTimeDisplay = (function (_Component) { _inherits(CurrentTimeDisplay, _Component); function CurrentTimeDisplay(player, options) { _classCallCheck(this, CurrentTimeDisplay); _Component.call(this, player, options); this.on(player, 'timeupdate', this.updateContent); } /** * Create the component's DOM element * * @return {Element} * @method createEl */ CurrentTimeDisplay.prototype.createEl = function createEl() { var el = _Component.prototype.createEl.call(this, 'div', { className: 'vjs-current-time vjs-time-control vjs-control' }); this.contentEl_ = Dom.createEl('div', { className: 'vjs-current-time-display', innerHTML: '<span class="vjs-control-text">Current Time </span>' + '0:00', // label the current time for screen reader users 'aria-live': 'off' // tell screen readers not to automatically read the time as it changes }); el.appendChild(this.contentEl_); return el; }; /** * Update current time display * * @method updateContent */ CurrentTimeDisplay.prototype.updateContent = function updateContent() { // Allows for smooth scrubbing, when player can't keep up. var time = this.player_.scrubbing() ? this.player_.getCache().currentTime : this.player_.currentTime(); var localizedText = this.localize('Current Time'); var formattedTime = _utilsFormatTimeJs2['default'](time, this.player_.duration()); this.contentEl_.innerHTML = '<span class="vjs-control-text">' + localizedText + '</span> ' + formattedTime; }; return CurrentTimeDisplay; })(_componentJs2['default']); _componentJs2['default'].registerComponent('CurrentTimeDisplay', CurrentTimeDisplay); exports['default'] = CurrentTimeDisplay; module.exports = exports['default']; },{"../../component.js":48,"../../utils/dom.js":107,"../../utils/format-time.js":110}],71:[function(_dereq_,module,exports){ /** * @file duration-display.js */ 'use strict'; exports.__esModule = true; function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj['default'] = obj; return newObj; } } function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var _componentJs = _dereq_('../../component.js'); var _componentJs2 = _interopRequireDefault(_componentJs); var _utilsDomJs = _dereq_('../../utils/dom.js'); var Dom = _interopRequireWildcard(_utilsDomJs); var _utilsFormatTimeJs = _dereq_('../../utils/format-time.js'); var _utilsFormatTimeJs2 = _interopRequireDefault(_utilsFormatTimeJs); /** * Displays the duration * * @param {Player|Object} player * @param {Object=} options * @extends Component * @class DurationDisplay */ var DurationDisplay = (function (_Component) { _inherits(DurationDisplay, _Component); function DurationDisplay(player, options) { _classCallCheck(this, DurationDisplay); _Component.call(this, player, options); // this might need to be changed to 'durationchange' instead of 'timeupdate' eventually, // however the durationchange event fires before this.player_.duration() is set, // so the value cannot be written out using this method. // Once the order of durationchange and this.player_.duration() being set is figured out, // this can be updated. this.on(player, 'timeupdate', this.updateContent); this.on(player, 'loadedmetadata', this.updateContent); } /** * Create the component's DOM element * * @return {Element} * @method createEl */ DurationDisplay.prototype.createEl = function createEl() { var el = _Component.prototype.createEl.call(this, 'div', { className: 'vjs-duration vjs-time-control vjs-control' }); this.contentEl_ = Dom.createEl('div', { className: 'vjs-duration-display', innerHTML: '<span class="vjs-control-text">' + this.localize('Duration Time') + '</span> 0:00', // label the duration time for screen reader users 'aria-live': 'off' // tell screen readers not to automatically read the time as it changes }); el.appendChild(this.contentEl_); return el; }; /** * Update duration time display * * @method updateContent */ DurationDisplay.prototype.updateContent = function updateContent() { var duration = this.player_.duration(); if (duration) { var localizedText = this.localize('Duration Time'); var formattedTime = _utilsFormatTimeJs2['default'](duration); this.contentEl_.innerHTML = '<span class="vjs-control-text">' + localizedText + '</span> ' + formattedTime; // label the duration time for screen reader users } }; return DurationDisplay; })(_componentJs2['default']); _componentJs2['default'].registerComponent('DurationDisplay', DurationDisplay); exports['default'] = DurationDisplay; module.exports = exports['default']; },{"../../component.js":48,"../../utils/dom.js":107,"../../utils/format-time.js":110}],72:[function(_dereq_,module,exports){ /** * @file remaining-time-display.js */ 'use strict'; exports.__esModule = true; function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj['default'] = obj; return newObj; } } function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var _componentJs = _dereq_('../../component.js'); var _componentJs2 = _interopRequireDefault(_componentJs); var _utilsDomJs = _dereq_('../../utils/dom.js'); var Dom = _interopRequireWildcard(_utilsDomJs); var _utilsFormatTimeJs = _dereq_('../../utils/format-time.js'); var _utilsFormatTimeJs2 = _interopRequireDefault(_utilsFormatTimeJs); /** * Displays the time left in the video * * @param {Player|Object} player * @param {Object=} options * @extends Component * @class RemainingTimeDisplay */ var RemainingTimeDisplay = (function (_Component) { _inherits(RemainingTimeDisplay, _Component); function RemainingTimeDisplay(player, options) { _classCallCheck(this, RemainingTimeDisplay); _Component.call(this, player, options); this.on(player, 'timeupdate', this.updateContent); } /** * Create the component's DOM element * * @return {Element} * @method createEl */ RemainingTimeDisplay.prototype.createEl = function createEl() { var el = _Component.prototype.createEl.call(this, 'div', { className: 'vjs-remaining-time vjs-time-control vjs-control' }); this.contentEl_ = Dom.createEl('div', { className: 'vjs-remaining-time-display', innerHTML: '<span class="vjs-control-text">' + this.localize('Remaining Time') + '</span> -0:00', // label the remaining time for screen reader users 'aria-live': 'off' // tell screen readers not to automatically read the time as it changes }); el.appendChild(this.contentEl_); return el; }; /** * Update remaining time display * * @method updateContent */ RemainingTimeDisplay.prototype.updateContent = function updateContent() { if (this.player_.duration()) { var localizedText = this.localize('Remaining Time'); var formattedTime = _utilsFormatTimeJs2['default'](this.player_.remainingTime()); this.contentEl_.innerHTML = '<span class="vjs-control-text">' + localizedText + '</span> -' + formattedTime; } // Allows for smooth scrubbing, when player can't keep up. // var time = (this.player_.scrubbing()) ? this.player_.getCache().currentTime : this.player_.currentTime(); // this.contentEl_.innerHTML = vjs.formatTime(time, this.player_.duration()); }; return RemainingTimeDisplay; })(_componentJs2['default']); _componentJs2['default'].registerComponent('RemainingTimeDisplay', RemainingTimeDisplay); exports['default'] = RemainingTimeDisplay; module.exports = exports['default']; },{"../../component.js":48,"../../utils/dom.js":107,"../../utils/format-time.js":110}],73:[function(_dereq_,module,exports){ /** * @file time-divider.js */ 'use strict'; exports.__esModule = true; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var _componentJs = _dereq_('../../component.js'); var _componentJs2 = _interopRequireDefault(_componentJs); /** * The separator between the current time and duration. * Can be hidden if it's not needed in the design. * * @param {Player|Object} player * @param {Object=} options * @extends Component * @class TimeDivider */ var TimeDivider = (function (_Component) { _inherits(TimeDivider, _Component); function TimeDivider() { _classCallCheck(this, TimeDivider); _Component.apply(this, arguments); } /** * Create the component's DOM element * * @return {Element} * @method createEl */ TimeDivider.prototype.createEl = function createEl() { return _Component.prototype.createEl.call(this, 'div', { className: 'vjs-time-control vjs-time-divider', innerHTML: '<div><span>/</span></div>' }); }; return TimeDivider; })(_componentJs2['default']); _componentJs2['default'].registerComponent('TimeDivider', TimeDivider); exports['default'] = TimeDivider; module.exports = exports['default']; },{"../../component.js":48}],74:[function(_dereq_,module,exports){ /** * @file volume-bar.js */ 'use strict'; exports.__esModule = true; function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj['default'] = obj; return newObj; } } function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var _sliderSliderJs = _dereq_('../../slider/slider.js'); var _sliderSliderJs2 = _interopRequireDefault(_sliderSliderJs); var _componentJs = _dereq_('../../component.js'); var _componentJs2 = _interopRequireDefault(_componentJs); var _utilsFnJs = _dereq_('../../utils/fn.js'); var Fn = _interopRequireWildcard(_utilsFnJs); // Required children var _volumeLevelJs = _dereq_('./volume-level.js'); var _volumeLevelJs2 = _interopRequireDefault(_volumeLevelJs); /** * The bar that contains the volume level and can be clicked on to adjust the level * * @param {Player|Object} player * @param {Object=} options * @extends Slider * @class VolumeBar */ var VolumeBar = (function (_Slider) { _inherits(VolumeBar, _Slider); function VolumeBar(player, options) { _classCallCheck(this, VolumeBar); _Slider.call(this, player, options); this.on(player, 'volumechange', this.updateARIAAttributes); player.ready(Fn.bind(this, this.updateARIAAttributes)); } /** * Create the component's DOM element * * @return {Element} * @method createEl */ VolumeBar.prototype.createEl = function createEl() { return _Slider.prototype.createEl.call(this, 'div', { className: 'vjs-volume-bar', 'aria-label': 'volume level' }); }; /** * Handle mouse move on volume bar * * @method handleMouseMove */ VolumeBar.prototype.handleMouseMove = function handleMouseMove(event) { if (this.player_.muted()) { this.player_.muted(false); } this.player_.volume(this.calculateDistance(event)); }; /** * Get percent of volume level * * @retun {Number} Volume level percent * @method getPercent */ VolumeBar.prototype.getPercent = function getPercent() { if (this.player_.muted()) { return 0; } else { return this.player_.volume(); } }; /** * Increase volume level for keyboard users * * @method stepForward */ VolumeBar.prototype.stepForward = function stepForward() { this.player_.volume(this.player_.volume() + 0.1); }; /** * Decrease volume level for keyboard users * * @method stepBack */ VolumeBar.prototype.stepBack = function stepBack() { this.player_.volume(this.player_.volume() - 0.1); }; /** * Update ARIA accessibility attributes * * @method updateARIAAttributes */ VolumeBar.prototype.updateARIAAttributes = function updateARIAAttributes() { // Current value of volume bar as a percentage var volume = (this.player_.volume() * 100).toFixed(2); this.el_.setAttribute('aria-valuenow', volume); this.el_.setAttribute('aria-valuetext', volume + '%'); }; return VolumeBar; })(_sliderSliderJs2['default']); VolumeBar.prototype.options_ = { children: { 'volumeLevel': {} }, 'barName': 'volumeLevel' }; VolumeBar.prototype.playerEvent = 'volumechange'; _componentJs2['default'].registerComponent('VolumeBar', VolumeBar); exports['default'] = VolumeBar; module.exports = exports['default']; },{"../../component.js":48,"../../slider/slider.js":91,"../../utils/fn.js":109,"./volume-level.js":76}],75:[function(_dereq_,module,exports){ /** * @file volume-control.js */ 'use strict'; exports.__esModule = true; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var _componentJs = _dereq_('../../component.js'); var _componentJs2 = _interopRequireDefault(_componentJs); // Required children var _volumeBarJs = _dereq_('./volume-bar.js'); var _volumeBarJs2 = _interopRequireDefault(_volumeBarJs); /** * The component for controlling the volume level * * @param {Player|Object} player * @param {Object=} options * @extends Component * @class VolumeControl */ var VolumeControl = (function (_Component) { _inherits(VolumeControl, _Component); function VolumeControl(player, options) { _classCallCheck(this, VolumeControl); _Component.call(this, player, options); // hide volume controls when they're not supported by the current tech if (player.tech && player.tech['featuresVolumeControl'] === false) { this.addClass('vjs-hidden'); } this.on(player, 'loadstart', function () { if (player.tech['featuresVolumeControl'] === false) { this.addClass('vjs-hidden'); } else { this.removeClass('vjs-hidden'); } }); } /** * Create the component's DOM element * * @return {Element} * @method createEl */ VolumeControl.prototype.createEl = function createEl() { return _Component.prototype.createEl.call(this, 'div', { className: 'vjs-volume-control vjs-control' }); }; return VolumeControl; })(_componentJs2['default']); VolumeControl.prototype.options_ = { children: { 'volumeBar': {} } }; _componentJs2['default'].registerComponent('VolumeControl', VolumeControl); exports['default'] = VolumeControl; module.exports = exports['default']; },{"../../component.js":48,"./volume-bar.js":74}],76:[function(_dereq_,module,exports){ /** * @file volume-level.js */ 'use strict'; exports.__esModule = true; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var _componentJs = _dereq_('../../component.js'); var _componentJs2 = _interopRequireDefault(_componentJs); /** * Shows volume level * * @param {Player|Object} player * @param {Object=} options * @extends Component * @class VolumeLevel */ var VolumeLevel = (function (_Component) { _inherits(VolumeLevel, _Component); function VolumeLevel() { _classCallCheck(this, VolumeLevel); _Component.apply(this, arguments); } /** * Create the component's DOM element * * @return {Element} * @method createEl */ VolumeLevel.prototype.createEl = function createEl() { return _Component.prototype.createEl.call(this, 'div', { className: 'vjs-volume-level', innerHTML: '<span class="vjs-control-text"></span>' }); }; return VolumeLevel; })(_componentJs2['default']); _componentJs2['default'].registerComponent('VolumeLevel', VolumeLevel); exports['default'] = VolumeLevel; module.exports = exports['default']; },{"../../component.js":48}],77:[function(_dereq_,module,exports){ /** * @file volume-menu-button.js */ 'use strict'; exports.__esModule = true; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var _buttonJs = _dereq_('../button.js'); var _buttonJs2 = _interopRequireDefault(_buttonJs); var _componentJs = _dereq_('../component.js'); var _componentJs2 = _interopRequireDefault(_componentJs); var _menuMenuJs = _dereq_('../menu/menu.js'); var _menuMenuJs2 = _interopRequireDefault(_menuMenuJs); var _menuMenuButtonJs = _dereq_('../menu/menu-button.js'); var _menuMenuButtonJs2 = _interopRequireDefault(_menuMenuButtonJs); var _muteToggleJs = _dereq_('./mute-toggle.js'); var _muteToggleJs2 = _interopRequireDefault(_muteToggleJs); var _volumeControlVolumeBarJs = _dereq_('./volume-control/volume-bar.js'); var _volumeControlVolumeBarJs2 = _interopRequireDefault(_volumeControlVolumeBarJs); /** * Button for volume menu * * @param {Player|Object} player * @param {Object=} options * @extends MenuButton * @class VolumeMenuButton */ var VolumeMenuButton = (function (_MenuButton) { _inherits(VolumeMenuButton, _MenuButton); function VolumeMenuButton(player) { var options = arguments.length <= 1 || arguments[1] === undefined ? {} : arguments[1]; _classCallCheck(this, VolumeMenuButton); // If the vertical option isn't passed at all, default to true. if (options.vertical === undefined) { // If an inline volumeMenuButton is used, we should default to using a horizontal // slider for obvious reasons. if (options.inline) { options.vertical = false; } else { options.vertical = true; } } // The vertical option needs to be set on the volumeBar as well, since that will // need to be passed along to the VolumeBar constructor options.volumeBar = options.volumeBar || {}; options.volumeBar.vertical = !!options.vertical; _MenuButton.call(this, player, options); // Same listeners as MuteToggle this.on(player, 'volumechange', this.volumeUpdate); this.on(player, 'loadstart', this.volumeUpdate); // hide mute toggle if the current tech doesn't support volume control if (player.tech && player.tech['featuresVolumeControl'] === false) { this.addClass('vjs-hidden'); } this.on(player, 'loadstart', function () { if (player.tech['featuresVolumeControl'] === false) { this.addClass('vjs-hidden'); } else { this.removeClass('vjs-hidden'); } }); this.addClass('vjs-menu-button'); } /** * Allow sub components to stack CSS class names * * @return {String} The constructed class name * @method buildCSSClass */ VolumeMenuButton.prototype.buildCSSClass = function buildCSSClass() { var orientationClass = ''; if (!!this.options_.vertical) { orientationClass = 'vjs-volume-menu-button-vertical'; } else { orientationClass = 'vjs-volume-menu-button-horizontal'; } return 'vjs-volume-menu-button ' + _MenuButton.prototype.buildCSSClass.call(this) + ' ' + orientationClass; }; /** * Allow sub components to stack CSS class names * * @return {Menu} The volume menu button * @method createMenu */ VolumeMenuButton.prototype.createMenu = function createMenu() { var menu = new _menuMenuJs2['default'](this.player_, { contentElType: 'div' }); var vc = new _volumeControlVolumeBarJs2['default'](this.player_, this.options_.volumeBar); vc.on('focus', function () { menu.lockShowing(); }); vc.on('blur', function () { menu.unlockShowing(); }); menu.addChild(vc); return menu; }; /** * Handle click on volume menu and calls super * * @method handleClick */ VolumeMenuButton.prototype.handleClick = function handleClick() { _muteToggleJs2['default'].prototype.handleClick.call(this); _MenuButton.prototype.handleClick.call(this); }; return VolumeMenuButton; })(_menuMenuButtonJs2['default']); VolumeMenuButton.prototype.volumeUpdate = _muteToggleJs2['default'].prototype.update; VolumeMenuButton.prototype.controlText_ = 'Mute'; _componentJs2['default'].registerComponent('VolumeMenuButton', VolumeMenuButton); exports['default'] = VolumeMenuButton; module.exports = exports['default']; },{"../button.js":47,"../component.js":48,"../menu/menu-button.js":84,"../menu/menu.js":86,"./mute-toggle.js":52,"./volume-control/volume-bar.js":74}],78:[function(_dereq_,module,exports){ /** * @file error-display.js */ 'use strict'; exports.__esModule = true; function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj['default'] = obj; return newObj; } } function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var _component = _dereq_('./component'); var _component2 = _interopRequireDefault(_component); var _utilsDomJs = _dereq_('./utils/dom.js'); var Dom = _interopRequireWildcard(_utilsDomJs); /** * Display that an error has occurred making the video unplayable * * @param {Object} player Main Player * @param {Object=} options Object of option names and values * @extends Component * @class ErrorDisplay */ var ErrorDisplay = (function (_Component) { _inherits(ErrorDisplay, _Component); function ErrorDisplay(player, options) { _classCallCheck(this, ErrorDisplay); _Component.call(this, player, options); this.update(); this.on(player, 'error', this.update); } /** * Create the component's DOM element * * @return {Element} * @method createEl */ ErrorDisplay.prototype.createEl = function createEl() { var el = _Component.prototype.createEl.call(this, 'div', { className: 'vjs-error-display' }); this.contentEl_ = Dom.createEl('div'); el.appendChild(this.contentEl_); return el; }; /** * Update the error message in localized language * * @method update */ ErrorDisplay.prototype.update = function update() { if (this.player().error()) { this.contentEl_.innerHTML = this.localize(this.player().error().message); } }; return ErrorDisplay; })(_component2['default']); _component2['default'].registerComponent('ErrorDisplay', ErrorDisplay); exports['default'] = ErrorDisplay; module.exports = exports['default']; },{"./component":48,"./utils/dom.js":107}],79:[function(_dereq_,module,exports){ /** * @file event-target.js */ 'use strict'; exports.__esModule = true; function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj['default'] = obj; return newObj; } } var _utilsEventsJs = _dereq_('./utils/events.js'); var Events = _interopRequireWildcard(_utilsEventsJs); var EventTarget = function EventTarget() {}; EventTarget.prototype.allowedEvents_ = {}; EventTarget.prototype.on = function (type, fn) { // Remove the addEventListener alias before calling Events.on // so we don't get into an infinite type loop var ael = this.addEventListener; this.addEventListener = Function.prototype; Events.on(this, type, fn); this.addEventListener = ael; }; EventTarget.prototype.addEventListener = EventTarget.prototype.on; EventTarget.prototype.off = function (type, fn) { Events.off(this, type, fn); }; EventTarget.prototype.removeEventListener = EventTarget.prototype.off; EventTarget.prototype.one = function (type, fn) { Events.one(this, type, fn); }; EventTarget.prototype.trigger = function (event) { var type = event.type || event; if (typeof event === 'string') { event = { type: type }; } event = Events.fixEvent(event); if (this.allowedEvents_[type] && this['on' + type]) { this['on' + type](event); } Events.trigger(this, event); }; // The standard DOM EventTarget.dispatchEvent() is aliased to trigger() EventTarget.prototype.dispatchEvent = EventTarget.prototype.trigger; exports['default'] = EventTarget; module.exports = exports['default']; },{"./utils/events.js":108}],80:[function(_dereq_,module,exports){ 'use strict'; exports.__esModule = true; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } var _utilsLog = _dereq_('./utils/log'); var _utilsLog2 = _interopRequireDefault(_utilsLog); /* * @file extends.js * * A combination of node inherits and babel's inherits (after transpile). * Both work the same but node adds `super_` to the subClass * and Bable adds the superClass as __proto__. Both seem useful. */ var _inherits = function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) { // node subClass.super_ = superClass; } }; /* * Function for subclassing using the same inheritance that * videojs uses internally * ```js * var Button = videojs.getComponent('Button'); * ``` * ```js * var MyButton = videojs.extends(Button, { * constructor: function(player, options) { * Button.call(this, player, options); * }, * onClick: function() { * // doSomething * } * }); * ``` */ var extendsFn = function extendsFn(superClass) { var subClassMethods = arguments.length <= 1 || arguments[1] === undefined ? {} : arguments[1]; var subClass = function subClass() { superClass.apply(this, arguments); }; var methods = {}; if (typeof subClassMethods === 'object') { if (typeof subClassMethods.init === 'function') { _utilsLog2['default'].warn('Constructor logic via init() is deprecated; please use constructor() instead.'); subClassMethods.constructor = subClassMethods.init; } if (subClassMethods.constructor !== Object.prototype.constructor) { subClass = subClassMethods.constructor; } methods = subClassMethods; } else if (typeof subClassMethods === 'function') { subClass = subClassMethods; } _inherits(subClass, superClass); // Extend subObj's prototype with functions and other properties from props for (var name in methods) { if (methods.hasOwnProperty(name)) { subClass.prototype[name] = methods[name]; } } return subClass; }; exports['default'] = extendsFn; module.exports = exports['default']; },{"./utils/log":112}],81:[function(_dereq_,module,exports){ /** * @file fullscreen-api.js */ 'use strict'; exports.__esModule = true; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } var _globalDocument = _dereq_('global/document'); var _globalDocument2 = _interopRequireDefault(_globalDocument); /* * Store the browser-specific methods for the fullscreen API * @type {Object|undefined} * @private */ var FullscreenApi = {}; // browser API methods // map approach from Screenful.js - https://github.com/sindresorhus/screenfull.js var apiMap = [ // Spec: https://dvcs.w3.org/hg/fullscreen/raw-file/tip/Overview.html ['requestFullscreen', 'exitFullscreen', 'fullscreenElement', 'fullscreenEnabled', 'fullscreenchange', 'fullscreenerror'], // WebKit ['webkitRequestFullscreen', 'webkitExitFullscreen', 'webkitFullscreenElement', 'webkitFullscreenEnabled', 'webkitfullscreenchange', 'webkitfullscreenerror'], // Old WebKit (Safari 5.1) ['webkitRequestFullScreen', 'webkitCancelFullScreen', 'webkitCurrentFullScreenElement', 'webkitCancelFullScreen', 'webkitfullscreenchange', 'webkitfullscreenerror'], // Mozilla ['mozRequestFullScreen', 'mozCancelFullScreen', 'mozFullScreenElement', 'mozFullScreenEnabled', 'mozfullscreenchange', 'mozfullscreenerror'], // Microsoft ['msRequestFullscreen', 'msExitFullscreen', 'msFullscreenElement', 'msFullscreenEnabled', 'MSFullscreenChange', 'MSFullscreenError']]; var specApi = apiMap[0]; var browserApi = undefined; // determine the supported set of functions for (var i = 0; i < apiMap.length; i++) { // check for exitFullscreen function if (apiMap[i][1] in _globalDocument2['default']) { browserApi = apiMap[i]; break; } } // map the browser API names to the spec API names if (browserApi) { for (var i = 0; i < browserApi.length; i++) { FullscreenApi[specApi[i]] = browserApi[i]; } } exports['default'] = FullscreenApi; module.exports = exports['default']; },{"global/document":1}],82:[function(_dereq_,module,exports){ /** * @file loading-spinner.js */ 'use strict'; exports.__esModule = true; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var _component = _dereq_('./component'); var _component2 = _interopRequireDefault(_component); /* Loading Spinner ================================================================================ */ /** * Loading spinner for waiting events * * @extends Component * @class LoadingSpinner */ var LoadingSpinner = (function (_Component) { _inherits(LoadingSpinner, _Component); function LoadingSpinner() { _classCallCheck(this, LoadingSpinner); _Component.apply(this, arguments); } /** * Create the component's DOM element * * @method createEl */ LoadingSpinner.prototype.createEl = function createEl() { return _Component.prototype.createEl.call(this, 'div', { className: 'vjs-loading-spinner' }); }; return LoadingSpinner; })(_component2['default']); _component2['default'].registerComponent('LoadingSpinner', LoadingSpinner); exports['default'] = LoadingSpinner; module.exports = exports['default']; },{"./component":48}],83:[function(_dereq_,module,exports){ /** * @file media-error.js */ 'use strict'; exports.__esModule = true; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } var _objectAssign = _dereq_('object.assign'); var _objectAssign2 = _interopRequireDefault(_objectAssign); /* * Custom MediaError to mimic the HTML5 MediaError * * @param {Number} code The media error code */ var MediaError = function MediaError(code) { if (typeof code === 'number') { this.code = code; } else if (typeof code === 'string') { // default code is zero, so this is a custom error this.message = code; } else if (typeof code === 'object') { // object _objectAssign2['default'](this, code); } if (!this.message) { this.message = MediaError.defaultMessages[this.code] || ''; } }; /* * The error code that refers two one of the defined * MediaError types * * @type {Number} */ MediaError.prototype.code = 0; /* * An optional message to be shown with the error. * Message is not part of the HTML5 video spec * but allows for more informative custom errors. * * @type {String} */ MediaError.prototype.message = ''; /* * An optional status code that can be set by plugins * to allow even more detail about the error. * For example the HLS plugin might provide the specific * HTTP status code that was returned when the error * occurred, then allowing a custom error overlay * to display more information. * * @type {Array} */ MediaError.prototype.status = null; MediaError.errorTypes = ['MEDIA_ERR_CUSTOM', // = 0 'MEDIA_ERR_ABORTED', // = 1 'MEDIA_ERR_NETWORK', // = 2 'MEDIA_ERR_DECODE', // = 3 'MEDIA_ERR_SRC_NOT_SUPPORTED', // = 4 'MEDIA_ERR_ENCRYPTED' // = 5 ]; MediaError.defaultMessages = { 1: 'You aborted the media playback', 2: 'A network error caused the media download to fail part-way.', 3: 'The media playback was aborted due to a corruption problem or because the media used features your browser did not support.', 4: 'The media could not be loaded, either because the server or network failed or because the format is not supported.', 5: 'The media is encrypted and we do not have the keys to decrypt it.' }; // Add types as properties on MediaError // e.g. MediaError.MEDIA_ERR_SRC_NOT_SUPPORTED = 4; for (var errNum = 0; errNum < MediaError.errorTypes.length; errNum++) { MediaError[MediaError.errorTypes[errNum]] = errNum; // values should be accessible on both the class and instance MediaError.prototype[MediaError.errorTypes[errNum]] = errNum; } exports['default'] = MediaError; module.exports = exports['default']; },{"object.assign":40}],84:[function(_dereq_,module,exports){ /** * @file menu-button.js */ 'use strict'; exports.__esModule = true; function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj['default'] = obj; return newObj; } } function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var _buttonJs = _dereq_('../button.js'); var _buttonJs2 = _interopRequireDefault(_buttonJs); var _componentJs = _dereq_('../component.js'); var _componentJs2 = _interopRequireDefault(_componentJs); var _menuJs = _dereq_('./menu.js'); var _menuJs2 = _interopRequireDefault(_menuJs); var _utilsDomJs = _dereq_('../utils/dom.js'); var Dom = _interopRequireWildcard(_utilsDomJs); var _utilsFnJs = _dereq_('../utils/fn.js'); var Fn = _interopRequireWildcard(_utilsFnJs); var _utilsToTitleCaseJs = _dereq_('../utils/to-title-case.js'); var _utilsToTitleCaseJs2 = _interopRequireDefault(_utilsToTitleCaseJs); /** * A button class with a popup menu * * @param {Player|Object} player * @param {Object=} options * @extends Button * @class MenuButton */ var MenuButton = (function (_Button) { _inherits(MenuButton, _Button); function MenuButton(player) { var options = arguments.length <= 1 || arguments[1] === undefined ? {} : arguments[1]; _classCallCheck(this, MenuButton); _Button.call(this, player, options); this.update(); this.on('keydown', this.handleKeyPress); this.el_.setAttribute('aria-haspopup', true); this.el_.setAttribute('role', 'button'); } /** * Update menu * * @method update */ MenuButton.prototype.update = function update() { var menu = this.createMenu(); if (this.menu) { this.removeChild(this.menu); } this.menu = menu; this.addChild(menu); /** * Track the state of the menu button * * @type {Boolean} * @private */ this.buttonPressed_ = false; if (this.items && this.items.length === 0) { this.hide(); } else if (this.items && this.items.length > 1) { this.show(); } }; /** * Create menu * * @return {Menu} The constructed menu * @method createMenu */ MenuButton.prototype.createMenu = function createMenu() { var menu = new _menuJs2['default'](this.player_); // Add a title list item to the top if (this.options_.title) { menu.contentEl().appendChild(Dom.createEl('li', { className: 'vjs-menu-title', innerHTML: _utilsToTitleCaseJs2['default'](this.options_.title), tabIndex: -1 })); } this.items = this['createItems'](); if (this.items) { // Add menu items to the menu for (var i = 0; i < this.items.length; i++) { menu.addItem(this.items[i]); } } return menu; }; /** * Create the list of menu items. Specific to each subclass. * * @method createItems */ MenuButton.prototype.createItems = function createItems() {}; /** * Create the component's DOM element * * @return {Element} * @method createEl */ MenuButton.prototype.createEl = function createEl() { return _Button.prototype.createEl.call(this, 'div', { className: this.buildCSSClass() }); }; /** * Allow sub components to stack CSS class names * * @return {String} The constructed class name * @method buildCSSClass */ MenuButton.prototype.buildCSSClass = function buildCSSClass() { var menuButtonClass = 'vjs-menu-button'; // If the inline option is passed, we want to use different styles altogether. if (this.options_.inline === true) { menuButtonClass += '-inline'; } else { menuButtonClass += '-popup'; } return 'vjs-menu-button ' + menuButtonClass + ' ' + _Button.prototype.buildCSSClass.call(this); }; /** * Focus - Add keyboard functionality to element * This function is not needed anymore. Instead, the * keyboard functionality is handled by * treating the button as triggering a submenu. * When the button is pressed, the submenu * appears. Pressing the button again makes * the submenu disappear. * * @method handleFocus */ MenuButton.prototype.handleFocus = function handleFocus() {}; /** * Can't turn off list display that we turned * on with focus, because list would go away. * * @method handleBlur */ MenuButton.prototype.handleBlur = function handleBlur() {}; /** * When you click the button it adds focus, which * will show the menu indefinitely. * So we'll remove focus when the mouse leaves the button. * Focus is needed for tab navigation. * Allow sub components to stack CSS class names * * @method handleClick */ MenuButton.prototype.handleClick = function handleClick() { this.one('mouseout', Fn.bind(this, function () { this.menu.unlockShowing(); this.el_.blur(); })); if (this.buttonPressed_) { this.unpressButton(); } else { this.pressButton(); } }; /** * Handle key press on menu * * @param {Object} Key press event * @method handleKeyPress */ MenuButton.prototype.handleKeyPress = function handleKeyPress(event) { // Check for space bar (32) or enter (13) keys if (event.which === 32 || event.which === 13) { if (this.buttonPressed_) { this.unpressButton(); } else { this.pressButton(); } event.preventDefault(); // Check for escape (27) key } else if (event.which === 27) { if (this.buttonPressed_) { this.unpressButton(); } event.preventDefault(); } }; /** * Makes changes based on button pressed * * @method pressButton */ MenuButton.prototype.pressButton = function pressButton() { this.buttonPressed_ = true; this.menu.lockShowing(); this.el_.setAttribute('aria-pressed', true); if (this.items && this.items.length > 0) { this.items[0].el().focus(); // set the focus to the title of the submenu } }; /** * Makes changes based on button unpressed * * @method unpressButton */ MenuButton.prototype.unpressButton = function unpressButton() { this.buttonPressed_ = false; this.menu.unlockShowing(); this.el_.setAttribute('aria-pressed', false); }; return MenuButton; })(_buttonJs2['default']); _componentJs2['default'].registerComponent('MenuButton', MenuButton); exports['default'] = MenuButton; module.exports = exports['default']; },{"../button.js":47,"../component.js":48,"../utils/dom.js":107,"../utils/fn.js":109,"../utils/to-title-case.js":116,"./menu.js":86}],85:[function(_dereq_,module,exports){ /** * @file menu-item.js */ 'use strict'; exports.__esModule = true; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var _buttonJs = _dereq_('../button.js'); var _buttonJs2 = _interopRequireDefault(_buttonJs); var _componentJs = _dereq_('../component.js'); var _componentJs2 = _interopRequireDefault(_componentJs); var _objectAssign = _dereq_('object.assign'); var _objectAssign2 = _interopRequireDefault(_objectAssign); /** * The component for a menu item. `<li>` * * @param {Player|Object} player * @param {Object=} options * @extends Button * @class MenuItem */ var MenuItem = (function (_Button) { _inherits(MenuItem, _Button); function MenuItem(player, options) { _classCallCheck(this, MenuItem); _Button.call(this, player, options); this.selected(options['selected']); } /** * Create the component's DOM element * * @param {String=} type Desc * @param {Object=} props Desc * @return {Element} * @method createEl */ MenuItem.prototype.createEl = function createEl(type, props) { return _Button.prototype.createEl.call(this, 'li', _objectAssign2['default']({ className: 'vjs-menu-item', innerHTML: this.localize(this.options_['label']) }, props)); }; /** * Handle a click on the menu item, and set it to selected * * @method handleClick */ MenuItem.prototype.handleClick = function handleClick() { this.selected(true); }; /** * Set this menu item as selected or not * * @param {Boolean} selected * @method selected */ MenuItem.prototype.selected = function selected(_selected) { if (_selected) { this.addClass('vjs-selected'); this.el_.setAttribute('aria-selected', true); } else { this.removeClass('vjs-selected'); this.el_.setAttribute('aria-selected', false); } }; return MenuItem; })(_buttonJs2['default']); _componentJs2['default'].registerComponent('MenuItem', MenuItem); exports['default'] = MenuItem; module.exports = exports['default']; },{"../button.js":47,"../component.js":48,"object.assign":40}],86:[function(_dereq_,module,exports){ /** * @file menu.js */ 'use strict'; exports.__esModule = true; function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj['default'] = obj; return newObj; } } function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var _componentJs = _dereq_('../component.js'); var _componentJs2 = _interopRequireDefault(_componentJs); var _utilsDomJs = _dereq_('../utils/dom.js'); var Dom = _interopRequireWildcard(_utilsDomJs); var _utilsFnJs = _dereq_('../utils/fn.js'); var Fn = _interopRequireWildcard(_utilsFnJs); var _utilsEventsJs = _dereq_('../utils/events.js'); var Events = _interopRequireWildcard(_utilsEventsJs); /** * The Menu component is used to build pop up menus, including subtitle and * captions selection menus. * * @extends Component * @class Menu */ var Menu = (function (_Component) { _inherits(Menu, _Component); function Menu() { _classCallCheck(this, Menu); _Component.apply(this, arguments); } /** * Add a menu item to the menu * * @param {Object|String} component Component or component type to add * @method addItem */ Menu.prototype.addItem = function addItem(component) { this.addChild(component); component.on('click', Fn.bind(this, function () { this.unlockShowing(); })); }; /** * Create the component's DOM element * * @return {Element} * @method createEl */ Menu.prototype.createEl = function createEl() { var contentElType = this.options_.contentElType || 'ul'; this.contentEl_ = Dom.createEl(contentElType, { className: 'vjs-menu-content' }); var el = _Component.prototype.createEl.call(this, 'div', { append: this.contentEl_, className: 'vjs-menu' }); el.appendChild(this.contentEl_); // Prevent clicks from bubbling up. Needed for Menu Buttons, // where a click on the parent is significant Events.on(el, 'click', function (event) { event.preventDefault(); event.stopImmediatePropagation(); }); return el; }; return Menu; })(_componentJs2['default']); _componentJs2['default'].registerComponent('Menu', Menu); exports['default'] = Menu; module.exports = exports['default']; },{"../component.js":48,"../utils/dom.js":107,"../utils/events.js":108,"../utils/fn.js":109}],87:[function(_dereq_,module,exports){ /** * @file player.js */ // Subclasses Component 'use strict'; exports.__esModule = true; function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj['default'] = obj; return newObj; } } function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var _componentJs = _dereq_('./component.js'); var _componentJs2 = _interopRequireDefault(_componentJs); var _globalDocument = _dereq_('global/document'); var _globalDocument2 = _interopRequireDefault(_globalDocument); var _globalWindow = _dereq_('global/window'); var _globalWindow2 = _interopRequireDefault(_globalWindow); var _utilsEventsJs = _dereq_('./utils/events.js'); var Events = _interopRequireWildcard(_utilsEventsJs); var _utilsDomJs = _dereq_('./utils/dom.js'); var Dom = _interopRequireWildcard(_utilsDomJs); var _utilsFnJs = _dereq_('./utils/fn.js'); var Fn = _interopRequireWildcard(_utilsFnJs); var _utilsGuidJs = _dereq_('./utils/guid.js'); var Guid = _interopRequireWildcard(_utilsGuidJs); var _utilsBrowserJs = _dereq_('./utils/browser.js'); var browser = _interopRequireWildcard(_utilsBrowserJs); var _utilsLogJs = _dereq_('./utils/log.js'); var _utilsLogJs2 = _interopRequireDefault(_utilsLogJs); var _utilsToTitleCaseJs = _dereq_('./utils/to-title-case.js'); var _utilsToTitleCaseJs2 = _interopRequireDefault(_utilsToTitleCaseJs); var _utilsTimeRangesJs = _dereq_('./utils/time-ranges.js'); var _utilsBufferJs = _dereq_('./utils/buffer.js'); var _utilsStylesheetJs = _dereq_('./utils/stylesheet.js'); var stylesheet = _interopRequireWildcard(_utilsStylesheetJs); var _fullscreenApiJs = _dereq_('./fullscreen-api.js'); var _fullscreenApiJs2 = _interopRequireDefault(_fullscreenApiJs); var _mediaErrorJs = _dereq_('./media-error.js'); var _mediaErrorJs2 = _interopRequireDefault(_mediaErrorJs); var _safeJsonParseTuple = _dereq_('safe-json-parse/tuple'); var _safeJsonParseTuple2 = _interopRequireDefault(_safeJsonParseTuple); var _objectAssign = _dereq_('object.assign'); var _objectAssign2 = _interopRequireDefault(_objectAssign); var _utilsMergeOptionsJs = _dereq_('./utils/merge-options.js'); var _utilsMergeOptionsJs2 = _interopRequireDefault(_utilsMergeOptionsJs); var _tracksTextTrackListConverterJs = _dereq_('./tracks/text-track-list-converter.js'); var _tracksTextTrackListConverterJs2 = _interopRequireDefault(_tracksTextTrackListConverterJs); // Include required child components (importing also registers them) var _techLoaderJs = _dereq_('./tech/loader.js'); var _techLoaderJs2 = _interopRequireDefault(_techLoaderJs); var _posterImageJs = _dereq_('./poster-image.js'); var _posterImageJs2 = _interopRequireDefault(_posterImageJs); var _tracksTextTrackDisplayJs = _dereq_('./tracks/text-track-display.js'); var _tracksTextTrackDisplayJs2 = _interopRequireDefault(_tracksTextTrackDisplayJs); var _loadingSpinnerJs = _dereq_('./loading-spinner.js'); var _loadingSpinnerJs2 = _interopRequireDefault(_loadingSpinnerJs); var _bigPlayButtonJs = _dereq_('./big-play-button.js'); var _bigPlayButtonJs2 = _interopRequireDefault(_bigPlayButtonJs); var _controlBarControlBarJs = _dereq_('./control-bar/control-bar.js'); var _controlBarControlBarJs2 = _interopRequireDefault(_controlBarControlBarJs); var _errorDisplayJs = _dereq_('./error-display.js'); var _errorDisplayJs2 = _interopRequireDefault(_errorDisplayJs); var _tracksTextTrackSettingsJs = _dereq_('./tracks/text-track-settings.js'); var _tracksTextTrackSettingsJs2 = _interopRequireDefault(_tracksTextTrackSettingsJs); // Require html5 tech, at least for disposing the original video tag var _techHtml5Js = _dereq_('./tech/html5.js'); var _techHtml5Js2 = _interopRequireDefault(_techHtml5Js); /** * An instance of the `Player` class is created when any of the Video.js setup methods are used to initialize a video. * ```js * var myPlayer = videojs('example_video_1'); * ``` * In the following example, the `data-setup` attribute tells the Video.js library to create a player instance when the library is ready. * ```html * <video id="example_video_1" data-setup='{}' controls> * <source src="my-source.mp4" type="video/mp4"> * </video> * ``` * After an instance has been created it can be accessed globally using `Video('example_video_1')`. * * @param {Element} tag The original video tag used for configuring options * @param {Object=} options Object of option names and values * @param {Function=} ready Ready callback function * @extends Component * @class Player */ var Player = (function (_Component) { _inherits(Player, _Component); /** * player's constructor function * * @constructs * @method init * @param {Element} tag The original video tag used for configuring options * @param {Object=} options Player options * @param {Function=} ready Ready callback function */ function Player(tag, options, ready) { var _this = this; _classCallCheck(this, Player); // Make sure tag ID exists tag.id = tag.id || 'vjs_video_' + Guid.newGUID(); // Set Options // The options argument overrides options set in the video tag // which overrides globally set options. // This latter part coincides with the load order // (tag must exist before Player) options = _objectAssign2['default'](Player.getTagSettings(tag), options); // Delay the initialization of children because we need to set up // player properties first, and can't use `this` before `super()` options.initChildren = false; // Same with creating the element options.createEl = false; // we don't want the player to report touch activity on itself // see enableTouchActivity in Component options.reportTouchActivity = false; // Run base component initializing with new options _Component.call(this, null, options, ready); // if the global option object was accidentally blown away by // someone, bail early with an informative error if (!this.options_ || !this.options_.techOrder || !this.options_.techOrder.length) { throw new Error('No techOrder specified. Did you overwrite ' + 'videojs.options instead of just changing the ' + 'properties you want to override?'); } this.tag = tag; // Store the original tag used to set options // Store the tag attributes used to restore html5 element this.tagAttributes = tag && Dom.getElAttributes(tag); // Update current language this.language(this.options_.language); // Update Supported Languages if (options.languages) { (function () { // Normalise player option languages to lowercase var languagesToLower = {}; Object.getOwnPropertyNames(options.languages).forEach(function (name) { languagesToLower[name.toLowerCase()] = options.languages[name]; }); _this.languages_ = languagesToLower; })(); } else { this.languages_ = Player.prototype.options_.languages; } // Cache for video property values. this.cache_ = {}; // Set poster this.poster_ = options.poster || ''; // Set controls this.controls_ = !!options.controls; // Original tag settings stored in options // now remove immediately so native controls don't flash. // May be turned back on by HTML5 tech if nativeControlsForTouch is true tag.controls = false; /* * Store the internal state of scrubbing * * @private * @return {Boolean} True if the user is scrubbing */ this.scrubbing_ = false; this.el_ = this.createEl(); // We also want to pass the original player options to each component and plugin // as well so they don't need to reach back into the player for options later. // We also need to do another copy of this.options_ so we don't end up with // an infinite loop. var playerOptionsCopy = _utilsMergeOptionsJs2['default'](this.options_); // Load plugins if (options.plugins) { (function () { var plugins = options.plugins; Object.getOwnPropertyNames(plugins).forEach(function (name) { if (typeof this[name] === 'function') { this[name](plugins[name]); } else { _utilsLogJs2['default'].error('Unable to find plugin:', name); } }, _this); })(); } this.options_.playerOptions = playerOptionsCopy; this.initChildren(); // Set isAudio based on whether or not an audio tag was used this.isAudio(tag.nodeName.toLowerCase() === 'audio'); // Update controls className. Can't do this when the controls are initially // set because the element doesn't exist yet. if (this.controls()) { this.addClass('vjs-controls-enabled'); } else { this.addClass('vjs-controls-disabled'); } if (this.isAudio()) { this.addClass('vjs-audio'); } if (this.flexNotSupported_()) { this.addClass('vjs-no-flex'); } // TODO: Make this smarter. Toggle user state between touching/mousing // using events, since devices can have both touch and mouse events. // if (browser.TOUCH_ENABLED) { // this.addClass('vjs-touch-enabled'); // } // Make player easily findable by ID Player.players[this.id_] = this; // When the player is first initialized, trigger activity so components // like the control bar show themselves if needed this.userActive(true); this.reportUserActivity(); this.listenForUserActivity(); this.on('fullscreenchange', this.handleFullscreenChange); this.on('stageclick', this.handleStageClick); } /* * Global player list * * @type {Object} */ /** * Destroys the video player and does any necessary cleanup * ```js * myPlayer.dispose(); * ``` * This is especially helpful if you are dynamically adding and removing videos * to/from the DOM. * * @method dispose */ Player.prototype.dispose = function dispose() { this.trigger('dispose'); // prevent dispose from being called twice this.off('dispose'); if (this.styleEl_) { this.styleEl_.parentNode.removeChild(this.styleEl_); } // Kill reference to this player Player.players[this.id_] = null; if (this.tag && this.tag.player) { this.tag.player = null; } if (this.el_ && this.el_.player) { this.el_.player = null; } if (this.tech) { this.tech.dispose(); } _Component.prototype.dispose.call(this); }; /** * Create the component's DOM element * * @return {Element} * @method createEl */ Player.prototype.createEl = function createEl() { var el = this.el_ = _Component.prototype.createEl.call(this, 'div'); var tag = this.tag; // Remove width/height attrs from tag so CSS can make it 100% width/height tag.removeAttribute('width'); tag.removeAttribute('height'); // Copy over all the attributes from the tag, including ID and class // ID will now reference player box, not the video tag var attrs = Dom.getElAttributes(tag); Object.getOwnPropertyNames(attrs).forEach(function (attr) { // workaround so we don't totally break IE7 // http://stackoverflow.com/questions/3653444/css-styles-not-applied-on-dynamic-elements-in-internet-explorer-7 if (attr === 'class') { el.className = attrs[attr]; } else { el.setAttribute(attr, attrs[attr]); } }); // Update tag id/class for use as HTML5 playback tech // Might think we should do this after embedding in container so .vjs-tech class // doesn't flash 100% width/height, but class only applies with .video-js parent tag.id += '_html5_api'; tag.className = 'vjs-tech'; // Make player findable on elements tag.player = el.player = this; // Default state of video is paused this.addClass('vjs-paused'); // Add a style element in the player that we'll use to set the width/height // of the player in a way that's still overrideable by CSS, just like the // video element this.styleEl_ = stylesheet.createStyleElement('vjs-styles-dimensions'); var defaultsStyleEl = _globalDocument2['default'].querySelector('.vjs-styles-defaults'); var head = _globalDocument2['default'].querySelector('head'); head.insertBefore(this.styleEl_, defaultsStyleEl ? defaultsStyleEl.nextSibling : head.firstChild); // Pass in the width/height/aspectRatio options which will update the style el this.width(this.options_.width); this.height(this.options_.height); this.fluid(this.options_.fluid); this.aspectRatio(this.options_.aspectRatio); // insertElFirst seems to cause the networkState to flicker from 3 to 2, so // keep track of the original for later so we can know if the source originally failed tag.initNetworkState_ = tag.networkState; // Wrap video tag in div (el/box) container if (tag.parentNode) { tag.parentNode.insertBefore(el, tag); } Dom.insertElFirst(tag, el); // Breaks iPhone, fixed in HTML5 setup. this.el_ = el; return el; }; /** * Get/set player width * * @param {Number=} value Value for width * @return {Number} Width when getting * @method width */ Player.prototype.width = function width(value) { return this.dimension('width', value); }; /** * Get/set player height * * @param {Number=} value Value for height * @return {Number} Height when getting * @method height */ Player.prototype.height = function height(value) { return this.dimension('height', value); }; /** * Get/set dimension for player * * @param {String} dimension Either width or height * @param {Number=} value Value for dimension * @return {Component} * @method dimension */ Player.prototype.dimension = function dimension(_dimension, value) { var privDimension = _dimension + '_'; if (value === undefined) { return this[privDimension] || 0; } if (value === '') { // If an empty string is given, reset the dimension to be automatic this[privDimension] = undefined; } else { var parsedVal = parseFloat(value); if (isNaN(parsedVal)) { _utilsLogJs2['default'].error('Improper value "' + value + '" supplied for for ' + _dimension); return this; } this[privDimension] = parsedVal; } this.updateStyleEl_(); return this; }; /** * Add/remove the vjs-fluid class * * @param {Boolean} bool Value of true adds the class, value of false removes the class * @method fluid */ Player.prototype.fluid = function fluid(bool) { if (bool === undefined) { return !!this.fluid_; } this.fluid_ = !!bool; if (bool) { this.addClass('vjs-fluid'); } else { this.removeClass('vjs-fluid'); } }; /** * Get/Set the aspect ratio * * @param {String=} ratio Aspect ratio for player * @return aspectRatio * @method aspectRatio */ Player.prototype.aspectRatio = function aspectRatio(ratio) { if (ratio === undefined) { return this.aspectRatio_; } // Check for width:height format if (!/^\d+\:\d+$/.test(ratio)) { throw new Error('Improper value supplied for aspect ratio. The format should be width:height, for example 16:9.'); } this.aspectRatio_ = ratio; // We're assuming if you set an aspect ratio you want fluid mode, // because in fixed mode you could calculate width and height yourself. this.fluid(true); this.updateStyleEl_(); }; /** * Update styles of the player element (height, width and aspect ratio) * * @method updateStyleEl_ */ Player.prototype.updateStyleEl_ = function updateStyleEl_() { var width = undefined; var height = undefined; var aspectRatio = undefined; // The aspect ratio is either used directly or to calculate width and height. if (this.aspectRatio_ !== undefined && this.aspectRatio_ !== 'auto') { // Use any aspectRatio that's been specifically set aspectRatio = this.aspectRatio_; } else if (this.videoWidth()) { // Otherwise try to get the aspect ratio from the video metadata aspectRatio = this.videoWidth() + ':' + this.videoHeight(); } else { // Or use a default. The video element's is 2:1, but 16:9 is more common. aspectRatio = '16:9'; } // Get the ratio as a decimal we can use to calculate dimensions var ratioParts = aspectRatio.split(':'); var ratioMultiplier = ratioParts[1] / ratioParts[0]; if (this.width_ !== undefined) { // Use any width that's been specifically set width = this.width_; } else if (this.height_ !== undefined) { // Or calulate the width from the aspect ratio if a height has been set width = this.height_ / ratioMultiplier; } else { // Or use the video's metadata, or use the video el's default of 300 width = this.videoWidth() || 300; } if (this.height_ !== undefined) { // Use any height that's been specifically set height = this.height_; } else { // Otherwise calculate the height from the ratio and the width height = width * ratioMultiplier; } var idClass = this.id() + '-dimensions'; // Ensure the right class is still on the player for the style element this.addClass(idClass); stylesheet.setTextContent(this.styleEl_, '\n .' + idClass + ' {\n width: ' + width + 'px;\n height: ' + height + 'px;\n }\n\n .' + idClass + '.vjs-fluid {\n padding-top: ' + ratioMultiplier * 100 + '%;\n }\n '); }; /** * Load the Media Playback Technology (tech) * Load/Create an instance of playback technology including element and API methods * And append playback element in player div. * * @param {String} techName Name of the playback technology * @param {String} source Video source * @method loadTech */ Player.prototype.loadTech = function loadTech(techName, source) { // Pause and remove current playback technology if (this.tech) { this.unloadTech(); } // get rid of the HTML5 video tag as soon as we are using another tech if (techName !== 'Html5' && this.tag) { _componentJs2['default'].getComponent('Html5').disposeMediaElement(this.tag); this.tag.player = null; this.tag = null; } this.techName = techName; // Turn off API access because we're loading a new tech that might load asynchronously this.isReady_ = false; var techReady = Fn.bind(this, function () { this.triggerReady(); }); // Grab tech-specific options from player options and add source and parent element to use. var techOptions = _objectAssign2['default']({ 'nativeControlsForTouch': this.options_.nativeControlsForTouch, 'source': source, 'playerId': this.id(), 'techId': this.id() + '_' + techName + '_api', 'textTracks': this.textTracks_, 'autoplay': this.options_.autoplay, 'preload': this.options_.preload, 'loop': this.options_.loop, 'muted': this.options_.muted, 'poster': this.poster(), 'language': this.language(), 'vtt.js': this.options_['vtt.js'] }, this.options_[techName.toLowerCase()]); if (this.tag) { techOptions.tag = this.tag; } if (source) { this.currentType_ = source.type; if (source.src === this.cache_.src && this.cache_.currentTime > 0) { techOptions.startTime = this.cache_.currentTime; } this.cache_.src = source.src; } // Initialize tech instance var techComponent = _componentJs2['default'].getComponent(techName); this.tech = new techComponent(techOptions); _tracksTextTrackListConverterJs2['default'].jsonToTextTracks(this.textTracksJson_ || [], this.tech); this.on(this.tech, 'ready', this.handleTechReady); // Listen to every HTML5 events and trigger them back on the player for the plugins this.on(this.tech, 'loadstart', this.handleTechLoadStart); this.on(this.tech, 'waiting', this.handleTechWaiting); this.on(this.tech, 'canplay', this.handleTechCanPlay); this.on(this.tech, 'canplaythrough', this.handleTechCanPlayThrough); this.on(this.tech, 'playing', this.handleTechPlaying); this.on(this.tech, 'ended', this.handleTechEnded); this.on(this.tech, 'seeking', this.handleTechSeeking); this.on(this.tech, 'seeked', this.handleTechSeeked); this.on(this.tech, 'play', this.handleTechPlay); this.on(this.tech, 'firstplay', this.handleTechFirstPlay); this.on(this.tech, 'pause', this.handleTechPause); this.on(this.tech, 'progress', this.handleTechProgress); this.on(this.tech, 'durationchange', this.handleTechDurationChange); this.on(this.tech, 'fullscreenchange', this.handleTechFullscreenChange); this.on(this.tech, 'error', this.handleTechError); this.on(this.tech, 'suspend', this.handleTechSuspend); this.on(this.tech, 'abort', this.handleTechAbort); this.on(this.tech, 'emptied', this.handleTechEmptied); this.on(this.tech, 'stalled', this.handleTechStalled); this.on(this.tech, 'loadedmetadata', this.handleTechLoadedMetaData); this.on(this.tech, 'loadeddata', this.handleTechLoadedData); this.on(this.tech, 'timeupdate', this.handleTechTimeUpdate); this.on(this.tech, 'ratechange', this.handleTechRateChange); this.on(this.tech, 'volumechange', this.handleTechVolumeChange); this.on(this.tech, 'texttrackchange', this.onTextTrackChange); this.on(this.tech, 'loadedmetadata', this.updateStyleEl_); this.usingNativeControls(this.techGet('controls')); if (this.controls() && !this.usingNativeControls()) { this.addTechControlsListeners(); } // Add the tech element in the DOM if it was not already there // Make sure to not insert the original video element if using Html5 if (this.tech.el().parentNode !== this.el() && (techName !== 'Html5' || !this.tag)) { Dom.insertElFirst(this.tech.el(), this.el()); } // Get rid of the original video tag reference after the first tech is loaded if (this.tag) { this.tag.player = null; this.tag = null; } // player.triggerReady is always async, so don't need this to be async this.tech.ready(techReady, true); }; /** * Unload playback technology * * @method unloadTech */ Player.prototype.unloadTech = function unloadTech() { // Save the current text tracks so that we can reuse the same text tracks with the next tech this.textTracks_ = this.textTracks(); this.textTracksJson_ = _tracksTextTrackListConverterJs2['default'].textTracksToJson(this); this.isReady_ = false; this.tech.dispose(); this.tech = false; }; /** * Add playback technology listeners * * @method addTechControlsListeners */ Player.prototype.addTechControlsListeners = function addTechControlsListeners() { // Make sure to remove all the previous listeners in case we are called multiple times. this.removeTechControlsListeners(); // Some browsers (Chrome & IE) don't trigger a click on a flash swf, but do // trigger mousedown/up. // http://stackoverflow.com/questions/1444562/javascript-onclick-event-over-flash-object // Any touch events are set to block the mousedown event from happening this.on(this.tech, 'mousedown', this.handleTechClick); // If the controls were hidden we don't want that to change without a tap event // so we'll check if the controls were already showing before reporting user // activity this.on(this.tech, 'touchstart', this.handleTechTouchStart); this.on(this.tech, 'touchmove', this.handleTechTouchMove); this.on(this.tech, 'touchend', this.handleTechTouchEnd); // The tap listener needs to come after the touchend listener because the tap // listener cancels out any reportedUserActivity when setting userActive(false) this.on(this.tech, 'tap', this.handleTechTap); }; /** * Remove the listeners used for click and tap controls. This is needed for * toggling to controls disabled, where a tap/touch should do nothing. * * @method removeTechControlsListeners */ Player.prototype.removeTechControlsListeners = function removeTechControlsListeners() { // We don't want to just use `this.off()` because there might be other needed // listeners added by techs that extend this. this.off(this.tech, 'tap', this.handleTechTap); this.off(this.tech, 'touchstart', this.handleTechTouchStart); this.off(this.tech, 'touchmove', this.handleTechTouchMove); this.off(this.tech, 'touchend', this.handleTechTouchEnd); this.off(this.tech, 'mousedown', this.handleTechClick); }; /** * Player waits for the tech to be ready * * @private * @method handleTechReady */ Player.prototype.handleTechReady = function handleTechReady() { this.triggerReady(); // Keep the same volume as before if (this.cache_.volume) { this.techCall('setVolume', this.cache_.volume); } // Update the duration if available this.handleTechDurationChange(); // Chrome and Safari both have issues with autoplay. // In Safari (5.1.1), when we move the video element into the container div, autoplay doesn't work. // In Chrome (15), if you have autoplay + a poster + no controls, the video gets hidden (but audio plays) // This fixes both issues. Need to wait for API, so it updates displays correctly if (this.tag && this.options_.autoplay && this.paused()) { delete this.tag.poster; // Chrome Fix. Fixed in Chrome v16. this.play(); } }; /** * Fired when the user agent begins looking for media data * * @event loadstart */ Player.prototype.handleTechLoadStart = function handleTechLoadStart() { // TODO: Update to use `emptied` event instead. See #1277. this.removeClass('vjs-ended'); // reset the error state this.error(null); // If it's already playing we want to trigger a firstplay event now. // The firstplay event relies on both the play and loadstart events // which can happen in any order for a new source if (!this.paused()) { this.trigger('loadstart'); this.trigger('firstplay'); } else { // reset the hasStarted state this.hasStarted(false); this.trigger('loadstart'); } }; /** * Add/remove the vjs-has-started class * * @param {Boolean} hasStarted The value of true adds the class the value of false remove the class * @return {Boolean} Boolean value if has started * @method hasStarted */ Player.prototype.hasStarted = function hasStarted(_hasStarted) { if (_hasStarted !== undefined) { // only update if this is a new value if (this.hasStarted_ !== _hasStarted) { this.hasStarted_ = _hasStarted; if (_hasStarted) { this.addClass('vjs-has-started'); // trigger the firstplay event if this newly has played this.trigger('firstplay'); } else { this.removeClass('vjs-has-started'); } } return this; } return !!this.hasStarted_; }; /** * Fired whenever the media begins or resumes playback * * @event play */ Player.prototype.handleTechPlay = function handleTechPlay() { this.removeClass('vjs-ended'); this.removeClass('vjs-paused'); this.addClass('vjs-playing'); // hide the poster when the user hits play // https://html.spec.whatwg.org/multipage/embedded-content.html#dom-media-play this.hasStarted(true); this.trigger('play'); }; /** * Fired whenever the media begins waiting * * @event waiting */ Player.prototype.handleTechWaiting = function handleTechWaiting() { this.addClass('vjs-waiting'); this.trigger('waiting'); }; /** * A handler for events that signal that waiting has ended * which is not consistent between browsers. See #1351 * * @event canplay */ Player.prototype.handleTechCanPlay = function handleTechCanPlay() { this.removeClass('vjs-waiting'); this.trigger('canplay'); }; /** * A handler for events that signal that waiting has ended * which is not consistent between browsers. See #1351 * * @event canplaythrough */ Player.prototype.handleTechCanPlayThrough = function handleTechCanPlayThrough() { this.removeClass('vjs-waiting'); this.trigger('canplaythrough'); }; /** * A handler for events that signal that waiting has ended * which is not consistent between browsers. See #1351 * * @event playing */ Player.prototype.handleTechPlaying = function handleTechPlaying() { this.removeClass('vjs-waiting'); this.trigger('playing'); }; /** * Fired whenever the player is jumping to a new time * * @event seeking */ Player.prototype.handleTechSeeking = function handleTechSeeking() { this.addClass('vjs-seeking'); this.trigger('seeking'); }; /** * Fired when the player has finished jumping to a new time * * @event seeked */ Player.prototype.handleTechSeeked = function handleTechSeeked() { this.removeClass('vjs-seeking'); this.trigger('seeked'); }; /** * Fired the first time a video is played * Not part of the HLS spec, and we're not sure if this is the best * implementation yet, so use sparingly. If you don't have a reason to * prevent playback, use `myPlayer.one('play');` instead. * * @event firstplay */ Player.prototype.handleTechFirstPlay = function handleTechFirstPlay() { //If the first starttime attribute is specified //then we will start at the given offset in seconds if (this.options_.starttime) { this.currentTime(this.options_.starttime); } this.addClass('vjs-has-started'); this.trigger('firstplay'); }; /** * Fired whenever the media has been paused * * @event pause */ Player.prototype.handleTechPause = function handleTechPause() { this.removeClass('vjs-playing'); this.addClass('vjs-paused'); this.trigger('pause'); }; /** * Fired while the user agent is downloading media data * * @event progress */ Player.prototype.handleTechProgress = function handleTechProgress() { this.trigger('progress'); // Add custom event for when source is finished downloading. if (this.bufferedPercent() === 1) { this.trigger('loadedalldata'); } }; /** * Fired when the end of the media resource is reached (currentTime == duration) * * @event ended */ Player.prototype.handleTechEnded = function handleTechEnded() { this.addClass('vjs-ended'); if (this.options_.loop) { this.currentTime(0); this.play(); } else if (!this.paused()) { this.pause(); } this.trigger('ended'); }; /** * Fired when the duration of the media resource is first known or changed * * @event durationchange */ Player.prototype.handleTechDurationChange = function handleTechDurationChange() { this.duration(this.techGet('duration')); }; /** * Handle a click on the media element to play/pause * * @param {Object=} event Event object * @method handleTechClick */ Player.prototype.handleTechClick = function handleTechClick(event) { // We're using mousedown to detect clicks thanks to Flash, but mousedown // will also be triggered with right-clicks, so we need to prevent that if (event.button !== 0) return; // When controls are disabled a click should not toggle playback because // the click is considered a control if (this.controls()) { if (this.paused()) { this.play(); } else { this.pause(); } } }; /** * Handle a tap on the media element. It will toggle the user * activity state, which hides and shows the controls. * * @method handleTechTap */ Player.prototype.handleTechTap = function handleTechTap() { this.userActive(!this.userActive()); }; /** * Handle touch to start * * @method handleTechTouchStart */ Player.prototype.handleTechTouchStart = function handleTechTouchStart() { this.userWasActive = this.userActive(); }; /** * Handle touch to move * * @method handleTechTouchMove */ Player.prototype.handleTechTouchMove = function handleTechTouchMove() { if (this.userWasActive) { this.reportUserActivity(); } }; /** * Handle touch to end * * @method handleTechTouchEnd */ Player.prototype.handleTechTouchEnd = function handleTechTouchEnd(event) { // Stop the mouse events from also happening event.preventDefault(); }; /** * Fired when the player switches in or out of fullscreen mode * * @event fullscreenchange */ Player.prototype.handleFullscreenChange = function handleFullscreenChange() { if (this.isFullscreen()) { this.addClass('vjs-fullscreen'); } else { this.removeClass('vjs-fullscreen'); } }; /** * native click events on the SWF aren't triggered on IE11, Win8.1RT * use stageclick events triggered from inside the SWF instead * * @private * @method handleStageClick */ Player.prototype.handleStageClick = function handleStageClick() { this.reportUserActivity(); }; /** * Handle Tech Fullscreen Change * * @method handleTechFullscreenChange */ Player.prototype.handleTechFullscreenChange = function handleTechFullscreenChange(event, data) { if (data) { this.isFullscreen(data.isFullscreen); } this.trigger('fullscreenchange'); }; /** * Fires when an error occurred during the loading of an audio/video * * @event error */ Player.prototype.handleTechError = function handleTechError() { var error = this.tech.error(); this.error(error && error.code); }; /** * Fires when the browser is intentionally not getting media data * * @event suspend */ Player.prototype.handleTechSuspend = function handleTechSuspend() { this.trigger('suspend'); }; /** * Fires when the loading of an audio/video is aborted * * @event abort */ Player.prototype.handleTechAbort = function handleTechAbort() { this.trigger('abort'); }; /** * Fires when the current playlist is empty * * @event emptied */ Player.prototype.handleTechEmptied = function handleTechEmptied() { this.trigger('emptied'); }; /** * Fires when the browser is trying to get media data, but data is not available * * @event stalled */ Player.prototype.handleTechStalled = function handleTechStalled() { this.trigger('stalled'); }; /** * Fires when the browser has loaded meta data for the audio/video * * @event loadedmetadata */ Player.prototype.handleTechLoadedMetaData = function handleTechLoadedMetaData() { this.trigger('loadedmetadata'); }; /** * Fires when the browser has loaded the current frame of the audio/video * * @event loaddata */ Player.prototype.handleTechLoadedData = function handleTechLoadedData() { this.trigger('loadeddata'); }; /** * Fires when the current playback position has changed * * @event timeupdate */ Player.prototype.handleTechTimeUpdate = function handleTechTimeUpdate() { this.trigger('timeupdate'); }; /** * Fires when the playing speed of the audio/video is changed * * @event ratechange */ Player.prototype.handleTechRateChange = function handleTechRateChange() { this.trigger('ratechange'); }; /** * Fires when the volume has been changed * * @event volumechange */ Player.prototype.handleTechVolumeChange = function handleTechVolumeChange() { this.trigger('volumechange'); }; /** * Fires when the text track has been changed * * @event texttrackchange */ Player.prototype.onTextTrackChange = function onTextTrackChange() { this.trigger('texttrackchange'); }; /** * Get object for cached values. * * @return {Object} * @method getCache */ Player.prototype.getCache = function getCache() { return this.cache_; }; /** * Pass values to the playback tech * * @param {String=} method Method * @param {Object=} arg Argument * @method techCall */ Player.prototype.techCall = function techCall(method, arg) { // If it's not ready yet, call method when it is if (this.tech && !this.tech.isReady_) { this.tech.ready(function () { this[method](arg); }, true); // Otherwise call method now } else { try { this.tech[method](arg); } catch (e) { _utilsLogJs2['default'](e); throw e; } } }; /** * Get calls can't wait for the tech, and sometimes don't need to. * * @param {String} method Tech method * @return {Method} * @method techGet */ Player.prototype.techGet = function techGet(method) { if (this.tech && this.tech.isReady_) { // Flash likes to die and reload when you hide or reposition it. // In these cases the object methods go away and we get errors. // When that happens we'll catch the errors and inform tech that it's not ready any more. try { return this.tech[method](); } catch (e) { // When building additional tech libs, an expected method may not be defined yet if (this.tech[method] === undefined) { _utilsLogJs2['default']('Video.js: ' + method + ' method not defined for ' + this.techName + ' playback technology.', e); } else { // When a method isn't available on the object it throws a TypeError if (e.name === 'TypeError') { _utilsLogJs2['default']('Video.js: ' + method + ' unavailable on ' + this.techName + ' playback technology element.', e); this.tech.isReady_ = false; } else { _utilsLogJs2['default'](e); } } throw e; } } return; }; /** * start media playback * ```js * myPlayer.play(); * ``` * * @return {Player} self * @method play */ Player.prototype.play = function play() { this.techCall('play'); return this; }; /** * Pause the video playback * ```js * myPlayer.pause(); * ``` * * @return {Player} self * @method pause */ Player.prototype.pause = function pause() { this.techCall('pause'); return this; }; /** * Check if the player is paused * ```js * var isPaused = myPlayer.paused(); * var isPlaying = !myPlayer.paused(); * ``` * * @return {Boolean} false if the media is currently playing, or true otherwise * @method paused */ Player.prototype.paused = function paused() { // The initial state of paused should be true (in Safari it's actually false) return this.techGet('paused') === false ? false : true; }; /** * Returns whether or not the user is "scrubbing". Scrubbing is when the user * has clicked the progress bar handle and is dragging it along the progress bar. * * @param {Boolean} isScrubbing True/false the user is scrubbing * @return {Boolean} The scrubbing status when getting * @return {Object} The player when setting * @method scrubbing */ Player.prototype.scrubbing = function scrubbing(isScrubbing) { if (isScrubbing !== undefined) { this.scrubbing_ = !!isScrubbing; if (isScrubbing) { this.addClass('vjs-scrubbing'); } else { this.removeClass('vjs-scrubbing'); } return this; } return this.scrubbing_; }; /** * Get or set the current time (in seconds) * ```js * // get * var whereYouAt = myPlayer.currentTime(); * // set * myPlayer.currentTime(120); // 2 minutes into the video * ``` * * @param {Number|String=} seconds The time to seek to * @return {Number} The time in seconds, when not setting * @return {Player} self, when the current time is set * @method currentTime */ Player.prototype.currentTime = function currentTime(seconds) { if (seconds !== undefined) { this.techCall('setCurrentTime', seconds); return this; } // cache last currentTime and return. default to 0 seconds // // Caching the currentTime is meant to prevent a massive amount of reads on the tech's // currentTime when scrubbing, but may not provide much performance benefit afterall. // Should be tested. Also something has to read the actual current time or the cache will // never get updated. return this.cache_.currentTime = this.techGet('currentTime') || 0; }; /** * Get the length in time of the video in seconds * ```js * var lengthOfVideo = myPlayer.duration(); * ``` * **NOTE**: The video must have started loading before the duration can be * known, and in the case of Flash, may not be known until the video starts * playing. * * @param {Number} seconds Duration when setting * @return {Number} The duration of the video in seconds when getting * @method duration */ Player.prototype.duration = function duration(seconds) { if (seconds === undefined) { return this.cache_.duration || 0; } seconds = parseFloat(seconds) || 0; // Standardize on Inifity for signaling video is live if (seconds < 0) { seconds = Infinity; } if (seconds !== this.cache_.duration) { // Cache the last set value for optimized scrubbing (esp. Flash) this.cache_.duration = seconds; if (seconds === Infinity) { this.addClass('vjs-live'); } else { this.removeClass('vjs-live'); } this.trigger('durationchange'); } return this; }; /** * Calculates how much time is left. * ```js * var timeLeft = myPlayer.remainingTime(); * ``` * Not a native video element function, but useful * * @return {Number} The time remaining in seconds * @method remainingTime */ Player.prototype.remainingTime = function remainingTime() { return this.duration() - this.currentTime(); }; // http://dev.w3.org/html5/spec/video.html#dom-media-buffered // Buffered returns a timerange object. // Kind of like an array of portions of the video that have been downloaded. /** * Get a TimeRange object with the times of the video that have been downloaded * If you just want the percent of the video that's been downloaded, * use bufferedPercent. * ```js * // Number of different ranges of time have been buffered. Usually 1. * numberOfRanges = bufferedTimeRange.length, * // Time in seconds when the first range starts. Usually 0. * firstRangeStart = bufferedTimeRange.start(0), * // Time in seconds when the first range ends * firstRangeEnd = bufferedTimeRange.end(0), * // Length in seconds of the first time range * firstRangeLength = firstRangeEnd - firstRangeStart; * ``` * * @return {Object} A mock TimeRange object (following HTML spec) * @method buffered */ Player.prototype.buffered = function buffered() { var buffered = this.techGet('buffered'); if (!buffered || !buffered.length) { buffered = _utilsTimeRangesJs.createTimeRange(0, 0); } return buffered; }; /** * Get the percent (as a decimal) of the video that's been downloaded * ```js * var howMuchIsDownloaded = myPlayer.bufferedPercent(); * ``` * 0 means none, 1 means all. * (This method isn't in the HTML5 spec, but it's very convenient) * * @return {Number} A decimal between 0 and 1 representing the percent * @method bufferedPercent */ Player.prototype.bufferedPercent = function bufferedPercent() { return _utilsBufferJs.bufferedPercent(this.buffered(), this.duration()); }; /** * Get the ending time of the last buffered time range * This is used in the progress bar to encapsulate all time ranges. * * @return {Number} The end of the last buffered time range * @method bufferedEnd */ Player.prototype.bufferedEnd = function bufferedEnd() { var buffered = this.buffered(), duration = this.duration(), end = buffered.end(buffered.length - 1); if (end > duration) { end = duration; } return end; }; /** * Get or set the current volume of the media * ```js * // get * var howLoudIsIt = myPlayer.volume(); * // set * myPlayer.volume(0.5); // Set volume to half * ``` * 0 is off (muted), 1.0 is all the way up, 0.5 is half way. * * @param {Number} percentAsDecimal The new volume as a decimal percent * @return {Number} The current volume when getting * @return {Player} self when setting * @method volume */ Player.prototype.volume = function volume(percentAsDecimal) { var vol = undefined; if (percentAsDecimal !== undefined) { vol = Math.max(0, Math.min(1, parseFloat(percentAsDecimal))); // Force value to between 0 and 1 this.cache_.volume = vol; this.techCall('setVolume', vol); return this; } // Default to 1 when returning current volume. vol = parseFloat(this.techGet('volume')); return isNaN(vol) ? 1 : vol; }; /** * Get the current muted state, or turn mute on or off * ```js * // get * var isVolumeMuted = myPlayer.muted(); * // set * myPlayer.muted(true); // mute the volume * ``` * * @param {Boolean=} muted True to mute, false to unmute * @return {Boolean} True if mute is on, false if not when getting * @return {Player} self when setting mute * @method muted */ Player.prototype.muted = function muted(_muted) { if (_muted !== undefined) { this.techCall('setMuted', _muted); return this; } return this.techGet('muted') || false; // Default to false }; // Check if current tech can support native fullscreen // (e.g. with built in controls like iOS, so not our flash swf) /** * Check to see if fullscreen is supported * * @return {Boolean} * @method supportsFullScreen */ Player.prototype.supportsFullScreen = function supportsFullScreen() { return this.techGet('supportsFullScreen') || false; }; /** * Check if the player is in fullscreen mode * ```js * // get * var fullscreenOrNot = myPlayer.isFullscreen(); * // set * myPlayer.isFullscreen(true); // tell the player it's in fullscreen * ``` * NOTE: As of the latest HTML5 spec, isFullscreen is no longer an official * property and instead document.fullscreenElement is used. But isFullscreen is * still a valuable property for internal player workings. * * @param {Boolean=} isFS Update the player's fullscreen state * @return {Boolean} true if fullscreen false if not when getting * @return {Player} self when setting * @method isFullscreen */ Player.prototype.isFullscreen = function isFullscreen(isFS) { if (isFS !== undefined) { this.isFullscreen_ = !!isFS; return this; } return !!this.isFullscreen_; }; /** * Increase the size of the video to full screen * ```js * myPlayer.requestFullscreen(); * ``` * In some browsers, full screen is not supported natively, so it enters * "full window mode", where the video fills the browser window. * In browsers and devices that support native full screen, sometimes the * browser's default controls will be shown, and not the Video.js custom skin. * This includes most mobile devices (iOS, Android) and older versions of * Safari. * * @return {Player} self * @method requestFullscreen */ Player.prototype.requestFullscreen = function requestFullscreen() { var fsApi = _fullscreenApiJs2['default']; this.isFullscreen(true); if (fsApi.requestFullscreen) { // the browser supports going fullscreen at the element level so we can // take the controls fullscreen as well as the video // Trigger fullscreenchange event after change // We have to specifically add this each time, and remove // when canceling fullscreen. Otherwise if there's multiple // players on a page, they would all be reacting to the same fullscreen // events Events.on(_globalDocument2['default'], fsApi.fullscreenchange, Fn.bind(this, function documentFullscreenChange(e) { this.isFullscreen(_globalDocument2['default'][fsApi.fullscreenElement]); // If cancelling fullscreen, remove event listener. if (this.isFullscreen() === false) { Events.off(_globalDocument2['default'], fsApi.fullscreenchange, documentFullscreenChange); } this.trigger('fullscreenchange'); })); this.el_[fsApi.requestFullscreen](); } else if (this.tech.supportsFullScreen()) { // we can't take the video.js controls fullscreen but we can go fullscreen // with native controls this.techCall('enterFullScreen'); } else { // fullscreen isn't supported so we'll just stretch the video element to // fill the viewport this.enterFullWindow(); this.trigger('fullscreenchange'); } return this; }; /** * Return the video to its normal size after having been in full screen mode * ```js * myPlayer.exitFullscreen(); * ``` * * @return {Player} self * @method exitFullscreen */ Player.prototype.exitFullscreen = function exitFullscreen() { var fsApi = _fullscreenApiJs2['default']; this.isFullscreen(false); // Check for browser element fullscreen support if (fsApi.requestFullscreen) { _globalDocument2['default'][fsApi.exitFullscreen](); } else if (this.tech.supportsFullScreen()) { this.techCall('exitFullScreen'); } else { this.exitFullWindow(); this.trigger('fullscreenchange'); } return this; }; /** * When fullscreen isn't supported we can stretch the video container to as wide as the browser will let us. * * @method enterFullWindow */ Player.prototype.enterFullWindow = function enterFullWindow() { this.isFullWindow = true; // Storing original doc overflow value to return to when fullscreen is off this.docOrigOverflow = _globalDocument2['default'].documentElement.style.overflow; // Add listener for esc key to exit fullscreen Events.on(_globalDocument2['default'], 'keydown', Fn.bind(this, this.fullWindowOnEscKey)); // Hide any scroll bars _globalDocument2['default'].documentElement.style.overflow = 'hidden'; // Apply fullscreen styles Dom.addElClass(_globalDocument2['default'].body, 'vjs-full-window'); this.trigger('enterFullWindow'); }; /** * Check for call to either exit full window or full screen on ESC key * * @param {String} event Event to check for key press * @method fullWindowOnEscKey */ Player.prototype.fullWindowOnEscKey = function fullWindowOnEscKey(event) { if (event.keyCode === 27) { if (this.isFullscreen() === true) { this.exitFullscreen(); } else { this.exitFullWindow(); } } }; /** * Exit full window * * @method exitFullWindow */ Player.prototype.exitFullWindow = function exitFullWindow() { this.isFullWindow = false; Events.off(_globalDocument2['default'], 'keydown', this.fullWindowOnEscKey); // Unhide scroll bars. _globalDocument2['default'].documentElement.style.overflow = this.docOrigOverflow; // Remove fullscreen styles Dom.removeElClass(_globalDocument2['default'].body, 'vjs-full-window'); // Resize the box, controller, and poster to original sizes // this.positionAll(); this.trigger('exitFullWindow'); }; /** * Select source based on tech order * * @param {Array} sources The sources for a media asset * @return {Object|Boolean} Object of source and tech order, otherwise false * @method selectSource */ Player.prototype.selectSource = function selectSource(sources) { // Loop through each playback technology in the options order for (var i = 0, j = this.options_.techOrder; i < j.length; i++) { var techName = _utilsToTitleCaseJs2['default'](j[i]); var tech = _componentJs2['default'].getComponent(techName); // Check if the current tech is defined before continuing if (!tech) { _utilsLogJs2['default'].error('The "' + techName + '" tech is undefined. Skipped browser support check for that tech.'); continue; } // Check if the browser supports this technology if (tech.isSupported()) { // Loop through each source object for (var a = 0, b = sources; a < b.length; a++) { var source = b[a]; // Check if source can be played with this technology if (tech.canPlaySource(source)) { return { source: source, tech: techName }; } } } } return false; }; /** * The source function updates the video source * There are three types of variables you can pass as the argument. * **URL String**: A URL to the the video file. Use this method if you are sure * the current playback technology (HTML5/Flash) can support the source you * provide. Currently only MP4 files can be used in both HTML5 and Flash. * ```js * myPlayer.src("http://www.example.com/path/to/video.mp4"); * ``` * **Source Object (or element):* * A javascript object containing information * about the source file. Use this method if you want the player to determine if * it can support the file using the type information. * ```js * myPlayer.src({ type: "video/mp4", src: "http://www.example.com/path/to/video.mp4" }); * ``` * **Array of Source Objects:* * To provide multiple versions of the source so * that it can be played using HTML5 across browsers you can use an array of * source objects. Video.js will detect which version is supported and load that * file. * ```js * myPlayer.src([ * { type: "video/mp4", src: "http://www.example.com/path/to/video.mp4" }, * { type: "video/webm", src: "http://www.example.com/path/to/video.webm" }, * { type: "video/ogg", src: "http://www.example.com/path/to/video.ogv" } * ]); * ``` * * @param {String|Object|Array=} source The source URL, object, or array of sources * @return {String} The current video source when getting * @return {String} The player when setting * @method src */ Player.prototype.src = function src(source) { if (source === undefined) { return this.techGet('src'); } var currentTech = _componentJs2['default'].getComponent(this.techName); // case: Array of source objects to choose from and pick the best to play if (Array.isArray(source)) { this.sourceList_(source); // case: URL String (http://myvideo...) } else if (typeof source === 'string') { // create a source object from the string this.src({ src: source }); // case: Source object { src: '', type: '' ... } } else if (source instanceof Object) { // check if the source has a type and the loaded tech cannot play the source // if there's no type we'll just try the current tech if (source.type && !currentTech.canPlaySource(source)) { // create a source list with the current source and send through // the tech loop to check for a compatible technology this.sourceList_([source]); } else { this.cache_.src = source.src; this.currentType_ = source.type || ''; // wait until the tech is ready to set the source this.ready(function () { // The setSource tech method was added with source handlers // so older techs won't support it // We need to check the direct prototype for the case where subclasses // of the tech do not support source handlers if (currentTech.prototype.hasOwnProperty('setSource')) { this.techCall('setSource', source); } else { this.techCall('src', source.src); } if (this.options_.preload === 'auto') { this.load(); } if (this.options_.autoplay) { this.play(); } // Set the source synchronously if possible (#2326) }, true); } } return this; }; /** * Handle an array of source objects * * @param {Array} sources Array of source objects * @private * @method sourceList_ */ Player.prototype.sourceList_ = function sourceList_(sources) { var sourceTech = this.selectSource(sources); if (sourceTech) { if (sourceTech.tech === this.techName) { // if this technology is already loaded, set the source this.src(sourceTech.source); } else { // load this technology with the chosen source this.loadTech(sourceTech.tech, sourceTech.source); } } else { // We need to wrap this in a timeout to give folks a chance to add error event handlers this.setTimeout(function () { this.error({ code: 4, message: this.localize(this.options_.notSupportedMessage) }); }, 0); // we could not find an appropriate tech, but let's still notify the delegate that this is it // this needs a better comment about why this is needed this.triggerReady(); } }; /** * Begin loading the src data. * * @return {Player} Returns the player * @method load */ Player.prototype.load = function load() { this.techCall('load'); return this; }; /** * Returns the fully qualified URL of the current source value e.g. http://mysite.com/video.mp4 * Can be used in conjuction with `currentType` to assist in rebuilding the current source object. * * @return {String} The current source * @method currentSrc */ Player.prototype.currentSrc = function currentSrc() { return this.techGet('currentSrc') || this.cache_.src || ''; }; /** * Get the current source type e.g. video/mp4 * This can allow you rebuild the current source object so that you could load the same * source and tech later * * @return {String} The source MIME type * @method currentType */ Player.prototype.currentType = function currentType() { return this.currentType_ || ''; }; /** * Get or set the preload attribute * * @param {Boolean} value Boolean to determine if preload should be used * @return {String} The preload attribute value when getting * @return {Player} Returns the player when setting * @method preload */ Player.prototype.preload = function preload(value) { if (value !== undefined) { this.techCall('setPreload', value); this.options_.preload = value; return this; } return this.techGet('preload'); }; /** * Get or set the autoplay attribute. * * @param {Boolean} value Boolean to determine if preload should be used * @return {String} The autoplay attribute value when getting * @return {Player} Returns the player when setting * @method autoplay */ Player.prototype.autoplay = function autoplay(value) { if (value !== undefined) { this.techCall('setAutoplay', value); this.options_.autoplay = value; return this; } return this.techGet('autoplay', value); }; /** * Get or set the loop attribute on the video element. * * @param {Boolean} value Boolean to determine if preload should be used * @return {String} The loop attribute value when getting * @return {Player} Returns the player when setting * @method loop */ Player.prototype.loop = function loop(value) { if (value !== undefined) { this.techCall('setLoop', value); this.options_['loop'] = value; return this; } return this.techGet('loop'); }; /** * get or set the poster image source url * ##### EXAMPLE: * ```js * // get * var currentPoster = myPlayer.poster(); * // set * myPlayer.poster('http://example.com/myImage.jpg'); * ``` * * @param {String=} src Poster image source URL * @return {String} poster URL when getting * @return {Player} self when setting * @method poster */ Player.prototype.poster = function poster(src) { if (src === undefined) { return this.poster_; } // The correct way to remove a poster is to set as an empty string // other falsey values will throw errors if (!src) { src = ''; } // update the internal poster variable this.poster_ = src; // update the tech's poster this.techCall('setPoster', src); // alert components that the poster has been set this.trigger('posterchange'); return this; }; /** * Get or set whether or not the controls are showing. * * @param {Boolean} bool Set controls to showing or not * @return {Boolean} Controls are showing * @method controls */ Player.prototype.controls = function controls(bool) { if (bool !== undefined) { bool = !!bool; // force boolean // Don't trigger a change event unless it actually changed if (this.controls_ !== bool) { this.controls_ = bool; if (this.usingNativeControls()) { this.techCall('setControls', bool); } if (bool) { this.removeClass('vjs-controls-disabled'); this.addClass('vjs-controls-enabled'); this.trigger('controlsenabled'); if (!this.usingNativeControls()) { this.addTechControlsListeners(); } } else { this.removeClass('vjs-controls-enabled'); this.addClass('vjs-controls-disabled'); this.trigger('controlsdisabled'); if (!this.usingNativeControls()) { this.removeTechControlsListeners(); } } } return this; } return !!this.controls_; }; /** * Toggle native controls on/off. Native controls are the controls built into * devices (e.g. default iPhone controls), Flash, or other techs * (e.g. Vimeo Controls) * **This should only be set by the current tech, because only the tech knows * if it can support native controls** * * @param {Boolean} bool True signals that native controls are on * @return {Player} Returns the player * @private * @method usingNativeControls */ Player.prototype.usingNativeControls = function usingNativeControls(bool) { if (bool !== undefined) { bool = !!bool; // force boolean // Don't trigger a change event unless it actually changed if (this.usingNativeControls_ !== bool) { this.usingNativeControls_ = bool; if (bool) { this.addClass('vjs-using-native-controls'); /** * player is using the native device controls * * @event usingnativecontrols * @memberof Player * @instance * @private */ this.trigger('usingnativecontrols'); } else { this.removeClass('vjs-using-native-controls'); /** * player is using the custom HTML controls * * @event usingcustomcontrols * @memberof Player * @instance * @private */ this.trigger('usingcustomcontrols'); } } return this; } return !!this.usingNativeControls_; }; /** * Set or get the current MediaError * * @param {*} err A MediaError or a String/Number to be turned into a MediaError * @return {MediaError|null} when getting * @return {Player} when setting * @method error */ Player.prototype.error = function error(err) { if (err === undefined) { return this.error_ || null; } // restoring to default if (err === null) { this.error_ = err; this.removeClass('vjs-error'); return this; } // error instance if (err instanceof _mediaErrorJs2['default']) { this.error_ = err; } else { this.error_ = new _mediaErrorJs2['default'](err); } // fire an error event on the player this.trigger('error'); // add the vjs-error classname to the player this.addClass('vjs-error'); // log the name of the error type and any message // ie8 just logs "[object object]" if you just log the error object _utilsLogJs2['default'].error('(CODE:' + this.error_.code + ' ' + _mediaErrorJs2['default'].errorTypes[this.error_.code] + ')', this.error_.message, this.error_); return this; }; /** * Returns whether or not the player is in the "ended" state. * * @return {Boolean} True if the player is in the ended state, false if not. * @method ended */ Player.prototype.ended = function ended() { return this.techGet('ended'); }; /** * Returns whether or not the player is in the "seeking" state. * * @return {Boolean} True if the player is in the seeking state, false if not. * @method seeking */ Player.prototype.seeking = function seeking() { return this.techGet('seeking'); }; /** * Returns the TimeRanges of the media that are currently available * for seeking to. * * @return {TimeRanges} the seekable intervals of the media timeline * @method seekable */ Player.prototype.seekable = function seekable() { return this.techGet('seekable'); }; /** * Report user activity * * @param {Object} event Event object * @method reportUserActivity */ Player.prototype.reportUserActivity = function reportUserActivity(event) { this.userActivity_ = true; }; /** * Get/set if user is active * * @param {Boolean} bool Value when setting * @return {Boolean} Value if user is active user when getting * @method userActive */ Player.prototype.userActive = function userActive(bool) { if (bool !== undefined) { bool = !!bool; if (bool !== this.userActive_) { this.userActive_ = bool; if (bool) { // If the user was inactive and is now active we want to reset the // inactivity timer this.userActivity_ = true; this.removeClass('vjs-user-inactive'); this.addClass('vjs-user-active'); this.trigger('useractive'); } else { // We're switching the state to inactive manually, so erase any other // activity this.userActivity_ = false; // Chrome/Safari/IE have bugs where when you change the cursor it can // trigger a mousemove event. This causes an issue when you're hiding // the cursor when the user is inactive, and a mousemove signals user // activity. Making it impossible to go into inactive mode. Specifically // this happens in fullscreen when we really need to hide the cursor. // // When this gets resolved in ALL browsers it can be removed // https://code.google.com/p/chromium/issues/detail?id=103041 if (this.tech) { this.tech.one('mousemove', function (e) { e.stopPropagation(); e.preventDefault(); }); } this.removeClass('vjs-user-active'); this.addClass('vjs-user-inactive'); this.trigger('userinactive'); } } return this; } return this.userActive_; }; /** * Listen for user activity based on timeout value * * @method listenForUserActivity */ Player.prototype.listenForUserActivity = function listenForUserActivity() { var mouseInProgress = undefined, lastMoveX = undefined, lastMoveY = undefined; var handleActivity = Fn.bind(this, this.reportUserActivity); var handleMouseMove = function handleMouseMove(e) { // #1068 - Prevent mousemove spamming // Chrome Bug: https://code.google.com/p/chromium/issues/detail?id=366970 if (e.screenX !== lastMoveX || e.screenY !== lastMoveY) { lastMoveX = e.screenX; lastMoveY = e.screenY; handleActivity(); } }; var handleMouseDown = function handleMouseDown() { handleActivity(); // For as long as the they are touching the device or have their mouse down, // we consider them active even if they're not moving their finger or mouse. // So we want to continue to update that they are active this.clearInterval(mouseInProgress); // Setting userActivity=true now and setting the interval to the same time // as the activityCheck interval (250) should ensure we never miss the // next activityCheck mouseInProgress = this.setInterval(handleActivity, 250); }; var handleMouseUp = function handleMouseUp(event) { handleActivity(); // Stop the interval that maintains activity if the mouse/touch is down this.clearInterval(mouseInProgress); }; // Any mouse movement will be considered user activity this.on('mousedown', handleMouseDown); this.on('mousemove', handleMouseMove); this.on('mouseup', handleMouseUp); // Listen for keyboard navigation // Shouldn't need to use inProgress interval because of key repeat this.on('keydown', handleActivity); this.on('keyup', handleActivity); // Run an interval every 250 milliseconds instead of stuffing everything into // the mousemove/touchmove function itself, to prevent performance degradation. // `this.reportUserActivity` simply sets this.userActivity_ to true, which // then gets picked up by this loop // http://ejohn.org/blog/learning-from-twitter/ var inactivityTimeout = undefined; var activityCheck = this.setInterval(function () { // Check to see if mouse/touch activity has happened if (this.userActivity_) { // Reset the activity tracker this.userActivity_ = false; // If the user state was inactive, set the state to active this.userActive(true); // Clear any existing inactivity timeout to start the timer over this.clearTimeout(inactivityTimeout); var timeout = this.options_['inactivityTimeout']; if (timeout > 0) { // In <timeout> milliseconds, if no more activity has occurred the // user will be considered inactive inactivityTimeout = this.setTimeout(function () { // Protect against the case where the inactivityTimeout can trigger just // before the next user activity is picked up by the activityCheck loop // causing a flicker if (!this.userActivity_) { this.userActive(false); } }, timeout); } } }, 250); }; /** * Gets or sets the current playback rate. A playback rate of * 1.0 represents normal speed and 0.5 would indicate half-speed * playback, for instance. * @see https://html.spec.whatwg.org/multipage/embedded-content.html#dom-media-playbackrate * * @param {Number} rate New playback rate to set. * @return {Number} Returns the new playback rate when setting * @return {Number} Returns the current playback rate when getting * @method playbackRate */ Player.prototype.playbackRate = function playbackRate(rate) { if (rate !== undefined) { this.techCall('setPlaybackRate', rate); return this; } if (this.tech && this.tech['featuresPlaybackRate']) { return this.techGet('playbackRate'); } else { return 1.0; } }; /** * Gets or sets the audio flag * * @param {Boolean} bool True signals that this is an audio player. * @return {Boolean} Returns true if player is audio, false if not when getting * @return {Player} Returns the player if setting * @private * @method isAudio */ Player.prototype.isAudio = function isAudio(bool) { if (bool !== undefined) { this.isAudio_ = !!bool; return this; } return !!this.isAudio_; }; /** * Returns the current state of network activity for the element, from * the codes in the list below. * - NETWORK_EMPTY (numeric value 0) * The element has not yet been initialised. All attributes are in * their initial states. * - NETWORK_IDLE (numeric value 1) * The element's resource selection algorithm is active and has * selected a resource, but it is not actually using the network at * this time. * - NETWORK_LOADING (numeric value 2) * The user agent is actively trying to download data. * - NETWORK_NO_SOURCE (numeric value 3) * The element's resource selection algorithm is active, but it has * not yet found a resource to use. * * @see https://html.spec.whatwg.org/multipage/embedded-content.html#network-states * @return {Number} the current network activity state * @method networkState */ Player.prototype.networkState = function networkState() { return this.techGet('networkState'); }; /** * Returns a value that expresses the current state of the element * with respect to rendering the current playback position, from the * codes in the list below. * - HAVE_NOTHING (numeric value 0) * No information regarding the media resource is available. * - HAVE_METADATA (numeric value 1) * Enough of the resource has been obtained that the duration of the * resource is available. * - HAVE_CURRENT_DATA (numeric value 2) * Data for the immediate current playback position is available. * - HAVE_FUTURE_DATA (numeric value 3) * Data for the immediate current playback position is available, as * well as enough data for the user agent to advance the current * playback position in the direction of playback. * - HAVE_ENOUGH_DATA (numeric value 4) * The user agent estimates that enough data is available for * playback to proceed uninterrupted. * * @see https://html.spec.whatwg.org/multipage/embedded-content.html#dom-media-readystate * @return {Number} the current playback rendering state * @method readyState */ Player.prototype.readyState = function readyState() { return this.techGet('readyState'); }; /* * Text tracks are tracks of timed text events. * Captions - text displayed over the video for the hearing impaired * Subtitles - text displayed over the video for those who don't understand language in the video * Chapters - text displayed in a menu allowing the user to jump to particular points (chapters) in the video * Descriptions (not supported yet) - audio descriptions that are read back to the user by a screen reading device */ /** * Get an array of associated text tracks. captions, subtitles, chapters, descriptions * http://www.w3.org/html/wg/drafts/html/master/embedded-content-0.html#dom-media-texttracks * * @return {Array} Array of track objects * @method textTracks */ Player.prototype.textTracks = function textTracks() { // cannot use techGet directly because it checks to see whether the tech is ready. // Flash is unlikely to be ready in time but textTracks should still work. return this.tech && this.tech['textTracks'](); }; /** * Get an array of remote text tracks * * @return {Array} * @method remoteTextTracks */ Player.prototype.remoteTextTracks = function remoteTextTracks() { return this.tech && this.tech['remoteTextTracks'](); }; /** * Add a text track * In addition to the W3C settings we allow adding additional info through options. * http://www.w3.org/html/wg/drafts/html/master/embedded-content-0.html#dom-media-addtexttrack * * @param {String} kind Captions, subtitles, chapters, descriptions, or metadata * @param {String=} label Optional label * @param {String=} language Optional language * @method addTextTrack */ Player.prototype.addTextTrack = function addTextTrack(kind, label, language) { return this.tech && this.tech['addTextTrack'](kind, label, language); }; /** * Add a remote text track * * @param {Object} options Options for remote text track * @method addRemoteTextTrack */ Player.prototype.addRemoteTextTrack = function addRemoteTextTrack(options) { return this.tech && this.tech['addRemoteTextTrack'](options); }; /** * Remove a remote text track * * @param {Object} track Remote text track to remove * @method removeRemoteTextTrack */ Player.prototype.removeRemoteTextTrack = function removeRemoteTextTrack(track) { this.tech && this.tech['removeRemoteTextTrack'](track); }; /** * Get video width * * @return {Number} Video width * @method videoWidth */ Player.prototype.videoWidth = function videoWidth() { return this.tech && this.tech.videoWidth && this.tech.videoWidth() || 0; }; /** * Get video height * * @return {Number} Video height * @method videoHeight */ Player.prototype.videoHeight = function videoHeight() { return this.tech && this.tech.videoHeight && this.tech.videoHeight() || 0; }; // Methods to add support for // initialTime: function(){ return this.techCall('initialTime'); }, // startOffsetTime: function(){ return this.techCall('startOffsetTime'); }, // played: function(){ return this.techCall('played'); }, // seekable: function(){ return this.techCall('seekable'); }, // videoTracks: function(){ return this.techCall('videoTracks'); }, // audioTracks: function(){ return this.techCall('audioTracks'); }, // defaultPlaybackRate: function(){ return this.techCall('defaultPlaybackRate'); }, // mediaGroup: function(){ return this.techCall('mediaGroup'); }, // controller: function(){ return this.techCall('controller'); }, // defaultMuted: function(){ return this.techCall('defaultMuted'); } // TODO // currentSrcList: the array of sources including other formats and bitrates // playList: array of source lists in order of playback /** * The player's language code * NOTE: The language should be set in the player options if you want the * the controls to be built with a specific language. Changing the lanugage * later will not update controls text. * * @param {String} code The locale string * @return {String} The locale string when getting * @return {Player} self when setting * @method language */ Player.prototype.language = function language(code) { if (code === undefined) { return this.language_; } this.language_ = ('' + code).toLowerCase(); return this; }; /** * Get the player's language dictionary * Merge every time, because a newly added plugin might call videojs.addLanguage() at any time * Languages specified directly in the player options have precedence * * @return {Array} Array of languages * @method languages */ Player.prototype.languages = function languages() { return _utilsMergeOptionsJs2['default'](Player.prototype.options_.languages, this.languages_); }; /** * Converts track info to JSON * * @return {Object} JSON object of options * @method toJSON */ Player.prototype.toJSON = function toJSON() { var options = _utilsMergeOptionsJs2['default'](this.options_); var tracks = options.tracks; options.tracks = []; for (var i = 0; i < tracks.length; i++) { var track = tracks[i]; // deep merge tracks and null out player so no circular references track = _utilsMergeOptionsJs2['default'](track); track.player = undefined; options.tracks[i] = track; } return options; }; /** * Gets tag settings * * @param {Element} tag The player tag * @return {Array} An array of sources and track objects * @static * @method getTagSettings */ Player.getTagSettings = function getTagSettings(tag) { var baseOptions = { 'sources': [], 'tracks': [] }; var tagOptions = Dom.getElAttributes(tag); var dataSetup = tagOptions['data-setup']; // Check if data-setup attr exists. if (dataSetup !== null) { // Parse options JSON var _safeParseTuple = _safeJsonParseTuple2['default'](dataSetup || '{}'); var err = _safeParseTuple[0]; var data = _safeParseTuple[1]; if (err) { _utilsLogJs2['default'].error(err); } _objectAssign2['default'](tagOptions, data); } _objectAssign2['default'](baseOptions, tagOptions); // Get tag children settings if (tag.hasChildNodes()) { var children = tag.childNodes; for (var i = 0, j = children.length; i < j; i++) { var child = children[i]; // Change case needed: http://ejohn.org/blog/nodename-case-sensitivity/ var childName = child.nodeName.toLowerCase(); if (childName === 'source') { baseOptions.sources.push(Dom.getElAttributes(child)); } else if (childName === 'track') { baseOptions.tracks.push(Dom.getElAttributes(child)); } } } return baseOptions; }; return Player; })(_componentJs2['default']); Player.players = {}; var navigator = _globalWindow2['default'].navigator; /* * Player instance options, surfaced using options * options = Player.prototype.options_ * Make changes in options, not here. * * @type {Object} * @private */ Player.prototype.options_ = { // Default order of fallback technology techOrder: ['html5', 'flash'], // techOrder: ['flash','html5'], html5: {}, flash: {}, // defaultVolume: 0.85, defaultVolume: 0.00, // The freakin seaguls are driving me crazy! // default inactivity timeout inactivityTimeout: 2000, // default playback rates playbackRates: [], // Add playback rate selection by adding rates // 'playbackRates': [0.5, 1, 1.5, 2], // Included control sets children: { mediaLoader: {}, posterImage: {}, textTrackDisplay: {}, loadingSpinner: {}, bigPlayButton: {}, controlBar: {}, errorDisplay: {}, textTrackSettings: {} }, language: _globalDocument2['default'].getElementsByTagName('html')[0].getAttribute('lang') || navigator.languages && navigator.languages[0] || navigator.userLanguage || navigator.language || 'en', // locales and their language translations languages: {}, // Default message to show when a video cannot be played. notSupportedMessage: 'No compatible source was found for this video.' }; /** * Fired when the player has initial duration and dimension information * * @event loadedmetadata */ Player.prototype.handleLoadedMetaData; /** * Fired when the player has downloaded data at the current playback position * * @event loadeddata */ Player.prototype.handleLoadedData; /** * Fired when the player has finished downloading the source data * * @event loadedalldata */ Player.prototype.handleLoadedAllData; /** * Fired when the user is active, e.g. moves the mouse over the player * * @event useractive */ Player.prototype.handleUserActive; /** * Fired when the user is inactive, e.g. a short delay after the last mouse move or control interaction * * @event userinactive */ Player.prototype.handleUserInactive; /** * Fired when the current playback position has changed * * During playback this is fired every 15-250 milliseconds, depending on the * playback technology in use. * * @event timeupdate */ Player.prototype.handleTimeUpdate; /** * Fired when the volume changes * * @event volumechange */ Player.prototype.handleVolumeChange; /** * Fired when an error occurs * * @event error */ Player.prototype.handleError; Player.prototype.flexNotSupported_ = function () { var elem = _globalDocument2['default'].createElement('i'); // Note: We don't actually use flexBasis (or flexOrder), but it's one of the more // common flex features that we can rely on when checking for flex support. return !('flexBasis' in elem.style || 'webkitFlexBasis' in elem.style || 'mozFlexBasis' in elem.style || 'msFlexBasis' in elem.style || 'msFlexOrder' in elem.style) /* IE10-specific (2012 flex spec) */; }; _componentJs2['default'].registerComponent('Player', Player); exports['default'] = Player; module.exports = exports['default']; // If empty string, make it a parsable json object. },{"./big-play-button.js":46,"./component.js":48,"./control-bar/control-bar.js":49,"./error-display.js":78,"./fullscreen-api.js":81,"./loading-spinner.js":82,"./media-error.js":83,"./poster-image.js":89,"./tech/html5.js":94,"./tech/loader.js":95,"./tracks/text-track-display.js":98,"./tracks/text-track-list-converter.js":100,"./tracks/text-track-settings.js":102,"./utils/browser.js":104,"./utils/buffer.js":105,"./utils/dom.js":107,"./utils/events.js":108,"./utils/fn.js":109,"./utils/guid.js":111,"./utils/log.js":112,"./utils/merge-options.js":113,"./utils/stylesheet.js":114,"./utils/time-ranges.js":115,"./utils/to-title-case.js":116,"global/document":1,"global/window":2,"object.assign":40,"safe-json-parse/tuple":45}],88:[function(_dereq_,module,exports){ /** * @file plugins.js */ 'use strict'; exports.__esModule = true; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } var _playerJs = _dereq_('./player.js'); var _playerJs2 = _interopRequireDefault(_playerJs); /** * The method for registering a video.js plugin * * @param {String} name The name of the plugin * @param {Function} init The function that is run when the player inits * @method plugin */ var plugin = function plugin(name, init) { _playerJs2['default'].prototype[name] = init; }; exports['default'] = plugin; module.exports = exports['default']; },{"./player.js":87}],89:[function(_dereq_,module,exports){ /** * @file poster-image.js */ 'use strict'; exports.__esModule = true; function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj['default'] = obj; return newObj; } } function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var _buttonJs = _dereq_('./button.js'); var _buttonJs2 = _interopRequireDefault(_buttonJs); var _componentJs = _dereq_('./component.js'); var _componentJs2 = _interopRequireDefault(_componentJs); var _utilsFnJs = _dereq_('./utils/fn.js'); var Fn = _interopRequireWildcard(_utilsFnJs); var _utilsDomJs = _dereq_('./utils/dom.js'); var Dom = _interopRequireWildcard(_utilsDomJs); var _utilsBrowserJs = _dereq_('./utils/browser.js'); var browser = _interopRequireWildcard(_utilsBrowserJs); /** * The component that handles showing the poster image. * * @param {Player|Object} player * @param {Object=} options * @extends Button * @class PosterImage */ var PosterImage = (function (_Button) { _inherits(PosterImage, _Button); function PosterImage(player, options) { _classCallCheck(this, PosterImage); _Button.call(this, player, options); this.update(); player.on('posterchange', Fn.bind(this, this.update)); } /** * Clean up the poster image * * @method dispose */ PosterImage.prototype.dispose = function dispose() { this.player().off('posterchange', this.update); _Button.prototype.dispose.call(this); }; /** * Create the poster's image element * * @return {Element} * @method createEl */ PosterImage.prototype.createEl = function createEl() { var el = Dom.createEl('div', { className: 'vjs-poster', // Don't want poster to be tabbable. tabIndex: -1 }); // To ensure the poster image resizes while maintaining its original aspect // ratio, use a div with `background-size` when available. For browsers that // do not support `background-size` (e.g. IE8), fall back on using a regular // img element. if (!browser.BACKGROUND_SIZE_SUPPORTED) { this.fallbackImg_ = Dom.createEl('img'); el.appendChild(this.fallbackImg_); } return el; }; /** * Event handler for updates to the player's poster source * * @method update */ PosterImage.prototype.update = function update() { var url = this.player().poster(); this.setSrc(url); // If there's no poster source we should display:none on this component // so it's not still clickable or right-clickable if (url) { this.show(); } else { this.hide(); } }; /** * Set the poster source depending on the display method * * @param {String} url The URL to the poster source * @method setSrc */ PosterImage.prototype.setSrc = function setSrc(url) { if (this.fallbackImg_) { this.fallbackImg_.src = url; } else { var backgroundImage = ''; // Any falsey values should stay as an empty string, otherwise // this will throw an extra error if (url) { backgroundImage = 'url("' + url + '")'; } this.el_.style.backgroundImage = backgroundImage; } }; /** * Event handler for clicks on the poster image * * @method handleClick */ PosterImage.prototype.handleClick = function handleClick() { // We don't want a click to trigger playback when controls are disabled // but CSS should be hiding the poster to prevent that from happening if (this.player_.paused()) { this.player_.play(); } else { this.player_.pause(); } }; return PosterImage; })(_buttonJs2['default']); _componentJs2['default'].registerComponent('PosterImage', PosterImage); exports['default'] = PosterImage; module.exports = exports['default']; },{"./button.js":47,"./component.js":48,"./utils/browser.js":104,"./utils/dom.js":107,"./utils/fn.js":109}],90:[function(_dereq_,module,exports){ /** * @file setup.js * * Functions for automatically setting up a player * based on the data-setup attribute of the video tag */ 'use strict'; exports.__esModule = true; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj['default'] = obj; return newObj; } } var _utilsEventsJs = _dereq_('./utils/events.js'); var Events = _interopRequireWildcard(_utilsEventsJs); var _globalDocument = _dereq_('global/document'); var _globalDocument2 = _interopRequireDefault(_globalDocument); var _globalWindow = _dereq_('global/window'); var _globalWindow2 = _interopRequireDefault(_globalWindow); var _windowLoaded = false; var videojs = undefined; // Automatically set up any tags that have a data-setup attribute var autoSetup = function autoSetup() { // One day, when we stop supporting IE8, go back to this, but in the meantime...*hack hack hack* // var vids = Array.prototype.slice.call(document.getElementsByTagName('video')); // var audios = Array.prototype.slice.call(document.getElementsByTagName('audio')); // var mediaEls = vids.concat(audios); // Because IE8 doesn't support calling slice on a node list, we need to loop through each list of elements // to build up a new, combined list of elements. var vids = _globalDocument2['default'].getElementsByTagName('video'); var audios = _globalDocument2['default'].getElementsByTagName('audio'); var mediaEls = []; if (vids && vids.length > 0) { for (var i = 0, e = vids.length; i < e; i++) { mediaEls.push(vids[i]); } } if (audios && audios.length > 0) { for (var i = 0, e = audios.length; i < e; i++) { mediaEls.push(audios[i]); } } // Check if any media elements exist if (mediaEls && mediaEls.length > 0) { for (var i = 0, e = mediaEls.length; i < e; i++) { var mediaEl = mediaEls[i]; // Check if element exists, has getAttribute func. // IE seems to consider typeof el.getAttribute == 'object' instead of 'function' like expected, at least when loading the player immediately. if (mediaEl && mediaEl.getAttribute) { // Make sure this player hasn't already been set up. if (mediaEl['player'] === undefined) { var options = mediaEl.getAttribute('data-setup'); // Check if data-setup attr exists. // We only auto-setup if they've added the data-setup attr. if (options !== null) { // Create new video.js instance. var player = videojs(mediaEl); } } // If getAttribute isn't defined, we need to wait for the DOM. } else { autoSetupTimeout(1); break; } } // No videos were found, so keep looping unless page is finished loading. } else if (!_windowLoaded) { autoSetupTimeout(1); } }; // Pause to let the DOM keep processing var autoSetupTimeout = function autoSetupTimeout(wait, vjs) { videojs = vjs; setTimeout(autoSetup, wait); }; if (_globalDocument2['default'].readyState === 'complete') { _windowLoaded = true; } else { Events.one(_globalWindow2['default'], 'load', function () { _windowLoaded = true; }); } var hasLoaded = function hasLoaded() { return _windowLoaded; }; exports.autoSetup = autoSetup; exports.autoSetupTimeout = autoSetupTimeout; exports.hasLoaded = hasLoaded; },{"./utils/events.js":108,"global/document":1,"global/window":2}],91:[function(_dereq_,module,exports){ /** * @file slider.js */ 'use strict'; exports.__esModule = true; function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj['default'] = obj; return newObj; } } function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var _componentJs = _dereq_('../component.js'); var _componentJs2 = _interopRequireDefault(_componentJs); var _utilsDomJs = _dereq_('../utils/dom.js'); var Dom = _interopRequireWildcard(_utilsDomJs); var _globalDocument = _dereq_('global/document'); var _globalDocument2 = _interopRequireDefault(_globalDocument); var _objectAssign = _dereq_('object.assign'); var _objectAssign2 = _interopRequireDefault(_objectAssign); /** * The base functionality for sliders like the volume bar and seek bar * * @param {Player|Object} player * @param {Object=} options * @extends Component * @class Slider */ var Slider = (function (_Component) { _inherits(Slider, _Component); function Slider(player, options) { _classCallCheck(this, Slider); _Component.call(this, player, options); // Set property names to bar to match with the child Slider class is looking for this.bar = this.getChild(this.options_.barName); // Set a horizontal or vertical class on the slider depending on the slider type this.vertical(!!this.options_.vertical); this.on('mousedown', this.handleMouseDown); this.on('touchstart', this.handleMouseDown); this.on('focus', this.handleFocus); this.on('blur', this.handleBlur); this.on('click', this.handleClick); this.on(player, 'controlsvisible', this.update); this.on(player, this.playerEvent, this.update); } /** * Create the component's DOM element * * @param {String} type Type of element to create * @param {Object=} props List of properties in Object form * @return {Element} * @method createEl */ Slider.prototype.createEl = function createEl(type) { var props = arguments.length <= 1 || arguments[1] === undefined ? {} : arguments[1]; // Add the slider element class to all sub classes props.className = props.className + ' vjs-slider'; props = _objectAssign2['default']({ 'role': 'slider', 'aria-valuenow': 0, 'aria-valuemin': 0, 'aria-valuemax': 100, tabIndex: 0 }, props); return _Component.prototype.createEl.call(this, type, props); }; /** * Handle mouse down on slider * * @param {Object} event Mouse down event object * @method handleMouseDown */ Slider.prototype.handleMouseDown = function handleMouseDown(event) { event.preventDefault(); Dom.blockTextSelection(); this.addClass('vjs-sliding'); this.on(_globalDocument2['default'], 'mousemove', this.handleMouseMove); this.on(_globalDocument2['default'], 'mouseup', this.handleMouseUp); this.on(_globalDocument2['default'], 'touchmove', this.handleMouseMove); this.on(_globalDocument2['default'], 'touchend', this.handleMouseUp); this.handleMouseMove(event); }; /** * To be overridden by a subclass * * @method handleMouseMove */ Slider.prototype.handleMouseMove = function handleMouseMove() {}; /** * Handle mouse up on Slider * * @method handleMouseUp */ Slider.prototype.handleMouseUp = function handleMouseUp() { Dom.unblockTextSelection(); this.removeClass('vjs-sliding'); this.off(_globalDocument2['default'], 'mousemove', this.handleMouseMove); this.off(_globalDocument2['default'], 'mouseup', this.handleMouseUp); this.off(_globalDocument2['default'], 'touchmove', this.handleMouseMove); this.off(_globalDocument2['default'], 'touchend', this.handleMouseUp); this.update(); }; /** * Update slider * * @method update */ Slider.prototype.update = function update() { // In VolumeBar init we have a setTimeout for update that pops and update to the end of the // execution stack. The player is destroyed before then update will cause an error if (!this.el_) return; // If scrubbing, we could use a cached value to make the handle keep up with the user's mouse. // On HTML5 browsers scrubbing is really smooth, but some flash players are slow, so we might want to utilize this later. // var progress = (this.player_.scrubbing()) ? this.player_.getCache().currentTime / this.player_.duration() : this.player_.currentTime() / this.player_.duration(); var progress = this.getPercent(); var bar = this.bar; // If there's no bar... if (!bar) return; // Protect against no duration and other division issues if (typeof progress !== 'number' || progress !== progress || progress < 0 || progress === Infinity) { progress = 0; } // Convert to a percentage for setting var percentage = (progress * 100).toFixed(2) + '%'; // Set the new bar width or height if (this.vertical()) { bar.el().style.height = percentage; } else { bar.el().style.width = percentage; } }; /** * Calculate distance for slider * * @param {Object} event Event object * @method calculateDistance */ Slider.prototype.calculateDistance = function calculateDistance(event) { var el = this.el_; var box = Dom.findElPosition(el); var boxW = el.offsetWidth; var boxH = el.offsetHeight; if (this.vertical()) { var boxY = box.top; var pageY = undefined; if (event.changedTouches) { pageY = event.changedTouches[0].pageY; } else { pageY = event.pageY; } // Percent that the click is through the adjusted area return Math.max(0, Math.min(1, (boxY - pageY + boxH) / boxH)); } else { var boxX = box.left; var pageX = undefined; if (event.changedTouches) { pageX = event.changedTouches[0].pageX; } else { pageX = event.pageX; } // Percent that the click is through the adjusted area return Math.max(0, Math.min(1, (pageX - boxX) / boxW)); } }; /** * Handle on focus for slider * * @method handleFocus */ Slider.prototype.handleFocus = function handleFocus() { this.on(_globalDocument2['default'], 'keydown', this.handleKeyPress); }; /** * Handle key press for slider * * @param {Object} event Event object * @method handleKeyPress */ Slider.prototype.handleKeyPress = function handleKeyPress(event) { if (event.which === 37 || event.which === 40) { // Left and Down Arrows event.preventDefault(); this.stepBack(); } else if (event.which === 38 || event.which === 39) { // Up and Right Arrows event.preventDefault(); this.stepForward(); } }; /** * Handle on blur for slider * * @method handleBlur */ Slider.prototype.handleBlur = function handleBlur() { this.off(_globalDocument2['default'], 'keydown', this.handleKeyPress); }; /** * Listener for click events on slider, used to prevent clicks * from bubbling up to parent elements like button menus. * * @param {Object} event Event object * @method handleClick */ Slider.prototype.handleClick = function handleClick(event) { event.stopImmediatePropagation(); event.preventDefault(); }; /** * Get/set if slider is horizontal for vertical * * @param {Boolean} bool True if slider is vertical, false is horizontal * @return {Boolean} True if slider is vertical, false is horizontal * @method vertical */ Slider.prototype.vertical = function vertical(bool) { if (bool === undefined) { return this.vertical_ || false; } this.vertical_ = !!bool; if (this.vertical_) { this.addClass('vjs-slider-vertical'); } else { this.addClass('vjs-slider-horizontal'); } return this; }; return Slider; })(_componentJs2['default']); _componentJs2['default'].registerComponent('Slider', Slider); exports['default'] = Slider; module.exports = exports['default']; },{"../component.js":48,"../utils/dom.js":107,"global/document":1,"object.assign":40}],92:[function(_dereq_,module,exports){ /** * @file flash-rtmp.js */ 'use strict'; exports.__esModule = true; function FlashRtmpDecorator(Flash) { Flash.streamingFormats = { 'rtmp/mp4': 'MP4', 'rtmp/flv': 'FLV' }; Flash.streamFromParts = function (connection, stream) { return connection + '&' + stream; }; Flash.streamToParts = function (src) { var parts = { connection: '', stream: '' }; if (!src) return parts; // Look for the normal URL separator we expect, '&'. // If found, we split the URL into two pieces around the // first '&'. var connEnd = src.indexOf('&'); var streamBegin = undefined; if (connEnd !== -1) { streamBegin = connEnd + 1; } else { // If there's not a '&', we use the last '/' as the delimiter. connEnd = streamBegin = src.lastIndexOf('/') + 1; if (connEnd === 0) { // really, there's not a '/'? connEnd = streamBegin = src.length; } } parts.connection = src.substring(0, connEnd); parts.stream = src.substring(streamBegin, src.length); return parts; }; Flash.isStreamingType = function (srcType) { return srcType in Flash.streamingFormats; }; // RTMP has four variations, any string starting // with one of these protocols should be valid Flash.RTMP_RE = /^rtmp[set]?:\/\//i; Flash.isStreamingSrc = function (src) { return Flash.RTMP_RE.test(src); }; /** * A source handler for RTMP urls * @type {Object} */ Flash.rtmpSourceHandler = {}; /** * Check Flash can handle the source natively * @param {Object} source The source object * @return {String} 'probably', 'maybe', or '' (empty string) */ Flash.rtmpSourceHandler.canHandleSource = function (source) { if (Flash.isStreamingType(source.type) || Flash.isStreamingSrc(source.src)) { return 'maybe'; } return ''; }; /** * Pass the source to the flash object * Adaptive source handlers will have more complicated workflows before passing * video data to the video element * @param {Object} source The source object * @param {Flash} tech The instance of the Flash tech */ Flash.rtmpSourceHandler.handleSource = function (source, tech) { var srcParts = Flash.streamToParts(source.src); tech['setRtmpConnection'](srcParts.connection); tech['setRtmpStream'](srcParts.stream); }; // Register the native source handler Flash.registerSourceHandler(Flash.rtmpSourceHandler); return Flash; } exports['default'] = FlashRtmpDecorator; module.exports = exports['default']; },{}],93:[function(_dereq_,module,exports){ /** * @file flash.js * VideoJS-SWF - Custom Flash Player with HTML5-ish API * https://github.com/zencoder/video-js-swf * Not using setupTriggers. Using global onEvent func to distribute events */ 'use strict'; exports.__esModule = true; function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj['default'] = obj; return newObj; } } function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var _tech = _dereq_('./tech'); var _tech2 = _interopRequireDefault(_tech); var _utilsDomJs = _dereq_('../utils/dom.js'); var Dom = _interopRequireWildcard(_utilsDomJs); var _utilsUrlJs = _dereq_('../utils/url.js'); var Url = _interopRequireWildcard(_utilsUrlJs); var _utilsTimeRangesJs = _dereq_('../utils/time-ranges.js'); var _flashRtmp = _dereq_('./flash-rtmp'); var _flashRtmp2 = _interopRequireDefault(_flashRtmp); var _component = _dereq_('../component'); var _component2 = _interopRequireDefault(_component); var _globalWindow = _dereq_('global/window'); var _globalWindow2 = _interopRequireDefault(_globalWindow); var _objectAssign = _dereq_('object.assign'); var _objectAssign2 = _interopRequireDefault(_objectAssign); var navigator = _globalWindow2['default'].navigator; /** * Flash Media Controller - Wrapper for fallback SWF API * * @param {Object=} options Object of option names and values * @param {Function=} ready Ready callback function * @extends Tech * @class Flash */ var Flash = (function (_Tech) { _inherits(Flash, _Tech); function Flash(options, ready) { _classCallCheck(this, Flash); _Tech.call(this, options, ready); // Set the source when ready if (options.source) { this.ready(function () { this.setSource(options.source); }, true); } // Having issues with Flash reloading on certain page actions (hide/resize/fullscreen) in certain browsers // This allows resetting the playhead when we catch the reload if (options.startTime) { this.ready(function () { this.load(); this.play(); this.currentTime(options.startTime); }, true); } // Add global window functions that the swf expects // A 4.x workflow we weren't able to solve for in 5.0 // because of the need to hard code these functions // into the swf for security reasons _globalWindow2['default'].videojs = _globalWindow2['default'].videojs || {}; _globalWindow2['default'].videojs.Flash = _globalWindow2['default'].videojs.Flash || {}; _globalWindow2['default'].videojs.Flash.onReady = Flash.onReady; _globalWindow2['default'].videojs.Flash.onEvent = Flash.onEvent; _globalWindow2['default'].videojs.Flash.onError = Flash.onError; this.on('seeked', function () { this.lastSeekTarget_ = undefined; }); } // Create setters and getters for attributes /** * Create the component's DOM element * * @return {Element} * @method createEl */ Flash.prototype.createEl = function createEl() { var options = this.options_; // If video.js is hosted locally you should also set the location // for the hosted swf, which should be relative to the page (not video.js) // Otherwise this adds a CDN url. // The CDN also auto-adds a swf URL for that specific version. if (!options.swf) { options.swf = '//vjs.zencdn.net/swf/5.0.0-rc1/video-js.swf'; } // Generate ID for swf object var objId = options.techId; // Merge default flashvars with ones passed in to init var flashVars = _objectAssign2['default']({ // SWF Callback Functions 'readyFunction': 'videojs.Flash.onReady', 'eventProxyFunction': 'videojs.Flash.onEvent', 'errorEventProxyFunction': 'videojs.Flash.onError', // Player Settings 'autoplay': options.autoplay, 'preload': options.preload, 'loop': options.loop, 'muted': options.muted }, options.flashVars); // Merge default parames with ones passed in var params = _objectAssign2['default']({ 'wmode': 'opaque', // Opaque is needed to overlay controls, but can affect playback performance 'bgcolor': '#000000' // Using bgcolor prevents a white flash when the object is loading }, options.params); // Merge default attributes with ones passed in var attributes = _objectAssign2['default']({ 'id': objId, 'name': objId, // Both ID and Name needed or swf to identify itself 'class': 'vjs-tech' }, options.attributes); this.el_ = Flash.embed(options.swf, flashVars, params, attributes); this.el_.tech = this; return this.el_; }; /** * Play for flash tech * * @method play */ Flash.prototype.play = function play() { if (this.ended()) { this.setCurrentTime(0); } this.el_.vjs_play(); }; /** * Pause for flash tech * * @method pause */ Flash.prototype.pause = function pause() { this.el_.vjs_pause(); }; /** * Get/set video * * @param {Object=} src Source object * @return {Object} * @method src */ Flash.prototype.src = function src(_src) { if (_src === undefined) { return this.currentSrc(); } // Setting src through `src` not `setSrc` will be deprecated return this.setSrc(_src); }; /** * Set video * * @param {Object=} src Source object * @deprecated * @method setSrc */ Flash.prototype.setSrc = function setSrc(src) { // Make sure source URL is absolute. src = Url.getAbsoluteURL(src); this.el_.vjs_src(src); // Currently the SWF doesn't autoplay if you load a source later. // e.g. Load player w/ no source, wait 2s, set src. if (this.autoplay()) { var tech = this; this.setTimeout(function () { tech.play(); }, 0); } }; /** * Returns true if the tech is currently seeking. * @return {boolean} true if seeking */ Flash.prototype.seeking = function seeking() { return this.lastSeekTarget_ !== undefined; }; /** * Set current time * * @param {Number} time Current time of video * @method setCurrentTime */ Flash.prototype.setCurrentTime = function setCurrentTime(time) { var seekable = this.seekable(); if (seekable.length) { // clamp to the current seekable range time = time > seekable.start(0) ? time : seekable.start(0); time = time < seekable.end(seekable.length - 1) ? time : seekable.end(seekable.length - 1); this.lastSeekTarget_ = time; this.trigger('seeking'); this.el_.vjs_setProperty('currentTime', time); _Tech.prototype.setCurrentTime.call(this); } }; /** * Get current time * * @param {Number=} time Current time of video * @return {Number} Current time * @method currentTime */ Flash.prototype.currentTime = function currentTime(time) { // when seeking make the reported time keep up with the requested time // by reading the time we're seeking to if (this.seeking()) { return this.lastSeekTarget_ || 0; } return this.el_.vjs_getProperty('currentTime'); }; /** * Get current source * * @method currentSrc */ Flash.prototype.currentSrc = function currentSrc() { if (this.currentSource_) { return this.currentSource_.src; } else { return this.el_.vjs_getProperty('currentSrc'); } }; /** * Load media into player * * @method load */ Flash.prototype.load = function load() { this.el_.vjs_load(); }; /** * Get poster * * @method poster */ Flash.prototype.poster = function poster() { this.el_.vjs_getProperty('poster'); }; /** * Poster images are not handled by the Flash tech so make this a no-op * * @method setPoster */ Flash.prototype.setPoster = function setPoster() {}; /** * Determine if can seek in media * * @return {TimeRangeObject} * @method seekable */ Flash.prototype.seekable = function seekable() { var duration = this.duration(); if (duration === 0) { return _utilsTimeRangesJs.createTimeRange(); } return _utilsTimeRangesJs.createTimeRange(0, duration); }; /** * Get buffered time range * * @return {TimeRangeObject} * @method buffered */ Flash.prototype.buffered = function buffered() { var ranges = this.el_.vjs_getProperty('buffered'); if (ranges.length === 0) { return _utilsTimeRangesJs.createTimeRange(); } return _utilsTimeRangesJs.createTimeRange(ranges[0][0], ranges[0][1]); }; /** * Get fullscreen support - * Flash does not allow fullscreen through javascript * so always returns false * * @return {Boolean} false * @method supportsFullScreen */ Flash.prototype.supportsFullScreen = function supportsFullScreen() { return false; // Flash does not allow fullscreen through javascript }; /** * Request to enter fullscreen * Flash does not allow fullscreen through javascript * so always returns false * * @return {Boolean} false * @method enterFullScreen */ Flash.prototype.enterFullScreen = function enterFullScreen() { return false; }; return Flash; })(_tech2['default']); var _api = Flash.prototype; var _readWrite = 'rtmpConnection,rtmpStream,preload,defaultPlaybackRate,playbackRate,autoplay,loop,mediaGroup,controller,controls,volume,muted,defaultMuted'.split(','); var _readOnly = 'networkState,readyState,initialTime,duration,startOffsetTime,paused,ended,videoTracks,audioTracks,videoWidth,videoHeight'.split(','); function _createSetter(attr) { var attrUpper = attr.charAt(0).toUpperCase() + attr.slice(1); _api['set' + attrUpper] = function (val) { return this.el_.vjs_setProperty(attr, val); }; } function _createGetter(attr) { _api[attr] = function () { return this.el_.vjs_getProperty(attr); }; } // Create getter and setters for all read/write attributes for (var i = 0; i < _readWrite.length; i++) { _createGetter(_readWrite[i]); _createSetter(_readWrite[i]); } // Create getters for read-only attributes for (var i = 0; i < _readOnly.length; i++) { _createGetter(_readOnly[i]); } /* Flash Support Testing -------------------------------------------------------- */ Flash.isSupported = function () { return Flash.version()[0] >= 10; // return swfobject.hasFlashPlayerVersion('10'); }; // Add Source Handler pattern functions to this tech _tech2['default'].withSourceHandlers(Flash); /* * The default native source handler. * This simply passes the source to the video element. Nothing fancy. * * @param {Object} source The source object * @param {Flash} tech The instance of the Flash tech */ Flash.nativeSourceHandler = {}; /* * Check Flash can handle the source natively * * @param {Object} source The source object * @return {String} 'probably', 'maybe', or '' (empty string) */ Flash.nativeSourceHandler.canHandleSource = function (source) { var type; function guessMimeType(src) { var ext = Url.getFileExtension(src); if (ext) { return 'video/' + ext; } return ''; } if (!source.type) { type = guessMimeType(source.src); } else { // Strip code information from the type because we don't get that specific type = source.type.replace(/;.*/, '').toLowerCase(); } if (type in Flash.formats) { return 'maybe'; } return ''; }; /* * Pass the source to the flash object * Adaptive source handlers will have more complicated workflows before passing * video data to the video element * * @param {Object} source The source object * @param {Flash} tech The instance of the Flash tech */ Flash.nativeSourceHandler.handleSource = function (source, tech) { tech.setSrc(source.src); }; /* * Clean up the source handler when disposing the player or switching sources.. * (no cleanup is needed when supporting the format natively) */ Flash.nativeSourceHandler.dispose = function () {}; // Register the native source handler Flash.registerSourceHandler(Flash.nativeSourceHandler); Flash.formats = { 'video/flv': 'FLV', 'video/x-flv': 'FLV', 'video/mp4': 'MP4', 'video/m4v': 'MP4' }; Flash.onReady = function (currSwf) { var el = Dom.getEl(currSwf); var tech = el && el.tech; // if there is no el then the tech has been disposed // and the tech element was removed from the player div if (tech && tech.el()) { // check that the flash object is really ready Flash.checkReady(tech); } }; // The SWF isn't always ready when it says it is. Sometimes the API functions still need to be added to the object. // If it's not ready, we set a timeout to check again shortly. Flash.checkReady = function (tech) { // stop worrying if the tech has been disposed if (!tech.el()) { return; } // check if API property exists if (tech.el().vjs_getProperty) { // tell tech it's ready tech.triggerReady(); } else { // wait longer this.setTimeout(function () { Flash['checkReady'](tech); }, 50); } }; // Trigger events from the swf on the player Flash.onEvent = function (swfID, eventName) { var tech = Dom.getEl(swfID).tech; tech.trigger(eventName); }; // Log errors from the swf Flash.onError = function (swfID, err) { var tech = Dom.getEl(swfID).tech; // trigger MEDIA_ERR_SRC_NOT_SUPPORTED if (err === 'srcnotfound') { return tech.error(4); } // trigger a custom error tech.error('FLASH: ' + err); }; // Flash Version Check Flash.version = function () { var version = '0,0,0'; // IE try { version = new _globalWindow2['default'].ActiveXObject('ShockwaveFlash.ShockwaveFlash').GetVariable('$version').replace(/\D+/g, ',').match(/^,?(.+),?$/)[1]; // other browsers } catch (e) { try { if (navigator.mimeTypes['application/x-shockwave-flash'].enabledPlugin) { version = (navigator.plugins['Shockwave Flash 2.0'] || navigator.plugins['Shockwave Flash']).description.replace(/\D+/g, ',').match(/^,?(.+),?$/)[1]; } } catch (err) {} } return version.split(','); }; // Flash embedding method. Only used in non-iframe mode Flash.embed = function (swf, flashVars, params, attributes) { var code = Flash.getEmbedCode(swf, flashVars, params, attributes); // Get element by embedding code and retrieving created element var obj = Dom.createEl('div', { innerHTML: code }).childNodes[0]; return obj; }; Flash.getEmbedCode = function (swf, flashVars, params, attributes) { var objTag = '<object type="application/x-shockwave-flash" '; var flashVarsString = ''; var paramsString = ''; var attrsString = ''; // Convert flash vars to string if (flashVars) { Object.getOwnPropertyNames(flashVars).forEach(function (key) { flashVarsString += key + '=' + flashVars[key] + '&amp;'; }); } // Add swf, flashVars, and other default params params = _objectAssign2['default']({ 'movie': swf, 'flashvars': flashVarsString, 'allowScriptAccess': 'always', // Required to talk to swf 'allowNetworking': 'all' // All should be default, but having security issues. }, params); // Create param tags string Object.getOwnPropertyNames(params).forEach(function (key) { paramsString += '<param name="' + key + '" value="' + params[key] + '" />'; }); attributes = _objectAssign2['default']({ // Add swf to attributes (need both for IE and Others to work) 'data': swf, // Default to 100% width/height 'width': '100%', 'height': '100%' }, attributes); // Create Attributes string Object.getOwnPropertyNames(attributes).forEach(function (key) { attrsString += key + '="' + attributes[key] + '" '; }); return '' + objTag + attrsString + '>' + paramsString + '</object>'; }; // Run Flash through the RTMP decorator _flashRtmp2['default'](Flash); _component2['default'].registerComponent('Flash', Flash); exports['default'] = Flash; module.exports = exports['default']; },{"../component":48,"../utils/dom.js":107,"../utils/time-ranges.js":115,"../utils/url.js":117,"./flash-rtmp":92,"./tech":96,"global/window":2,"object.assign":40}],94:[function(_dereq_,module,exports){ /** * @file html5.js * HTML5 Media Controller - Wrapper for HTML5 Media API */ 'use strict'; exports.__esModule = true; function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj['default'] = obj; return newObj; } } function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var _techJs = _dereq_('./tech.js'); var _techJs2 = _interopRequireDefault(_techJs); var _component = _dereq_('../component'); var _component2 = _interopRequireDefault(_component); var _utilsDomJs = _dereq_('../utils/dom.js'); var Dom = _interopRequireWildcard(_utilsDomJs); var _utilsUrlJs = _dereq_('../utils/url.js'); var Url = _interopRequireWildcard(_utilsUrlJs); var _utilsFnJs = _dereq_('../utils/fn.js'); var Fn = _interopRequireWildcard(_utilsFnJs); var _utilsLogJs = _dereq_('../utils/log.js'); var _utilsLogJs2 = _interopRequireDefault(_utilsLogJs); var _utilsBrowserJs = _dereq_('../utils/browser.js'); var browser = _interopRequireWildcard(_utilsBrowserJs); var _globalDocument = _dereq_('global/document'); var _globalDocument2 = _interopRequireDefault(_globalDocument); var _globalWindow = _dereq_('global/window'); var _globalWindow2 = _interopRequireDefault(_globalWindow); var _objectAssign = _dereq_('object.assign'); var _objectAssign2 = _interopRequireDefault(_objectAssign); var _utilsMergeOptionsJs = _dereq_('../utils/merge-options.js'); var _utilsMergeOptionsJs2 = _interopRequireDefault(_utilsMergeOptionsJs); /** * HTML5 Media Controller - Wrapper for HTML5 Media API * * @param {Object=} options Object of option names and values * @param {Function=} ready Ready callback function * @extends Tech * @class Html5 */ var Html5 = (function (_Tech) { _inherits(Html5, _Tech); function Html5(options, ready) { _classCallCheck(this, Html5); _Tech.call(this, options, ready); var source = options.source; // Set the source if one is provided // 1) Check if the source is new (if not, we want to keep the original so playback isn't interrupted) // 2) Check to see if the network state of the tag was failed at init, and if so, reset the source // anyway so the error gets fired. if (source && (this.el_.currentSrc !== source.src || options.tag && options.tag.initNetworkState_ === 3)) { this.setSource(source); } if (this.el_.hasChildNodes()) { var nodes = this.el_.childNodes; var nodesLength = nodes.length; var removeNodes = []; while (nodesLength--) { var node = nodes[nodesLength]; var nodeName = node.nodeName.toLowerCase(); if (nodeName === 'track') { if (!this.featuresNativeTextTracks) { // Empty video tag tracks so the built-in player doesn't use them also. // This may not be fast enough to stop HTML5 browsers from reading the tags // so we'll need to turn off any default tracks if we're manually doing // captions and subtitles. videoElement.textTracks removeNodes.push(node); } else { this.remoteTextTracks().addTrack_(node.track); } } } for (var i = 0; i < removeNodes.length; i++) { this.el_.removeChild(removeNodes[i]); } } if (this.featuresNativeTextTracks) { this.handleTextTrackChange_ = Fn.bind(this, this.handleTextTrackChange); this.handleTextTrackAdd_ = Fn.bind(this, this.handleTextTrackAdd); this.handleTextTrackRemove_ = Fn.bind(this, this.handleTextTrackRemove); this.proxyNativeTextTracks_(); } // Determine if native controls should be used // Our goal should be to get the custom controls on mobile solid everywhere // so we can remove this all together. Right now this will block custom // controls on touch enabled laptops like the Chrome Pixel if (browser.TOUCH_ENABLED && options.nativeControlsForTouch === true || browser.IS_IPHONE || browser.IS_NATIVE_ANDROID) { this.setControls(true); } this.triggerReady(); } /* HTML5 Support Testing ---------------------------------------------------- */ /* * Element for testing browser HTML5 video capabilities * * @type {Element} * @constant * @private */ /** * Dispose of html5 media element * * @method dispose */ Html5.prototype.dispose = function dispose() { var tt = this.el().textTracks; var emulatedTt = this.textTracks(); // remove native event listeners if (tt && tt.removeEventListener) { tt.removeEventListener('change', this.handleTextTrackChange_); tt.removeEventListener('addtrack', this.handleTextTrackAdd_); tt.removeEventListener('removetrack', this.handleTextTrackRemove_); } // clearout the emulated text track list. var i = emulatedTt.length; while (i--) { emulatedTt.removeTrack_(emulatedTt[i]); } Html5.disposeMediaElement(this.el_); _Tech.prototype.dispose.call(this); }; /** * Create the component's DOM element * * @return {Element} * @method createEl */ Html5.prototype.createEl = function createEl() { var el = this.options_.tag; // Check if this browser supports moving the element into the box. // On the iPhone video will break if you move the element, // So we have to create a brand new element. if (!el || this['movingMediaElementInDOM'] === false) { // If the original tag is still there, clone and remove it. if (el) { var clone = el.cloneNode(true); el.parentNode.insertBefore(clone, el); Html5.disposeMediaElement(el); el = clone; } else { el = _globalDocument2['default'].createElement('video'); // determine if native controls should be used var tagAttributes = this.options_.tag && Dom.getElAttributes(this.options_.tag); var attributes = _utilsMergeOptionsJs2['default']({}, tagAttributes); if (!browser.TOUCH_ENABLED || this.options_.nativeControlsForTouch !== true) { delete attributes.controls; } Dom.setElAttributes(el, _objectAssign2['default'](attributes, { id: this.options_.techId, 'class': 'vjs-tech' })); } } // Update specific tag settings, in case they were overridden var settingsAttrs = ['autoplay', 'preload', 'loop', 'muted']; for (var i = settingsAttrs.length - 1; i >= 0; i--) { var attr = settingsAttrs[i]; var overwriteAttrs = {}; if (typeof this.options_[attr] !== 'undefined') { overwriteAttrs[attr] = this.options_[attr]; } Dom.setElAttributes(el, overwriteAttrs); } return el; // jenniisawesome = true; }; Html5.prototype.proxyNativeTextTracks_ = function proxyNativeTextTracks_() { var tt = this.el().textTracks; if (tt && tt.addEventListener) { tt.addEventListener('change', this.handleTextTrackChange_); tt.addEventListener('addtrack', this.handleTextTrackAdd_); tt.addEventListener('removetrack', this.handleTextTrackRemove_); } }; Html5.prototype.handleTextTrackChange = function handleTextTrackChange(e) { var tt = this.textTracks(); this.textTracks().trigger({ type: 'change', target: tt, currentTarget: tt, srcElement: tt }); }; Html5.prototype.handleTextTrackAdd = function handleTextTrackAdd(e) { this.textTracks().addTrack_(e.track); }; Html5.prototype.handleTextTrackRemove = function handleTextTrackRemove(e) { this.textTracks().removeTrack_(e.track); }; /** * Play for html5 tech * * @method play */ Html5.prototype.play = function play() { this.el_.play(); }; /** * Pause for html5 tech * * @method pause */ Html5.prototype.pause = function pause() { this.el_.pause(); }; /** * Paused for html5 tech * * @return {Boolean} * @method paused */ Html5.prototype.paused = function paused() { return this.el_.paused; }; /** * Get current time * * @return {Number} * @method currentTime */ Html5.prototype.currentTime = function currentTime() { return this.el_.currentTime; }; /** * Set current time * * @param {Number} seconds Current time of video * @method setCurrentTime */ Html5.prototype.setCurrentTime = function setCurrentTime(seconds) { try { this.el_.currentTime = seconds; } catch (e) { _utilsLogJs2['default'](e, 'Video is not ready. (Video.js)'); // this.warning(VideoJS.warnings.videoNotReady); } }; /** * Get duration * * @return {Number} * @method duration */ Html5.prototype.duration = function duration() { return this.el_.duration || 0; }; /** * Get a TimeRange object that represents the intersection * of the time ranges for which the user agent has all * relevant media * * @return {TimeRangeObject} * @method buffered */ Html5.prototype.buffered = function buffered() { return this.el_.buffered; }; /** * Get volume level * * @return {Number} * @method volume */ Html5.prototype.volume = function volume() { return this.el_.volume; }; /** * Set volume level * * @param {Number} percentAsDecimal Volume percent as a decimal * @method setVolume */ Html5.prototype.setVolume = function setVolume(percentAsDecimal) { this.el_.volume = percentAsDecimal; }; /** * Get if muted * * @return {Boolean} * @method muted */ Html5.prototype.muted = function muted() { return this.el_.muted; }; /** * Set muted * * @param {Boolean} If player is to be muted or note * @method setMuted */ Html5.prototype.setMuted = function setMuted(muted) { this.el_.muted = muted; }; /** * Get player width * * @return {Number} * @method width */ Html5.prototype.width = function width() { return this.el_.offsetWidth; }; /** * Get player height * * @return {Number} * @method height */ Html5.prototype.height = function height() { return this.el_.offsetHeight; }; /** * Get if there is fullscreen support * * @return {Boolean} * @method supportsFullScreen */ Html5.prototype.supportsFullScreen = function supportsFullScreen() { if (typeof this.el_.webkitEnterFullScreen === 'function') { var userAgent = _globalWindow2['default'].navigator.userAgent; // Seems to be broken in Chromium/Chrome && Safari in Leopard if (/Android/.test(userAgent) || !/Chrome|Mac OS X 10.5/.test(userAgent)) { return true; } } return false; }; /** * Request to enter fullscreen * * @method enterFullScreen */ Html5.prototype.enterFullScreen = function enterFullScreen() { var video = this.el_; if ('webkitDisplayingFullscreen' in video) { this.one('webkitbeginfullscreen', function () { this.one('webkitendfullscreen', function () { this.trigger('fullscreenchange', { isFullscreen: false }); }); this.trigger('fullscreenchange', { isFullscreen: true }); }); } if (video.paused && video.networkState <= video.HAVE_METADATA) { // attempt to prime the video element for programmatic access // this isn't necessary on the desktop but shouldn't hurt this.el_.play(); // playing and pausing synchronously during the transition to fullscreen // can get iOS ~6.1 devices into a play/pause loop this.setTimeout(function () { video.pause(); video.webkitEnterFullScreen(); }, 0); } else { video.webkitEnterFullScreen(); } }; /** * Request to exit fullscreen * * @method exitFullScreen */ Html5.prototype.exitFullScreen = function exitFullScreen() { this.el_.webkitExitFullScreen(); }; /** * Get/set video * * @param {Object=} src Source object * @return {Object} * @method src */ Html5.prototype.src = function src(_src) { if (_src === undefined) { return this.el_.src; } else { // Setting src through `src` instead of `setSrc` will be deprecated this.setSrc(_src); } }; /** * Set video * * @param {Object} src Source object * @deprecated * @method setSrc */ Html5.prototype.setSrc = function setSrc(src) { this.el_.src = src; }; /** * Load media into player * * @method load */ Html5.prototype.load = function load() { this.el_.load(); }; /** * Get current source * * @return {Object} * @method currentSrc */ Html5.prototype.currentSrc = function currentSrc() { return this.el_.currentSrc; }; /** * Get poster * * @return {String} * @method poster */ Html5.prototype.poster = function poster() { return this.el_.poster; }; /** * Set poster * * @param {String} val URL to poster image * @method */ Html5.prototype.setPoster = function setPoster(val) { this.el_.poster = val; }; /** * Get preload attribute * * @return {String} * @method preload */ Html5.prototype.preload = function preload() { return this.el_.preload; }; /** * Set preload attribute * * @param {String} val Value for preload attribute * @method setPreload */ Html5.prototype.setPreload = function setPreload(val) { this.el_.preload = val; }; /** * Get autoplay attribute * * @return {String} * @method autoplay */ Html5.prototype.autoplay = function autoplay() { return this.el_.autoplay; }; /** * Set autoplay attribute * * @param {String} val Value for preload attribute * @method setAutoplay */ Html5.prototype.setAutoplay = function setAutoplay(val) { this.el_.autoplay = val; }; /** * Get controls attribute * * @return {String} * @method controls */ Html5.prototype.controls = function controls() { return this.el_.controls; }; /** * Set controls attribute * * @param {String} val Value for controls attribute * @method setControls */ Html5.prototype.setControls = function setControls(val) { this.el_.controls = !!val; }; /** * Get loop attribute * * @return {String} * @method loop */ Html5.prototype.loop = function loop() { return this.el_.loop; }; /** * Set loop attribute * * @param {String} val Value for loop attribute * @method setLoop */ Html5.prototype.setLoop = function setLoop(val) { this.el_.loop = val; }; /** * Get error value * * @return {String} * @method error */ Html5.prototype.error = function error() { return this.el_.error; }; /** * Get whether or not the player is in the "seeking" state * * @return {Boolean} * @method seeking */ Html5.prototype.seeking = function seeking() { return this.el_.seeking; }; /** * Get a TimeRanges object that represents the * ranges of the media resource to which it is possible * for the user agent to seek. * * @return {TimeRangeObject} * @method seekable */ Html5.prototype.seekable = function seekable() { return this.el_.seekable; }; /** * Get if video ended * * @return {Boolean} * @method ended */ Html5.prototype.ended = function ended() { return this.el_.ended; }; /** * Get the value of the muted content attribute * This attribute has no dynamic effect, it only * controls the default state of the element * * @return {Boolean} * @method defaultMuted */ Html5.prototype.defaultMuted = function defaultMuted() { return this.el_.defaultMuted; }; /** * Get desired speed at which the media resource is to play * * @return {Number} * @method playbackRate */ Html5.prototype.playbackRate = function playbackRate() { return this.el_.playbackRate; }; /** * Returns a TimeRanges object that represents the ranges of the * media resource that the user agent has played. * @return {TimeRangeObject} the range of points on the media * timeline that has been reached through normal playback * @see https://html.spec.whatwg.org/multipage/embedded-content.html#dom-media-played */ Html5.prototype.played = function played() { return this.el_.played; }; /** * Set desired speed at which the media resource is to play * * @param {Number} val Speed at which the media resource is to play * @method setPlaybackRate */ Html5.prototype.setPlaybackRate = function setPlaybackRate(val) { this.el_.playbackRate = val; }; /** * Get the current state of network activity for the element, from * the list below * NETWORK_EMPTY (numeric value 0) * NETWORK_IDLE (numeric value 1) * NETWORK_LOADING (numeric value 2) * NETWORK_NO_SOURCE (numeric value 3) * * @return {Number} * @method networkState */ Html5.prototype.networkState = function networkState() { return this.el_.networkState; }; /** * Get a value that expresses the current state of the element * with respect to rendering the current playback position, from * the codes in the list below * HAVE_NOTHING (numeric value 0) * HAVE_METADATA (numeric value 1) * HAVE_CURRENT_DATA (numeric value 2) * HAVE_FUTURE_DATA (numeric value 3) * HAVE_ENOUGH_DATA (numeric value 4) * * @return {Number} * @method readyState */ Html5.prototype.readyState = function readyState() { return this.el_.readyState; }; /** * Get width of video * * @return {Number} * @method videoWidth */ Html5.prototype.videoWidth = function videoWidth() { return this.el_.videoWidth; }; /** * Get height of video * * @return {Number} * @method videoHeight */ Html5.prototype.videoHeight = function videoHeight() { return this.el_.videoHeight; }; /** * Get text tracks * * @return {TextTrackList} * @method textTracks */ Html5.prototype.textTracks = function textTracks() { return _Tech.prototype.textTracks.call(this); }; /** * Creates and returns a text track object * * @param {String} kind Text track kind (subtitles, captions, descriptions * chapters and metadata) * @param {String=} label Label to identify the text track * @param {String=} language Two letter language abbreviation * @return {TextTrackObject} * @method addTextTrack */ Html5.prototype.addTextTrack = function addTextTrack(kind, label, language) { if (!this['featuresNativeTextTracks']) { return _Tech.prototype.addTextTrack.call(this, kind, label, language); } return this.el_.addTextTrack(kind, label, language); }; /** * Creates and returns a remote text track object * * @param {Object} options The object should contain values for * kind, language, label and src (location of the WebVTT file) * @return {TextTrackObject} * @method addRemoteTextTrack */ Html5.prototype.addRemoteTextTrack = function addRemoteTextTrack() { var options = arguments.length <= 0 || arguments[0] === undefined ? {} : arguments[0]; if (!this['featuresNativeTextTracks']) { return _Tech.prototype.addRemoteTextTrack.call(this, options); } var track = _globalDocument2['default'].createElement('track'); if (options['kind']) { track['kind'] = options['kind']; } if (options['label']) { track['label'] = options['label']; } if (options['language'] || options['srclang']) { track['srclang'] = options['language'] || options['srclang']; } if (options['default']) { track['default'] = options['default']; } if (options['id']) { track['id'] = options['id']; } if (options['src']) { track['src'] = options['src']; } this.el().appendChild(track); this.remoteTextTracks().addTrack_(track.track); return track; }; /** * Remove remote text track from TextTrackList object * * @param {TextTrackObject} track Texttrack object to remove * @method removeRemoteTextTrack */ Html5.prototype.removeRemoteTextTrack = function removeRemoteTextTrack(track) { if (!this['featuresNativeTextTracks']) { return _Tech.prototype.removeRemoteTextTrack.call(this, track); } var tracks, i; this.remoteTextTracks().removeTrack_(track); tracks = this.el().querySelectorAll('track'); i = tracks.length; while (i--) { if (track === tracks[i] || track === tracks[i].track) { this.el().removeChild(tracks[i]); } } }; return Html5; })(_techJs2['default']); Html5.TEST_VID = _globalDocument2['default'].createElement('video'); var track = _globalDocument2['default'].createElement('track'); track.kind = 'captions'; track.srclang = 'en'; track.label = 'English'; Html5.TEST_VID.appendChild(track); /* * Check if HTML5 video is supported by this browser/device * * @return {Boolean} */ Html5.isSupported = function () { // IE9 with no Media Player is a LIAR! (#984) try { Html5.TEST_VID['volume'] = 0.5; } catch (e) { return false; } return !!Html5.TEST_VID.canPlayType; }; // Add Source Handler pattern functions to this tech _techJs2['default'].withSourceHandlers(Html5); /* * The default native source handler. * This simply passes the source to the video element. Nothing fancy. * * @param {Object} source The source object * @param {Html5} tech The instance of the HTML5 tech */ Html5.nativeSourceHandler = {}; /* * Check if the video element can handle the source natively * * @param {Object} source The source object * @return {String} 'probably', 'maybe', or '' (empty string) */ Html5.nativeSourceHandler.canHandleSource = function (source) { var match, ext; function canPlayType(type) { // IE9 on Windows 7 without MediaPlayer throws an error here // https://github.com/videojs/video.js/issues/519 try { return Html5.TEST_VID.canPlayType(type); } catch (e) { return ''; } } // If a type was provided we should rely on that if (source.type) { return canPlayType(source.type); } else if (source.src) { // If no type, fall back to checking 'video/[EXTENSION]' ext = Url.getFileExtension(source.src); return canPlayType('video/' + ext); } return ''; }; /* * Pass the source to the video element * Adaptive source handlers will have more complicated workflows before passing * video data to the video element * * @param {Object} source The source object * @param {Html5} tech The instance of the Html5 tech */ Html5.nativeSourceHandler.handleSource = function (source, tech) { tech.setSrc(source.src); }; /* * Clean up the source handler when disposing the player or switching sources.. * (no cleanup is needed when supporting the format natively) */ Html5.nativeSourceHandler.dispose = function () {}; // Register the native source handler Html5.registerSourceHandler(Html5.nativeSourceHandler); /* * Check if the volume can be changed in this browser/device. * Volume cannot be changed in a lot of mobile devices. * Specifically, it can't be changed from 1 on iOS. * * @return {Boolean} */ Html5.canControlVolume = function () { var volume = Html5.TEST_VID.volume; Html5.TEST_VID.volume = volume / 2 + 0.1; return volume !== Html5.TEST_VID.volume; }; /* * Check if playbackRate is supported in this browser/device. * * @return {Number} [description] */ Html5.canControlPlaybackRate = function () { var playbackRate = Html5.TEST_VID.playbackRate; Html5.TEST_VID.playbackRate = playbackRate / 2 + 0.1; return playbackRate !== Html5.TEST_VID.playbackRate; }; /* * Check to see if native text tracks are supported by this browser/device * * @return {Boolean} */ Html5.supportsNativeTextTracks = function () { var supportsTextTracks; // Figure out native text track support // If mode is a number, we cannot change it because it'll disappear from view. // Browsers with numeric modes include IE10 and older (<=2013) samsung android models. // Firefox isn't playing nice either with modifying the mode // TODO: Investigate firefox: https://github.com/videojs/video.js/issues/1862 supportsTextTracks = !!Html5.TEST_VID.textTracks; if (supportsTextTracks && Html5.TEST_VID.textTracks.length > 0) { supportsTextTracks = typeof Html5.TEST_VID.textTracks[0]['mode'] !== 'number'; } if (supportsTextTracks && browser.IS_FIREFOX) { supportsTextTracks = false; } if (supportsTextTracks && !('onremovetrack' in Html5.TEST_VID.textTracks)) { supportsTextTracks = false; } return supportsTextTracks; }; /** * An array of events available on the Html5 tech. * * @private * @type {Array} */ Html5.Events = ['loadstart', 'suspend', 'abort', 'error', 'emptied', 'stalled', 'loadedmetadata', 'loadeddata', 'canplay', 'canplaythrough', 'playing', 'waiting', 'seeking', 'seeked', 'ended', 'durationchange', 'timeupdate', 'progress', 'play', 'pause', 'ratechange', 'volumechange']; /* * Set the tech's volume control support status * * @type {Boolean} */ Html5.prototype['featuresVolumeControl'] = Html5.canControlVolume(); /* * Set the tech's playbackRate support status * * @type {Boolean} */ Html5.prototype['featuresPlaybackRate'] = Html5.canControlPlaybackRate(); /* * Set the tech's status on moving the video element. * In iOS, if you move a video element in the DOM, it breaks video playback. * * @type {Boolean} */ Html5.prototype['movingMediaElementInDOM'] = !browser.IS_IOS; /* * Set the the tech's fullscreen resize support status. * HTML video is able to automatically resize when going to fullscreen. * (No longer appears to be used. Can probably be removed.) */ Html5.prototype['featuresFullscreenResize'] = true; /* * Set the tech's progress event support status * (this disables the manual progress events of the Tech) */ Html5.prototype['featuresProgressEvents'] = true; /* * Sets the tech's status on native text track support * * @type {Boolean} */ Html5.prototype['featuresNativeTextTracks'] = Html5.supportsNativeTextTracks(); // HTML5 Feature detection and Device Fixes --------------------------------- // var canPlayType = undefined; var mpegurlRE = /^application\/(?:x-|vnd\.apple\.)mpegurl/i; var mp4RE = /^video\/mp4/i; Html5.patchCanPlayType = function () { // Android 4.0 and above can play HLS to some extent but it reports being unable to do so if (browser.ANDROID_VERSION >= 4.0) { if (!canPlayType) { canPlayType = Html5.TEST_VID.constructor.prototype.canPlayType; } Html5.TEST_VID.constructor.prototype.canPlayType = function (type) { if (type && mpegurlRE.test(type)) { return 'maybe'; } return canPlayType.call(this, type); }; } // Override Android 2.2 and less canPlayType method which is broken if (browser.IS_OLD_ANDROID) { if (!canPlayType) { canPlayType = Html5.TEST_VID.constructor.prototype.canPlayType; } Html5.TEST_VID.constructor.prototype.canPlayType = function (type) { if (type && mp4RE.test(type)) { return 'maybe'; } return canPlayType.call(this, type); }; } }; Html5.unpatchCanPlayType = function () { var r = Html5.TEST_VID.constructor.prototype.canPlayType; Html5.TEST_VID.constructor.prototype.canPlayType = canPlayType; canPlayType = null; return r; }; // by default, patch the video element Html5.patchCanPlayType(); Html5.disposeMediaElement = function (el) { if (!el) { return; } if (el.parentNode) { el.parentNode.removeChild(el); } // remove any child track or source nodes to prevent their loading while (el.hasChildNodes()) { el.removeChild(el.firstChild); } // remove any src reference. not setting `src=''` because that causes a warning // in firefox el.removeAttribute('src'); // force the media element to update its loading state by calling load() // however IE on Windows 7N has a bug that throws an error so need a try/catch (#793) if (typeof el.load === 'function') { // wrapping in an iife so it's not deoptimized (#1060#discussion_r10324473) (function () { try { el.load(); } catch (e) { // not supported } })(); } }; _component2['default'].registerComponent('Html5', Html5); exports['default'] = Html5; module.exports = exports['default']; },{"../component":48,"../utils/browser.js":104,"../utils/dom.js":107,"../utils/fn.js":109,"../utils/log.js":112,"../utils/merge-options.js":113,"../utils/url.js":117,"./tech.js":96,"global/document":1,"global/window":2,"object.assign":40}],95:[function(_dereq_,module,exports){ /** * @file loader.js */ 'use strict'; exports.__esModule = true; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var _component = _dereq_('../component'); var _component2 = _interopRequireDefault(_component); var _globalWindow = _dereq_('global/window'); var _globalWindow2 = _interopRequireDefault(_globalWindow); var _utilsToTitleCaseJs = _dereq_('../utils/to-title-case.js'); var _utilsToTitleCaseJs2 = _interopRequireDefault(_utilsToTitleCaseJs); /** * The Media Loader is the component that decides which playback technology to load * when the player is initialized. * * @param {Object} player Main Player * @param {Object=} options Object of option names and values * @param {Function=} ready Ready callback function * @extends Component * @class MediaLoader */ var MediaLoader = (function (_Component) { _inherits(MediaLoader, _Component); function MediaLoader(player, options, ready) { _classCallCheck(this, MediaLoader); _Component.call(this, player, options, ready); // If there are no sources when the player is initialized, // load the first supported playback technology. if (!options.playerOptions['sources'] || options.playerOptions['sources'].length === 0) { for (var i = 0, j = options.playerOptions['techOrder']; i < j.length; i++) { var techName = _utilsToTitleCaseJs2['default'](j[i]); var tech = _component2['default'].getComponent(techName); // Check if the browser supports this technology if (tech && tech.isSupported()) { player.loadTech(techName); break; } } } else { // // Loop through playback technologies (HTML5, Flash) and check for support. // // Then load the best source. // // A few assumptions here: // // All playback technologies respect preload false. player.src(options.playerOptions['sources']); } } return MediaLoader; })(_component2['default']); _component2['default'].registerComponent('MediaLoader', MediaLoader); exports['default'] = MediaLoader; module.exports = exports['default']; },{"../component":48,"../utils/to-title-case.js":116,"global/window":2}],96:[function(_dereq_,module,exports){ /** * @file tech.js * Media Technology Controller - Base class for media playback * technology controllers like Flash and HTML5 */ 'use strict'; exports.__esModule = true; function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj['default'] = obj; return newObj; } } function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var _component = _dereq_('../component'); var _component2 = _interopRequireDefault(_component); var _tracksTextTrack = _dereq_('../tracks/text-track'); var _tracksTextTrack2 = _interopRequireDefault(_tracksTextTrack); var _tracksTextTrackList = _dereq_('../tracks/text-track-list'); var _tracksTextTrackList2 = _interopRequireDefault(_tracksTextTrackList); var _utilsFnJs = _dereq_('../utils/fn.js'); var Fn = _interopRequireWildcard(_utilsFnJs); var _utilsLogJs = _dereq_('../utils/log.js'); var _utilsLogJs2 = _interopRequireDefault(_utilsLogJs); var _utilsTimeRangesJs = _dereq_('../utils/time-ranges.js'); var _utilsBufferJs = _dereq_('../utils/buffer.js'); var _mediaErrorJs = _dereq_('../media-error.js'); var _mediaErrorJs2 = _interopRequireDefault(_mediaErrorJs); var _globalWindow = _dereq_('global/window'); var _globalWindow2 = _interopRequireDefault(_globalWindow); var _globalDocument = _dereq_('global/document'); var _globalDocument2 = _interopRequireDefault(_globalDocument); /** * Base class for media (HTML5 Video, Flash) controllers * * @param {Object=} options Options object * @param {Function=} ready Ready callback function * @extends Component * @class Tech */ var Tech = (function (_Component) { _inherits(Tech, _Component); function Tech() { var options = arguments.length <= 0 || arguments[0] === undefined ? {} : arguments[0]; var ready = arguments.length <= 1 || arguments[1] === undefined ? function () {} : arguments[1]; _classCallCheck(this, Tech); // we don't want the tech to report user activity automatically. // This is done manually in addControlsListeners options.reportTouchActivity = false; _Component.call(this, null, options, ready); // keep track of whether the current source has played at all to // implement a very limited played() this.hasStarted_ = false; this.on('playing', function () { this.hasStarted_ = true; }); this.on('loadstart', function () { this.hasStarted_ = false; }); this.textTracks_ = options.textTracks; // Manually track progress in cases where the browser/flash player doesn't report it. if (!this.featuresProgressEvents) { this.manualProgressOn(); } // Manually track timeupdates in cases where the browser/flash player doesn't report it. if (!this.featuresTimeupdateEvents) { this.manualTimeUpdatesOn(); } this.initControlsListeners(); if (options.nativeCaptions === false || options.nativeTextTracks === false) { this.featuresNativeTextTracks = false; } if (!this.featuresNativeTextTracks) { this.emulateTextTracks(); } this.initTextTrackListeners(); // Turn on component tap events this.emitTapEvents(); } /* * List of associated text tracks * * @type {Array} * @private */ /** * Set up click and touch listeners for the playback element * On desktops, a click on the video itself will toggle playback, * on a mobile device a click on the video toggles controls. * (toggling controls is done by toggling the user state between active and * inactive) * A tap can signal that a user has become active, or has become inactive * e.g. a quick tap on an iPhone movie should reveal the controls. Another * quick tap should hide them again (signaling the user is in an inactive * viewing state) * In addition to this, we still want the user to be considered inactive after * a few seconds of inactivity. * Note: the only part of iOS interaction we can't mimic with this setup * is a touch and hold on the video element counting as activity in order to * keep the controls showing, but that shouldn't be an issue. A touch and hold on * any controls will still keep the user active * * @method initControlsListeners */ Tech.prototype.initControlsListeners = function initControlsListeners() { // if we're loading the playback object after it has started loading or playing the // video (often with autoplay on) then the loadstart event has already fired and we // need to fire it manually because many things rely on it. // Long term we might consider how we would do this for other events like 'canplay' // that may also have fired. this.ready(function () { if (this.networkState && this.networkState() > 0) { this.trigger('loadstart'); } // Allow the tech ready event to handle synchronisity }, true); }; /* Fallbacks for unsupported event types ================================================================================ */ // Manually trigger progress events based on changes to the buffered amount // Many flash players and older HTML5 browsers don't send progress or progress-like events /** * Turn on progress events * * @method manualProgressOn */ Tech.prototype.manualProgressOn = function manualProgressOn() { this.on('durationchange', this.onDurationChange); this.manualProgress = true; // Trigger progress watching when a source begins loading this.one('ready', this.trackProgress); }; /** * Turn off progress events * * @method manualProgressOff */ Tech.prototype.manualProgressOff = function manualProgressOff() { this.manualProgress = false; this.stopTrackingProgress(); this.off('durationchange', this.onDurationChange); }; /** * Track progress * * @method trackProgress */ Tech.prototype.trackProgress = function trackProgress() { this.stopTrackingProgress(); this.progressInterval = this.setInterval(Fn.bind(this, function () { // Don't trigger unless buffered amount is greater than last time var numBufferedPercent = this.bufferedPercent(); if (this.bufferedPercent_ !== numBufferedPercent) { this.trigger('progress'); } this.bufferedPercent_ = numBufferedPercent; if (numBufferedPercent === 1) { this.stopTrackingProgress(); } }), 500); }; /** * Update duration * * @method onDurationChange */ Tech.prototype.onDurationChange = function onDurationChange() { this.duration_ = this.duration(); }; /** * Create and get TimeRange object for buffering * * @return {TimeRangeObject} * @method buffered */ Tech.prototype.buffered = function buffered() { return _utilsTimeRangesJs.createTimeRange(0, 0); }; /** * Get buffered percent * * @return {Number} * @method bufferedPercent */ Tech.prototype.bufferedPercent = function bufferedPercent() { return _utilsBufferJs.bufferedPercent(this.buffered(), this.duration_); }; /** * Stops tracking progress by clearing progress interval * * @method stopTrackingProgress */ Tech.prototype.stopTrackingProgress = function stopTrackingProgress() { this.clearInterval(this.progressInterval); }; /*! Time Tracking -------------------------------------------------------------- */ /** * Set event listeners for on play and pause and tracking current time * * @method manualTimeUpdatesOn */ Tech.prototype.manualTimeUpdatesOn = function manualTimeUpdatesOn() { this.manualTimeUpdates = true; this.on('play', this.trackCurrentTime); this.on('pause', this.stopTrackingCurrentTime); }; /** * Remove event listeners for on play and pause and tracking current time * * @method manualTimeUpdatesOff */ Tech.prototype.manualTimeUpdatesOff = function manualTimeUpdatesOff() { this.manualTimeUpdates = false; this.stopTrackingCurrentTime(); this.off('play', this.trackCurrentTime); this.off('pause', this.stopTrackingCurrentTime); }; /** * Tracks current time * * @method trackCurrentTime */ Tech.prototype.trackCurrentTime = function trackCurrentTime() { if (this.currentTimeInterval) { this.stopTrackingCurrentTime(); } this.currentTimeInterval = this.setInterval(function () { this.trigger({ type: 'timeupdate', target: this, manuallyTriggered: true }); }, 250); // 42 = 24 fps // 250 is what Webkit uses // FF uses 15 }; /** * Turn off play progress tracking (when paused or dragging) * * @method stopTrackingCurrentTime */ Tech.prototype.stopTrackingCurrentTime = function stopTrackingCurrentTime() { this.clearInterval(this.currentTimeInterval); // #1002 - if the video ends right before the next timeupdate would happen, // the progress bar won't make it all the way to the end this.trigger({ type: 'timeupdate', target: this, manuallyTriggered: true }); }; /** * Turn off any manual progress or timeupdate tracking * * @method dispose */ Tech.prototype.dispose = function dispose() { // clear out text tracks because we can't reuse them between techs var textTracks = this.textTracks(); if (textTracks) { var i = textTracks.length; while (i--) { this.removeRemoteTextTrack(textTracks[i]); } } // Turn off any manual progress or timeupdate tracking if (this.manualProgress) { this.manualProgressOff(); } if (this.manualTimeUpdates) { this.manualTimeUpdatesOff(); } _Component.prototype.dispose.call(this); }; /** * When invoked without an argument, returns a MediaError object * representing the current error state of the player or null if * there is no error. When invoked with an argument, set the current * error state of the player. * @param {MediaError=} err Optional an error object * @return {MediaError} the current error object or null * @method error */ Tech.prototype.error = function error(err) { if (err !== undefined) { if (err instanceof _mediaErrorJs2['default']) { this.error_ = err; } else { this.error_ = new _mediaErrorJs2['default'](err); } this.trigger('error'); } return this.error_; }; /** * Return the time ranges that have been played through for the * current source. This implementation is incomplete. It does not * track the played time ranges, only whether the source has played * at all or not. * @return {TimeRangeObject} a single time range if this video has * played or an empty set of ranges if not. * @method played */ Tech.prototype.played = function played() { if (this.hasStarted_) { return _utilsTimeRangesJs.createTimeRange(0, 0); } return _utilsTimeRangesJs.createTimeRange(); }; /** * Set current time * * @method setCurrentTime */ Tech.prototype.setCurrentTime = function setCurrentTime() { // improve the accuracy of manual timeupdates if (this.manualTimeUpdates) { this.trigger({ type: 'timeupdate', target: this, manuallyTriggered: true }); } }; /** * Initialize texttrack listeners * * @method initTextTrackListeners */ Tech.prototype.initTextTrackListeners = function initTextTrackListeners() { var textTrackListChanges = Fn.bind(this, function () { this.trigger('texttrackchange'); }); var tracks = this.textTracks(); if (!tracks) return; tracks.addEventListener('removetrack', textTrackListChanges); tracks.addEventListener('addtrack', textTrackListChanges); this.on('dispose', Fn.bind(this, function () { tracks.removeEventListener('removetrack', textTrackListChanges); tracks.removeEventListener('addtrack', textTrackListChanges); })); }; /** * Emulate texttracks * * @method emulateTextTracks */ Tech.prototype.emulateTextTracks = function emulateTextTracks() { if (!_globalWindow2['default']['WebVTT'] && this.el().parentNode != null) { var script = _globalDocument2['default'].createElement('script'); script.src = this.options_['vtt.js'] || '../node_modules/vtt.js/dist/vtt.js'; this.el().parentNode.appendChild(script); _globalWindow2['default']['WebVTT'] = true; } var tracks = this.textTracks(); if (!tracks) { return; } var textTracksChanges = Fn.bind(this, function () { var _this = this; var updateDisplay = function updateDisplay() { return _this.trigger('texttrackchange'); }; updateDisplay(); for (var i = 0; i < tracks.length; i++) { var track = tracks[i]; track.removeEventListener('cuechange', updateDisplay); if (track.mode === 'showing') { track.addEventListener('cuechange', updateDisplay); } } }); tracks.addEventListener('change', textTracksChanges); this.on('dispose', function () { tracks.removeEventListener('change', textTracksChanges); }); }; /* * Provide default methods for text tracks. * * Html5 tech overrides these. */ /** * Get texttracks * * @returns {TextTrackList} * @method textTracks */ Tech.prototype.textTracks = function textTracks() { this.textTracks_ = this.textTracks_ || new _tracksTextTrackList2['default'](); return this.textTracks_; }; /** * Get remote texttracks * * @returns {TextTrackList} * @method remoteTextTracks */ Tech.prototype.remoteTextTracks = function remoteTextTracks() { this.remoteTextTracks_ = this.remoteTextTracks_ || new _tracksTextTrackList2['default'](); return this.remoteTextTracks_; }; /** * Creates and returns a remote text track object * * @param {String} kind Text track kind (subtitles, captions, descriptions * chapters and metadata) * @param {String=} label Label to identify the text track * @param {String=} language Two letter language abbreviation * @return {TextTrackObject} * @method addTextTrack */ Tech.prototype.addTextTrack = function addTextTrack(kind, label, language) { if (!kind) { throw new Error('TextTrack kind is required but was not provided'); } return createTrackHelper(this, kind, label, language); }; /** * Creates and returns a remote text track object * * @param {Object} options The object should contain values for * kind, language, label and src (location of the WebVTT file) * @return {TextTrackObject} * @method addRemoteTextTrack */ Tech.prototype.addRemoteTextTrack = function addRemoteTextTrack(options) { var track = createTrackHelper(this, options.kind, options.label, options.language, options); this.remoteTextTracks().addTrack_(track); return { track: track }; }; /** * Remove remote texttrack * * @param {TextTrackObject} track Texttrack to remove * @method removeRemoteTextTrack */ Tech.prototype.removeRemoteTextTrack = function removeRemoteTextTrack(track) { this.textTracks().removeTrack_(track); this.remoteTextTracks().removeTrack_(track); }; /** * Provide a default setPoster method for techs * Poster support for techs should be optional, so we don't want techs to * break if they don't have a way to set a poster. * * @method setPoster */ Tech.prototype.setPoster = function setPoster() {}; return Tech; })(_component2['default']); Tech.prototype.textTracks_; var createTrackHelper = function createTrackHelper(self, kind, label, language) { var options = arguments.length <= 4 || arguments[4] === undefined ? {} : arguments[4]; var tracks = self.textTracks(); options.kind = kind; if (label) { options.label = label; } if (language) { options.language = language; } options.tech = self; var track = new _tracksTextTrack2['default'](options); tracks.addTrack_(track); return track; }; Tech.prototype.featuresVolumeControl = true; // Resizing plugins using request fullscreen reloads the plugin Tech.prototype.featuresFullscreenResize = false; Tech.prototype.featuresPlaybackRate = false; // Optional events that we can manually mimic with timers // currently not triggered by video-js-swf Tech.prototype.featuresProgressEvents = false; Tech.prototype.featuresTimeupdateEvents = false; Tech.prototype.featuresNativeTextTracks = false; /* * A functional mixin for techs that want to use the Source Handler pattern. * * ##### EXAMPLE: * * Tech.withSourceHandlers.call(MyTech); * */ Tech.withSourceHandlers = function (_Tech) { /* * Register a source handler * Source handlers are scripts for handling specific formats. * The source handler pattern is used for adaptive formats (HLS, DASH) that * manually load video data and feed it into a Source Buffer (Media Source Extensions) * @param {Function} handler The source handler * @param {Boolean} first Register it before any existing handlers */ _Tech.registerSourceHandler = function (handler, index) { var handlers = _Tech.sourceHandlers; if (!handlers) { handlers = _Tech.sourceHandlers = []; } if (index === undefined) { // add to the end of the list index = handlers.length; } handlers.splice(index, 0, handler); }; /* * Return the first source handler that supports the source * TODO: Answer question: should 'probably' be prioritized over 'maybe' * @param {Object} source The source object * @returns {Object} The first source handler that supports the source * @returns {null} Null if no source handler is found */ _Tech.selectSourceHandler = function (source) { var handlers = _Tech.sourceHandlers || []; var can = undefined; for (var i = 0; i < handlers.length; i++) { can = handlers[i].canHandleSource(source); if (can) { return handlers[i]; } } return null; }; /* * Check if the tech can support the given source * @param {Object} srcObj The source object * @return {String} 'probably', 'maybe', or '' (empty string) */ _Tech.canPlaySource = function (srcObj) { var sh = _Tech.selectSourceHandler(srcObj); if (sh) { return sh.canHandleSource(srcObj); } return ''; }; var originalSeekable = _Tech.prototype.seekable; // when a source handler is registered, prefer its implementation of // seekable when present. _Tech.prototype.seekable = function () { if (this.sourceHandler_ && this.sourceHandler_.seekable) { return this.sourceHandler_.seekable(); } return originalSeekable.call(this); }; /* * Create a function for setting the source using a source object * and source handlers. * Should never be called unless a source handler was found. * @param {Object} source A source object with src and type keys * @return {Tech} self */ _Tech.prototype.setSource = function (source) { var sh = _Tech.selectSourceHandler(source); if (!sh) { // Fall back to a native source hander when unsupported sources are // deliberately set if (_Tech.nativeSourceHandler) { sh = _Tech.nativeSourceHandler; } else { _utilsLogJs2['default'].error('No source hander found for the current source.'); } } // Dispose any existing source handler this.disposeSourceHandler(); this.off('dispose', this.disposeSourceHandler); this.currentSource_ = source; this.sourceHandler_ = sh.handleSource(source, this); this.on('dispose', this.disposeSourceHandler); return this; }; /* * Clean up any existing source handler */ _Tech.prototype.disposeSourceHandler = function () { if (this.sourceHandler_ && this.sourceHandler_.dispose) { this.sourceHandler_.dispose(); } }; }; _component2['default'].registerComponent('Tech', Tech); // Old name for Tech _component2['default'].registerComponent('MediaTechController', Tech); exports['default'] = Tech; module.exports = exports['default']; },{"../component":48,"../media-error.js":83,"../tracks/text-track":103,"../tracks/text-track-list":101,"../utils/buffer.js":105,"../utils/fn.js":109,"../utils/log.js":112,"../utils/time-ranges.js":115,"global/document":1,"global/window":2}],97:[function(_dereq_,module,exports){ /** * @file text-track-cue-list.js */ 'use strict'; exports.__esModule = true; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj['default'] = obj; return newObj; } } var _utilsBrowserJs = _dereq_('../utils/browser.js'); var browser = _interopRequireWildcard(_utilsBrowserJs); var _globalDocument = _dereq_('global/document'); var _globalDocument2 = _interopRequireDefault(_globalDocument); /* * https://html.spec.whatwg.org/multipage/embedded-content.html#texttrackcuelist * * interface TextTrackCueList { * readonly attribute unsigned long length; * getter TextTrackCue (unsigned long index); * TextTrackCue? getCueById(DOMString id); * }; */ var TextTrackCueList = function TextTrackCueList(cues) { var list = this; if (browser.IS_IE8) { list = _globalDocument2['default'].createElement('custom'); for (var prop in TextTrackCueList.prototype) { list[prop] = TextTrackCueList.prototype[prop]; } } TextTrackCueList.prototype.setCues_.call(list, cues); Object.defineProperty(list, 'length', { get: function get() { return this.length_; } }); if (browser.IS_IE8) { return list; } }; TextTrackCueList.prototype.setCues_ = function (cues) { var oldLength = this.length || 0; var i = 0; var l = cues.length; this.cues_ = cues; this.length_ = cues.length; var defineProp = function defineProp(i) { if (!('' + i in this)) { Object.defineProperty(this, '' + i, { get: function get() { return this.cues_[i]; } }); } }; if (oldLength < l) { i = oldLength; for (; i < l; i++) { defineProp.call(this, i); } } }; TextTrackCueList.prototype.getCueById = function (id) { var result = null; for (var i = 0, l = this.length; i < l; i++) { var cue = this[i]; if (cue.id === id) { result = cue; break; } } return result; }; exports['default'] = TextTrackCueList; module.exports = exports['default']; },{"../utils/browser.js":104,"global/document":1}],98:[function(_dereq_,module,exports){ /** * @file text-track-display.js */ 'use strict'; exports.__esModule = true; function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj['default'] = obj; return newObj; } } function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var _component = _dereq_('../component'); var _component2 = _interopRequireDefault(_component); var _menuMenuJs = _dereq_('../menu/menu.js'); var _menuMenuJs2 = _interopRequireDefault(_menuMenuJs); var _menuMenuItemJs = _dereq_('../menu/menu-item.js'); var _menuMenuItemJs2 = _interopRequireDefault(_menuMenuItemJs); var _menuMenuButtonJs = _dereq_('../menu/menu-button.js'); var _menuMenuButtonJs2 = _interopRequireDefault(_menuMenuButtonJs); var _utilsFnJs = _dereq_('../utils/fn.js'); var Fn = _interopRequireWildcard(_utilsFnJs); var _globalDocument = _dereq_('global/document'); var _globalDocument2 = _interopRequireDefault(_globalDocument); var _globalWindow = _dereq_('global/window'); var _globalWindow2 = _interopRequireDefault(_globalWindow); var darkGray = '#222'; var lightGray = '#ccc'; var fontMap = { monospace: 'monospace', sansSerif: 'sans-serif', serif: 'serif', monospaceSansSerif: '"Andale Mono", "Lucida Console", monospace', monospaceSerif: '"Courier New", monospace', proportionalSansSerif: 'sans-serif', proportionalSerif: 'serif', casual: '"Comic Sans MS", Impact, fantasy', script: '"Monotype Corsiva", cursive', smallcaps: '"Andale Mono", "Lucida Console", monospace, sans-serif' }; /** * The component for displaying text track cues * * @param {Object} player Main Player * @param {Object=} options Object of option names and values * @param {Function=} ready Ready callback function * @extends Component * @class TextTrackDisplay */ var TextTrackDisplay = (function (_Component) { _inherits(TextTrackDisplay, _Component); function TextTrackDisplay(player, options, ready) { _classCallCheck(this, TextTrackDisplay); _Component.call(this, player, options, ready); player.on('loadstart', Fn.bind(this, this.toggleDisplay)); player.on('texttrackchange', Fn.bind(this, this.updateDisplay)); // This used to be called during player init, but was causing an error // if a track should show by default and the display hadn't loaded yet. // Should probably be moved to an external track loader when we support // tracks that don't need a display. player.ready(Fn.bind(this, function () { if (player.tech && player.tech['featuresNativeTextTracks']) { this.hide(); return; } player.on('fullscreenchange', Fn.bind(this, this.updateDisplay)); var tracks = this.options_.playerOptions['tracks'] || []; for (var i = 0; i < tracks.length; i++) { var track = tracks[i]; this.player_.addRemoteTextTrack(track); } })); } /** * Add cue HTML to display * * @param {Number} color Hex number for color, like #f0e * @param {Number} opacity Value for opacity,0.0 - 1.0 * @return {RGBAColor} In the form 'rgba(255, 0, 0, 0.3)' * @method constructColor */ /** * Toggle display texttracks * * @method toggleDisplay */ TextTrackDisplay.prototype.toggleDisplay = function toggleDisplay() { if (this.player_.tech && this.player_.tech['featuresNativeTextTracks']) { this.hide(); } else { this.show(); } }; /** * Create the component's DOM element * * @return {Element} * @method createEl */ TextTrackDisplay.prototype.createEl = function createEl() { return _Component.prototype.createEl.call(this, 'div', { className: 'vjs-text-track-display' }); }; /** * Clear display texttracks * * @method clearDisplay */ TextTrackDisplay.prototype.clearDisplay = function clearDisplay() { if (typeof _globalWindow2['default']['WebVTT'] === 'function') { _globalWindow2['default']['WebVTT']['processCues'](_globalWindow2['default'], [], this.el_); } }; /** * Update display texttracks * * @method updateDisplay */ TextTrackDisplay.prototype.updateDisplay = function updateDisplay() { var tracks = this.player_.textTracks(); this.clearDisplay(); if (!tracks) { return; } for (var i = 0; i < tracks.length; i++) { var track = tracks[i]; if (track['mode'] === 'showing') { this.updateForTrack(track); } } }; /** * Add texttrack to texttrack list * * @param {TextTrackObject} track Texttrack object to be added to list * @method updateForTrack */ TextTrackDisplay.prototype.updateForTrack = function updateForTrack(track) { if (typeof _globalWindow2['default']['WebVTT'] !== 'function' || !track['activeCues']) { return; } var overrides = this.player_['textTrackSettings'].getValues(); var cues = []; for (var _i = 0; _i < track['activeCues'].length; _i++) { cues.push(track['activeCues'][_i]); } _globalWindow2['default']['WebVTT']['processCues'](_globalWindow2['default'], track['activeCues'], this.el_); var i = cues.length; while (i--) { var cueDiv = cues[i].displayState; if (overrides.color) { cueDiv.firstChild.style.color = overrides.color; } if (overrides.textOpacity) { tryUpdateStyle(cueDiv.firstChild, 'color', constructColor(overrides.color || '#fff', overrides.textOpacity)); } if (overrides.backgroundColor) { cueDiv.firstChild.style.backgroundColor = overrides.backgroundColor; } if (overrides.backgroundOpacity) { tryUpdateStyle(cueDiv.firstChild, 'backgroundColor', constructColor(overrides.backgroundColor || '#000', overrides.backgroundOpacity)); } if (overrides.windowColor) { if (overrides.windowOpacity) { tryUpdateStyle(cueDiv, 'backgroundColor', constructColor(overrides.windowColor, overrides.windowOpacity)); } else { cueDiv.style.backgroundColor = overrides.windowColor; } } if (overrides.edgeStyle) { if (overrides.edgeStyle === 'dropshadow') { cueDiv.firstChild.style.textShadow = '2px 2px 3px ' + darkGray + ', 2px 2px 4px ' + darkGray + ', 2px 2px 5px ' + darkGray; } else if (overrides.edgeStyle === 'raised') { cueDiv.firstChild.style.textShadow = '1px 1px ' + darkGray + ', 2px 2px ' + darkGray + ', 3px 3px ' + darkGray; } else if (overrides.edgeStyle === 'depressed') { cueDiv.firstChild.style.textShadow = '1px 1px ' + lightGray + ', 0 1px ' + lightGray + ', -1px -1px ' + darkGray + ', 0 -1px ' + darkGray; } else if (overrides.edgeStyle === 'uniform') { cueDiv.firstChild.style.textShadow = '0 0 4px ' + darkGray + ', 0 0 4px ' + darkGray + ', 0 0 4px ' + darkGray + ', 0 0 4px ' + darkGray; } } if (overrides.fontPercent && overrides.fontPercent !== 1) { var fontSize = _globalWindow2['default'].parseFloat(cueDiv.style.fontSize); cueDiv.style.fontSize = fontSize * overrides.fontPercent + 'px'; cueDiv.style.height = 'auto'; cueDiv.style.top = 'auto'; cueDiv.style.bottom = '2px'; } if (overrides.fontFamily && overrides.fontFamily !== 'default') { if (overrides.fontFamily === 'small-caps') { cueDiv.firstChild.style.fontVariant = 'small-caps'; } else { cueDiv.firstChild.style.fontFamily = fontMap[overrides.fontFamily]; } } } }; return TextTrackDisplay; })(_component2['default']); function constructColor(color, opacity) { return 'rgba(' + // color looks like "#f0e" parseInt(color[1] + color[1], 16) + ',' + parseInt(color[2] + color[2], 16) + ',' + parseInt(color[3] + color[3], 16) + ',' + opacity + ')'; } /** * Try to update style * Some style changes will throw an error, particularly in IE8. Those should be noops. * * @param {Element} el The element to be styles * @param {CSSProperty} style The CSS property to be styled * @param {CSSStyle} rule The actual style to be applied to the property * @method tryUpdateStyle */ function tryUpdateStyle(el, style, rule) { // try { el.style[style] = rule; } catch (e) {} } _component2['default'].registerComponent('TextTrackDisplay', TextTrackDisplay); exports['default'] = TextTrackDisplay; module.exports = exports['default']; },{"../component":48,"../menu/menu-button.js":84,"../menu/menu-item.js":85,"../menu/menu.js":86,"../utils/fn.js":109,"global/document":1,"global/window":2}],99:[function(_dereq_,module,exports){ /** * @file text-track-enums.js * * https://html.spec.whatwg.org/multipage/embedded-content.html#texttrackmode * * enum TextTrackMode { "disabled", "hidden", "showing" }; */ 'use strict'; exports.__esModule = true; var TextTrackMode = { 'disabled': 'disabled', 'hidden': 'hidden', 'showing': 'showing' }; /* * https://html.spec.whatwg.org/multipage/embedded-content.html#texttrackkind * * enum TextTrackKind { "subtitles", "captions", "descriptions", "chapters", "metadata" }; */ var TextTrackKind = { 'subtitles': 'subtitles', 'captions': 'captions', 'descriptions': 'descriptions', 'chapters': 'chapters', 'metadata': 'metadata' }; exports.TextTrackMode = TextTrackMode; exports.TextTrackKind = TextTrackKind; },{}],100:[function(_dereq_,module,exports){ /** * Utilities for capturing text track state and re-creating tracks * based on a capture. * * @file text-track-list-converter.js */ /** * Examine a single text track and return a JSON-compatible javascript * object that represents the text track's state. * @param track {TextTrackObject} the text track to query * @return {Object} a serializable javascript representation of the * @private */ 'use strict'; exports.__esModule = true; var trackToJson_ = function trackToJson_(track) { return { kind: track.kind, label: track.label, language: track.language, id: track.id, inBandMetadataTrackDispatchType: track.inBandMetadataTrackDispatchType, mode: track.mode, cues: track.cues && Array.prototype.map.call(track.cues, function (cue) { return { startTime: cue.startTime, endTime: cue.endTime, text: cue.text, id: cue.id }; }), src: track.src }; }; /** * Examine a tech and return a JSON-compatible javascript array that * represents the state of all text tracks currently configured. The * return array is compatible with `jsonToTextTracks`. * @param tech {tech} the tech object to query * @return {Array} a serializable javascript representation of the * @function textTracksToJson */ var textTracksToJson = function textTracksToJson(tech) { var trackEls = tech.el().querySelectorAll('track'); var trackObjs = Array.prototype.map.call(trackEls, function (t) { return t.track; }); var tracks = Array.prototype.map.call(trackEls, function (trackEl) { var json = trackToJson_(trackEl.track); json.src = trackEl.src; return json; }); return tracks.concat(Array.prototype.filter.call(tech.textTracks(), function (track) { return trackObjs.indexOf(track) === -1; }).map(trackToJson_)); }; /** * Creates a set of remote text tracks on a tech based on an array of * javascript text track representations. * @param json {Array} an array of text track representation objects, * like those that would be produced by `textTracksToJson` * @param tech {tech} the tech to create text tracks on * @function jsonToTextTracks */ var jsonToTextTracks = function jsonToTextTracks(json, tech) { json.forEach(function (track) { var addedTrack = tech.addRemoteTextTrack(track).track; if (!track.src && track.cues) { track.cues.forEach(function (cue) { return addedTrack.addCue(cue); }); } }); return tech.textTracks(); }; exports['default'] = { textTracksToJson: textTracksToJson, jsonToTextTracks: jsonToTextTracks, trackToJson_: trackToJson_ }; module.exports = exports['default']; },{}],101:[function(_dereq_,module,exports){ /** * @file text-track-list.js */ 'use strict'; exports.__esModule = true; function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj['default'] = obj; return newObj; } } function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } var _eventTarget = _dereq_('../event-target'); var _eventTarget2 = _interopRequireDefault(_eventTarget); var _utilsFnJs = _dereq_('../utils/fn.js'); var Fn = _interopRequireWildcard(_utilsFnJs); var _utilsBrowserJs = _dereq_('../utils/browser.js'); var browser = _interopRequireWildcard(_utilsBrowserJs); var _globalDocument = _dereq_('global/document'); var _globalDocument2 = _interopRequireDefault(_globalDocument); /* * https://html.spec.whatwg.org/multipage/embedded-content.html#texttracklist * * interface TextTrackList : EventTarget { * readonly attribute unsigned long length; * getter TextTrack (unsigned long index); * TextTrack? getTrackById(DOMString id); * * attribute EventHandler onchange; * attribute EventHandler onaddtrack; * attribute EventHandler onremovetrack; * }; */ var TextTrackList = function TextTrackList(tracks) { var list = this; if (browser.IS_IE8) { list = _globalDocument2['default'].createElement('custom'); for (var prop in TextTrackList.prototype) { list[prop] = TextTrackList.prototype[prop]; } } tracks = tracks || []; list.tracks_ = []; Object.defineProperty(list, 'length', { get: function get() { return this.tracks_.length; } }); for (var i = 0; i < tracks.length; i++) { list.addTrack_(tracks[i]); } if (browser.IS_IE8) { return list; } }; TextTrackList.prototype = Object.create(_eventTarget2['default'].prototype); TextTrackList.prototype.constructor = TextTrackList; /* * change - One or more tracks in the track list have been enabled or disabled. * addtrack - A track has been added to the track list. * removetrack - A track has been removed from the track list. */ TextTrackList.prototype.allowedEvents_ = { 'change': 'change', 'addtrack': 'addtrack', 'removetrack': 'removetrack' }; // emulate attribute EventHandler support to allow for feature detection for (var _event in TextTrackList.prototype.allowedEvents_) { TextTrackList.prototype['on' + _event] = null; } TextTrackList.prototype.addTrack_ = function (track) { var index = this.tracks_.length; if (!('' + index in this)) { Object.defineProperty(this, index, { get: function get() { return this.tracks_[index]; } }); } track.addEventListener('modechange', Fn.bind(this, function () { this.trigger('change'); })); this.tracks_.push(track); this.trigger({ type: 'addtrack', track: track }); }; TextTrackList.prototype.removeTrack_ = function (rtrack) { var result = null; var track = undefined; for (var i = 0, l = this.length; i < l; i++) { track = this[i]; if (track === rtrack) { this.tracks_.splice(i, 1); break; } } this.trigger({ type: 'removetrack', track: track }); }; TextTrackList.prototype.getTrackById = function (id) { var result = null; for (var i = 0, l = this.length; i < l; i++) { var track = this[i]; if (track.id === id) { result = track; break; } } return result; }; exports['default'] = TextTrackList; module.exports = exports['default']; },{"../event-target":79,"../utils/browser.js":104,"../utils/fn.js":109,"global/document":1}],102:[function(_dereq_,module,exports){ /** * @file text-track-settings.js */ 'use strict'; exports.__esModule = true; function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj['default'] = obj; return newObj; } } function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var _component = _dereq_('../component'); var _component2 = _interopRequireDefault(_component); var _utilsEventsJs = _dereq_('../utils/events.js'); var Events = _interopRequireWildcard(_utilsEventsJs); var _utilsFnJs = _dereq_('../utils/fn.js'); var Fn = _interopRequireWildcard(_utilsFnJs); var _utilsLogJs = _dereq_('../utils/log.js'); var _utilsLogJs2 = _interopRequireDefault(_utilsLogJs); var _safeJsonParseTuple = _dereq_('safe-json-parse/tuple'); var _safeJsonParseTuple2 = _interopRequireDefault(_safeJsonParseTuple); var _globalWindow = _dereq_('global/window'); var _globalWindow2 = _interopRequireDefault(_globalWindow); /** * Manipulate settings of texttracks * * @param {Object} player Main Player * @param {Object=} options Object of option names and values * @extends Component * @class TextTrackSettings */ var TextTrackSettings = (function (_Component) { _inherits(TextTrackSettings, _Component); function TextTrackSettings(player, options) { _classCallCheck(this, TextTrackSettings); _Component.call(this, player, options); this.hide(); // Grab `persistTextTrackSettings` from the player options if not passed in child options if (options.persistTextTrackSettings === undefined) { this.options_.persistTextTrackSettings = this.options_.playerOptions.persistTextTrackSettings; } Events.on(this.el().querySelector('.vjs-done-button'), 'click', Fn.bind(this, function () { this.saveSettings(); this.hide(); })); Events.on(this.el().querySelector('.vjs-default-button'), 'click', Fn.bind(this, function () { this.el().querySelector('.vjs-fg-color > select').selectedIndex = 0; this.el().querySelector('.vjs-bg-color > select').selectedIndex = 0; this.el().querySelector('.window-color > select').selectedIndex = 0; this.el().querySelector('.vjs-text-opacity > select').selectedIndex = 0; this.el().querySelector('.vjs-bg-opacity > select').selectedIndex = 0; this.el().querySelector('.vjs-window-opacity > select').selectedIndex = 0; this.el().querySelector('.vjs-edge-style select').selectedIndex = 0; this.el().querySelector('.vjs-font-family select').selectedIndex = 0; this.el().querySelector('.vjs-font-percent select').selectedIndex = 2; this.updateDisplay(); })); Events.on(this.el().querySelector('.vjs-fg-color > select'), 'change', Fn.bind(this, this.updateDisplay)); Events.on(this.el().querySelector('.vjs-bg-color > select'), 'change', Fn.bind(this, this.updateDisplay)); Events.on(this.el().querySelector('.window-color > select'), 'change', Fn.bind(this, this.updateDisplay)); Events.on(this.el().querySelector('.vjs-text-opacity > select'), 'change', Fn.bind(this, this.updateDisplay)); Events.on(this.el().querySelector('.vjs-bg-opacity > select'), 'change', Fn.bind(this, this.updateDisplay)); Events.on(this.el().querySelector('.vjs-window-opacity > select'), 'change', Fn.bind(this, this.updateDisplay)); Events.on(this.el().querySelector('.vjs-font-percent select'), 'change', Fn.bind(this, this.updateDisplay)); Events.on(this.el().querySelector('.vjs-edge-style select'), 'change', Fn.bind(this, this.updateDisplay)); Events.on(this.el().querySelector('.vjs-font-family select'), 'change', Fn.bind(this, this.updateDisplay)); if (this.options_.persistTextTrackSettings) { this.restoreSettings(); } } /** * Create the component's DOM element * * @return {Element} * @method createEl */ TextTrackSettings.prototype.createEl = function createEl() { return _Component.prototype.createEl.call(this, 'div', { className: 'vjs-caption-settings vjs-modal-overlay', innerHTML: captionOptionsMenuTemplate() }); }; /** * Get texttrack settings * Settings are * .vjs-edge-style * .vjs-font-family * .vjs-fg-color * .vjs-text-opacity * .vjs-bg-color * .vjs-bg-opacity * .window-color * .vjs-window-opacity * * @return {Object} * @method getValues */ TextTrackSettings.prototype.getValues = function getValues() { var el = this.el(); var textEdge = getSelectedOptionValue(el.querySelector('.vjs-edge-style select')); var fontFamily = getSelectedOptionValue(el.querySelector('.vjs-font-family select')); var fgColor = getSelectedOptionValue(el.querySelector('.vjs-fg-color > select')); var textOpacity = getSelectedOptionValue(el.querySelector('.vjs-text-opacity > select')); var bgColor = getSelectedOptionValue(el.querySelector('.vjs-bg-color > select')); var bgOpacity = getSelectedOptionValue(el.querySelector('.vjs-bg-opacity > select')); var windowColor = getSelectedOptionValue(el.querySelector('.window-color > select')); var windowOpacity = getSelectedOptionValue(el.querySelector('.vjs-window-opacity > select')); var fontPercent = _globalWindow2['default']['parseFloat'](getSelectedOptionValue(el.querySelector('.vjs-font-percent > select'))); var result = { 'backgroundOpacity': bgOpacity, 'textOpacity': textOpacity, 'windowOpacity': windowOpacity, 'edgeStyle': textEdge, 'fontFamily': fontFamily, 'color': fgColor, 'backgroundColor': bgColor, 'windowColor': windowColor, 'fontPercent': fontPercent }; for (var _name in result) { if (result[_name] === '' || result[_name] === 'none' || _name === 'fontPercent' && result[_name] === 1.00) { delete result[_name]; } } return result; }; /** * Set texttrack settings * Settings are * .vjs-edge-style * .vjs-font-family * .vjs-fg-color * .vjs-text-opacity * .vjs-bg-color * .vjs-bg-opacity * .window-color * .vjs-window-opacity * * @param {Object} values Object with texttrack setting values * @method setValues */ TextTrackSettings.prototype.setValues = function setValues(values) { var el = this.el(); setSelectedOption(el.querySelector('.vjs-edge-style select'), values.edgeStyle); setSelectedOption(el.querySelector('.vjs-font-family select'), values.fontFamily); setSelectedOption(el.querySelector('.vjs-fg-color > select'), values.color); setSelectedOption(el.querySelector('.vjs-text-opacity > select'), values.textOpacity); setSelectedOption(el.querySelector('.vjs-bg-color > select'), values.backgroundColor); setSelectedOption(el.querySelector('.vjs-bg-opacity > select'), values.backgroundOpacity); setSelectedOption(el.querySelector('.window-color > select'), values.windowColor); setSelectedOption(el.querySelector('.vjs-window-opacity > select'), values.windowOpacity); var fontPercent = values.fontPercent; if (fontPercent) { fontPercent = fontPercent.toFixed(2); } setSelectedOption(el.querySelector('.vjs-font-percent > select'), fontPercent); }; /** * Restore texttrack settings * * @method restoreSettings */ TextTrackSettings.prototype.restoreSettings = function restoreSettings() { var _safeParseTuple = _safeJsonParseTuple2['default'](_globalWindow2['default'].localStorage.getItem('vjs-text-track-settings')); var err = _safeParseTuple[0]; var values = _safeParseTuple[1]; if (err) { _utilsLogJs2['default'].error(err); } if (values) { this.setValues(values); } }; /** * Save texttrack settings to local storage * * @method saveSettings */ TextTrackSettings.prototype.saveSettings = function saveSettings() { if (!this.options_.persistTextTrackSettings) { return; } var values = this.getValues(); try { if (Object.getOwnPropertyNames(values).length > 0) { _globalWindow2['default'].localStorage.setItem('vjs-text-track-settings', JSON.stringify(values)); } else { _globalWindow2['default'].localStorage.removeItem('vjs-text-track-settings'); } } catch (e) {} }; /** * Update display of texttrack settings * * @method updateDisplay */ TextTrackSettings.prototype.updateDisplay = function updateDisplay() { var ttDisplay = this.player_.getChild('textTrackDisplay'); if (ttDisplay) { ttDisplay.updateDisplay(); } }; return TextTrackSettings; })(_component2['default']); _component2['default'].registerComponent('TextTrackSettings', TextTrackSettings); function getSelectedOptionValue(target) { var selectedOption = undefined; // not all browsers support selectedOptions, so, fallback to options if (target.selectedOptions) { selectedOption = target.selectedOptions[0]; } else if (target.options) { selectedOption = target.options[target.options.selectedIndex]; } return selectedOption.value; } function setSelectedOption(target, value) { if (!value) { return; } var i = undefined; for (i = 0; i < target.options.length; i++) { var option = target.options[i]; if (option.value === value) { break; } } target.selectedIndex = i; } function captionOptionsMenuTemplate() { var template = '<div class="vjs-tracksettings">\n <div class="vjs-tracksettings-colors">\n <div class="vjs-fg-color vjs-tracksetting">\n <label class="vjs-label">Foreground</label>\n <select>\n <option value="">---</option>\n <option value="#FFF">White</option>\n <option value="#000">Black</option>\n <option value="#F00">Red</option>\n <option value="#0F0">Green</option>\n <option value="#00F">Blue</option>\n <option value="#FF0">Yellow</option>\n <option value="#F0F">Magenta</option>\n <option value="#0FF">Cyan</option>\n </select>\n <span class="vjs-text-opacity vjs-opacity">\n <select>\n <option value="">---</option>\n <option value="1">Opaque</option>\n <option value="0.5">Semi-Opaque</option>\n </select>\n </span>\n </div> <!-- vjs-fg-color -->\n <div class="vjs-bg-color vjs-tracksetting">\n <label class="vjs-label">Background</label>\n <select>\n <option value="">---</option>\n <option value="#FFF">White</option>\n <option value="#000">Black</option>\n <option value="#F00">Red</option>\n <option value="#0F0">Green</option>\n <option value="#00F">Blue</option>\n <option value="#FF0">Yellow</option>\n <option value="#F0F">Magenta</option>\n <option value="#0FF">Cyan</option>\n </select>\n <span class="vjs-bg-opacity vjs-opacity">\n <select>\n <option value="">---</option>\n <option value="1">Opaque</option>\n <option value="0.5">Semi-Transparent</option>\n <option value="0">Transparent</option>\n </select>\n </span>\n </div> <!-- vjs-bg-color -->\n <div class="window-color vjs-tracksetting">\n <label class="vjs-label">Window</label>\n <select>\n <option value="">---</option>\n <option value="#FFF">White</option>\n <option value="#000">Black</option>\n <option value="#F00">Red</option>\n <option value="#0F0">Green</option>\n <option value="#00F">Blue</option>\n <option value="#FF0">Yellow</option>\n <option value="#F0F">Magenta</option>\n <option value="#0FF">Cyan</option>\n </select>\n <span class="vjs-window-opacity vjs-opacity">\n <select>\n <option value="">---</option>\n <option value="1">Opaque</option>\n <option value="0.5">Semi-Transparent</option>\n <option value="0">Transparent</option>\n </select>\n </span>\n </div> <!-- vjs-window-color -->\n </div> <!-- vjs-tracksettings -->\n <div class="vjs-tracksettings-font">\n <div class="vjs-font-percent vjs-tracksetting">\n <label class="vjs-label">Font Size</label>\n <select>\n <option value="0.50">50%</option>\n <option value="0.75">75%</option>\n <option value="1.00" selected>100%</option>\n <option value="1.25">125%</option>\n <option value="1.50">150%</option>\n <option value="1.75">175%</option>\n <option value="2.00">200%</option>\n <option value="3.00">300%</option>\n <option value="4.00">400%</option>\n </select>\n </div> <!-- vjs-font-percent -->\n <div class="vjs-edge-style vjs-tracksetting">\n <label class="vjs-label">Text Edge Style</label>\n <select>\n <option value="none">None</option>\n <option value="raised">Raised</option>\n <option value="depressed">Depressed</option>\n <option value="uniform">Uniform</option>\n <option value="dropshadow">Dropshadow</option>\n </select>\n </div> <!-- vjs-edge-style -->\n <div class="vjs-font-family vjs-tracksetting">\n <label class="vjs-label">Font Family</label>\n <select>\n <option value="">Default</option>\n <option value="monospaceSerif">Monospace Serif</option>\n <option value="proportionalSerif">Proportional Serif</option>\n <option value="monospaceSansSerif">Monospace Sans-Serif</option>\n <option value="proportionalSansSerif">Proportional Sans-Serif</option>\n <option value="casual">Casual</option>\n <option value="script">Script</option>\n <option value="small-caps">Small Caps</option>\n </select>\n </div> <!-- vjs-font-family -->\n </div>\n </div>\n <div class="vjs-tracksettings-controls">\n <button class="vjs-default-button">Defaults</button>\n <button class="vjs-done-button">Done</button>\n </div>'; return template; } exports['default'] = TextTrackSettings; module.exports = exports['default']; },{"../component":48,"../utils/events.js":108,"../utils/fn.js":109,"../utils/log.js":112,"global/window":2,"safe-json-parse/tuple":45}],103:[function(_dereq_,module,exports){ /** * @file text-track.js */ 'use strict'; exports.__esModule = true; function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj['default'] = obj; return newObj; } } function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } var _textTrackCueList = _dereq_('./text-track-cue-list'); var _textTrackCueList2 = _interopRequireDefault(_textTrackCueList); var _utilsFnJs = _dereq_('../utils/fn.js'); var Fn = _interopRequireWildcard(_utilsFnJs); var _utilsGuidJs = _dereq_('../utils/guid.js'); var Guid = _interopRequireWildcard(_utilsGuidJs); var _utilsBrowserJs = _dereq_('../utils/browser.js'); var browser = _interopRequireWildcard(_utilsBrowserJs); var _textTrackEnums = _dereq_('./text-track-enums'); var TextTrackEnum = _interopRequireWildcard(_textTrackEnums); var _utilsLogJs = _dereq_('../utils/log.js'); var _utilsLogJs2 = _interopRequireDefault(_utilsLogJs); var _eventTarget = _dereq_('../event-target'); var _eventTarget2 = _interopRequireDefault(_eventTarget); var _globalDocument = _dereq_('global/document'); var _globalDocument2 = _interopRequireDefault(_globalDocument); var _globalWindow = _dereq_('global/window'); var _globalWindow2 = _interopRequireDefault(_globalWindow); var _xhrJs = _dereq_('../xhr.js'); var _xhrJs2 = _interopRequireDefault(_xhrJs); /* * https://html.spec.whatwg.org/multipage/embedded-content.html#texttrack * * interface TextTrack : EventTarget { * readonly attribute TextTrackKind kind; * readonly attribute DOMString label; * readonly attribute DOMString language; * * readonly attribute DOMString id; * readonly attribute DOMString inBandMetadataTrackDispatchType; * * attribute TextTrackMode mode; * * readonly attribute TextTrackCueList? cues; * readonly attribute TextTrackCueList? activeCues; * * void addCue(TextTrackCue cue); * void removeCue(TextTrackCue cue); * * attribute EventHandler oncuechange; * }; */ var TextTrack = function TextTrack() { var options = arguments.length <= 0 || arguments[0] === undefined ? {} : arguments[0]; if (!options.tech) { throw new Error('A tech was not provided.'); } var tt = this; if (browser.IS_IE8) { tt = _globalDocument2['default'].createElement('custom'); for (var prop in TextTrack.prototype) { tt[prop] = TextTrack.prototype[prop]; } } tt.tech_ = options.tech; var mode = TextTrackEnum.TextTrackMode[options['mode']] || 'disabled'; var kind = TextTrackEnum.TextTrackKind[options['kind']] || 'subtitles'; var label = options['label'] || ''; var language = options['language'] || options['srclang'] || ''; var id = options['id'] || 'vjs_text_track_' + Guid.newGUID(); if (kind === 'metadata' || kind === 'chapters') { mode = 'hidden'; } tt.cues_ = []; tt.activeCues_ = []; var cues = new _textTrackCueList2['default'](tt.cues_); var activeCues = new _textTrackCueList2['default'](tt.activeCues_); var changed = false; var timeupdateHandler = Fn.bind(tt, function () { this['activeCues']; if (changed) { this['trigger']('cuechange'); changed = false; } }); if (mode !== 'disabled') { tt.tech_.on('timeupdate', timeupdateHandler); } Object.defineProperty(tt, 'kind', { get: function get() { return kind; }, set: Function.prototype }); Object.defineProperty(tt, 'label', { get: function get() { return label; }, set: Function.prototype }); Object.defineProperty(tt, 'language', { get: function get() { return language; }, set: Function.prototype }); Object.defineProperty(tt, 'id', { get: function get() { return id; }, set: Function.prototype }); Object.defineProperty(tt, 'mode', { get: function get() { return mode; }, set: function set(newMode) { if (!TextTrackEnum.TextTrackMode[newMode]) { return; } mode = newMode; if (mode === 'showing') { this.tech_.on('timeupdate', timeupdateHandler); } this.trigger('modechange'); } }); Object.defineProperty(tt, 'cues', { get: function get() { if (!this.loaded_) { return null; } return cues; }, set: Function.prototype }); Object.defineProperty(tt, 'activeCues', { get: function get() { if (!this.loaded_) { return null; } if (this['cues'].length === 0) { return activeCues; // nothing to do } var ct = this.tech_.currentTime(); var active = []; for (var i = 0, l = this['cues'].length; i < l; i++) { var cue = this['cues'][i]; if (cue['startTime'] <= ct && cue['endTime'] >= ct) { active.push(cue); } else if (cue['startTime'] === cue['endTime'] && cue['startTime'] <= ct && cue['startTime'] + 0.5 >= ct) { active.push(cue); } } changed = false; if (active.length !== this.activeCues_.length) { changed = true; } else { for (var i = 0; i < active.length; i++) { if (indexOf.call(this.activeCues_, active[i]) === -1) { changed = true; } } } this.activeCues_ = active; activeCues.setCues_(this.activeCues_); return activeCues; }, set: Function.prototype }); if (options.src) { tt.src = options.src; loadTrack(options.src, tt); } else { tt.loaded_ = true; } if (browser.IS_IE8) { return tt; } }; TextTrack.prototype = Object.create(_eventTarget2['default'].prototype); TextTrack.prototype.constructor = TextTrack; /* * cuechange - One or more cues in the track have become active or stopped being active. */ TextTrack.prototype.allowedEvents_ = { 'cuechange': 'cuechange' }; TextTrack.prototype.addCue = function (cue) { var tracks = this.tech_.textTracks(); if (tracks) { for (var i = 0; i < tracks.length; i++) { if (tracks[i] !== this) { tracks[i].removeCue(cue); } } } this.cues_.push(cue); this['cues'].setCues_(this.cues_); }; TextTrack.prototype.removeCue = function (removeCue) { var removed = false; for (var i = 0, l = this.cues_.length; i < l; i++) { var cue = this.cues_[i]; if (cue === removeCue) { this.cues_.splice(i, 1); removed = true; } } if (removed) { this.cues.setCues_(this.cues_); } }; /* * Downloading stuff happens below this point */ var parseCues = function parseCues(srcContent, track) { if (typeof _globalWindow2['default']['WebVTT'] !== 'function') { //try again a bit later return _globalWindow2['default'].setTimeout(function () { parseCues(srcContent, track); }, 25); } var parser = new _globalWindow2['default']['WebVTT']['Parser'](_globalWindow2['default'], _globalWindow2['default']['vttjs'], _globalWindow2['default']['WebVTT']['StringDecoder']()); parser['oncue'] = function (cue) { track.addCue(cue); }; parser['onparsingerror'] = function (error) { _utilsLogJs2['default'].error(error); }; parser['parse'](srcContent); parser['flush'](); }; var loadTrack = function loadTrack(src, track) { _xhrJs2['default'](src, Fn.bind(this, function (err, response, responseBody) { if (err) { return _utilsLogJs2['default'].error(err, response); } track.loaded_ = true; parseCues(responseBody, track); })); }; var indexOf = function indexOf(searchElement, fromIndex) { if (this == null) { throw new TypeError('"this" is null or not defined'); } var O = Object(this); var len = O.length >>> 0; if (len === 0) { return -1; } var n = +fromIndex || 0; if (Math.abs(n) === Infinity) { n = 0; } if (n >= len) { return -1; } var k = Math.max(n >= 0 ? n : len - Math.abs(n), 0); while (k < len) { if (k in O && O[k] === searchElement) { return k; } k++; } return -1; }; exports['default'] = TextTrack; module.exports = exports['default']; },{"../event-target":79,"../utils/browser.js":104,"../utils/fn.js":109,"../utils/guid.js":111,"../utils/log.js":112,"../xhr.js":119,"./text-track-cue-list":97,"./text-track-enums":99,"global/document":1,"global/window":2}],104:[function(_dereq_,module,exports){ /** * @file browser.js */ 'use strict'; exports.__esModule = true; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } var _globalDocument = _dereq_('global/document'); var _globalDocument2 = _interopRequireDefault(_globalDocument); var _globalWindow = _dereq_('global/window'); var _globalWindow2 = _interopRequireDefault(_globalWindow); var USER_AGENT = _globalWindow2['default'].navigator.userAgent; var webkitVersionMap = /AppleWebKit\/([\d.]+)/i.exec(USER_AGENT); var appleWebkitVersion = webkitVersionMap ? parseFloat(webkitVersionMap.pop()) : null; /* * Device is an iPhone * * @type {Boolean} * @constant * @private */ var IS_IPHONE = /iPhone/i.test(USER_AGENT); exports.IS_IPHONE = IS_IPHONE; var IS_IPAD = /iPad/i.test(USER_AGENT); exports.IS_IPAD = IS_IPAD; var IS_IPOD = /iPod/i.test(USER_AGENT); exports.IS_IPOD = IS_IPOD; var IS_IOS = IS_IPHONE || IS_IPAD || IS_IPOD; exports.IS_IOS = IS_IOS; var IOS_VERSION = (function () { var match = USER_AGENT.match(/OS (\d+)_/i); if (match && match[1]) { return match[1]; } })(); exports.IOS_VERSION = IOS_VERSION; var IS_ANDROID = /Android/i.test(USER_AGENT); exports.IS_ANDROID = IS_ANDROID; var ANDROID_VERSION = (function () { // This matches Android Major.Minor.Patch versions // ANDROID_VERSION is Major.Minor as a Number, if Minor isn't available, then only Major is returned var match = USER_AGENT.match(/Android (\d+)(?:\.(\d+))?(?:\.(\d+))*/i), major, minor; if (!match) { return null; } major = match[1] && parseFloat(match[1]); minor = match[2] && parseFloat(match[2]); if (major && minor) { return parseFloat(match[1] + '.' + match[2]); } else if (major) { return major; } else { return null; } })(); exports.ANDROID_VERSION = ANDROID_VERSION; // Old Android is defined as Version older than 2.3, and requiring a webkit version of the android browser var IS_OLD_ANDROID = IS_ANDROID && /webkit/i.test(USER_AGENT) && ANDROID_VERSION < 2.3; exports.IS_OLD_ANDROID = IS_OLD_ANDROID; var IS_NATIVE_ANDROID = IS_ANDROID && ANDROID_VERSION < 5 && appleWebkitVersion < 537; exports.IS_NATIVE_ANDROID = IS_NATIVE_ANDROID; var IS_FIREFOX = /Firefox/i.test(USER_AGENT); exports.IS_FIREFOX = IS_FIREFOX; var IS_CHROME = /Chrome/i.test(USER_AGENT); exports.IS_CHROME = IS_CHROME; var IS_IE8 = /MSIE\s8\.0/.test(USER_AGENT); exports.IS_IE8 = IS_IE8; var TOUCH_ENABLED = !!('ontouchstart' in _globalWindow2['default'] || _globalWindow2['default'].DocumentTouch && _globalDocument2['default'] instanceof _globalWindow2['default'].DocumentTouch); exports.TOUCH_ENABLED = TOUCH_ENABLED; var BACKGROUND_SIZE_SUPPORTED = ('backgroundSize' in _globalDocument2['default'].createElement('video').style); exports.BACKGROUND_SIZE_SUPPORTED = BACKGROUND_SIZE_SUPPORTED; },{"global/document":1,"global/window":2}],105:[function(_dereq_,module,exports){ /** * @file buffer.js */ 'use strict'; exports.__esModule = true; exports.bufferedPercent = bufferedPercent; var _timeRangesJs = _dereq_('./time-ranges.js'); /** * Compute how much your video has been buffered * * @param {Object} Buffered object * @param {Number} Total duration * @return {Number} Percent buffered of the total duration * @private * @function bufferedPercent */ function bufferedPercent(buffered, duration) { var bufferedDuration = 0, start, end; if (!duration) { return 0; } if (!buffered || !buffered.length) { buffered = _timeRangesJs.createTimeRange(0, 0); } for (var i = 0; i < buffered.length; i++) { start = buffered.start(i); end = buffered.end(i); // buffered end can be bigger than duration by a very small fraction if (end > duration) { end = duration; } bufferedDuration += end - start; } return bufferedDuration / duration; } },{"./time-ranges.js":115}],106:[function(_dereq_,module,exports){ 'use strict'; exports.__esModule = true; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } var _logJs = _dereq_('./log.js'); var _logJs2 = _interopRequireDefault(_logJs); /** * Object containing the default behaviors for available handler methods. * * @private * @type {Object} */ var defaultBehaviors = { get: function get(obj, key) { return obj[key]; }, set: function set(obj, key, value) { obj[key] = value; return true; } }; /** * Expose private objects publicly using a Proxy to log deprecation warnings. * * Browsers that do not support Proxy objects will simply return the `target` * object, so it can be directly exposed. * * @param {Object} target The target object. * @param {Object} messages Messages to display from a Proxy. Only operations * with an associated message will be proxied. * @param {String} [messages.get] * @param {String} [messages.set] * @return {Object} A Proxy if supported or the `target` argument. */ exports['default'] = function (target) { var messages = arguments.length <= 1 || arguments[1] === undefined ? {} : arguments[1]; if (typeof Proxy === 'function') { var _ret = (function () { var handler = {}; // Build a handler object based on those keys that have both messages // and default behaviors. Object.keys(messages).forEach(function (key) { if (defaultBehaviors.hasOwnProperty(key)) { handler[key] = function () { _logJs2['default'].warn(messages[key]); return defaultBehaviors[key].apply(this, arguments); }; } }); return { v: new Proxy(target, handler) }; })(); if (typeof _ret === 'object') return _ret.v; } return target; }; module.exports = exports['default']; },{"./log.js":112}],107:[function(_dereq_,module,exports){ /** * @file dom.js */ 'use strict'; exports.__esModule = true; exports.getEl = getEl; exports.createEl = createEl; exports.insertElFirst = insertElFirst; exports.getElData = getElData; exports.hasElData = hasElData; exports.removeElData = removeElData; exports.hasElClass = hasElClass; exports.addElClass = addElClass; exports.removeElClass = removeElClass; exports.setElAttributes = setElAttributes; exports.getElAttributes = getElAttributes; exports.blockTextSelection = blockTextSelection; exports.unblockTextSelection = unblockTextSelection; exports.findElPosition = findElPosition; function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj['default'] = obj; return newObj; } } function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } var _globalDocument = _dereq_('global/document'); var _globalDocument2 = _interopRequireDefault(_globalDocument); var _globalWindow = _dereq_('global/window'); var _globalWindow2 = _interopRequireDefault(_globalWindow); var _guidJs = _dereq_('./guid.js'); var Guid = _interopRequireWildcard(_guidJs); /** * Shorthand for document.getElementById() * Also allows for CSS (jQuery) ID syntax. But nothing other than IDs. * * @param {String} id Element ID * @return {Element} Element with supplied ID * @function getEl */ function getEl(id) { if (id.indexOf('#') === 0) { id = id.slice(1); } return _globalDocument2['default'].getElementById(id); } /** * Creates an element and applies properties. * * @param {String=} tagName Name of tag to be created. * @param {Object=} properties Element properties to be applied. * @return {Element} * @function createEl */ function createEl() { var tagName = arguments.length <= 0 || arguments[0] === undefined ? 'div' : arguments[0]; var properties = arguments.length <= 1 || arguments[1] === undefined ? {} : arguments[1]; var el = _globalDocument2['default'].createElement(tagName); Object.getOwnPropertyNames(properties).forEach(function (propName) { var val = properties[propName]; // Not remembering why we were checking for dash // but using setAttribute means you have to use getAttribute // The check for dash checks for the aria- * attributes, like aria-label, aria-valuemin. // The additional check for "role" is because the default method for adding attributes does not // add the attribute "role". My guess is because it's not a valid attribute in some namespaces, although // browsers handle the attribute just fine. The W3C allows for aria- * attributes to be used in pre-HTML5 docs. // http://www.w3.org/TR/wai-aria-primer/#ariahtml. Using setAttribute gets around this problem. if (propName.indexOf('aria-') !== -1 || propName === 'role' || propName === 'type') { el.setAttribute(propName, val); } else { el[propName] = val; } }); return el; } /** * Insert an element as the first child node of another * * @param {Element} child Element to insert * @param {Element} parent Element to insert child into * @private * @function insertElFirst */ function insertElFirst(child, parent) { if (parent.firstChild) { parent.insertBefore(child, parent.firstChild); } else { parent.appendChild(child); } } /** * Element Data Store. Allows for binding data to an element without putting it directly on the element. * Ex. Event listeners are stored here. * (also from jsninja.com, slightly modified and updated for closure compiler) * * @type {Object} * @private */ var elData = {}; /* * Unique attribute name to store an element's guid in * * @type {String} * @constant * @private */ var elIdAttr = 'vdata' + new Date().getTime(); /** * Returns the cache object where data for an element is stored * * @param {Element} el Element to store data for. * @return {Object} * @function getElData */ function getElData(el) { var id = el[elIdAttr]; if (!id) { id = el[elIdAttr] = Guid.newGUID(); } if (!elData[id]) { elData[id] = {}; } return elData[id]; } /** * Returns whether or not an element has cached data * * @param {Element} el A dom element * @return {Boolean} * @private * @function hasElData */ function hasElData(el) { var id = el[elIdAttr]; if (!id) { return false; } return !!Object.getOwnPropertyNames(elData[id]).length; } /** * Delete data for the element from the cache and the guid attr from getElementById * * @param {Element} el Remove data for an element * @private * @function removeElData */ function removeElData(el) { var id = el[elIdAttr]; if (!id) { return; } // Remove all stored data delete elData[id]; // Remove the elIdAttr property from the DOM node try { delete el[elIdAttr]; } catch (e) { if (el.removeAttribute) { el.removeAttribute(elIdAttr); } else { // IE doesn't appear to support removeAttribute on the document element el[elIdAttr] = null; } } } /** * Check if an element has a CSS class * * @param {Element} element Element to check * @param {String} classToCheck Classname to check * @function hasElClass */ function hasElClass(element, classToCheck) { return (' ' + element.className + ' ').indexOf(' ' + classToCheck + ' ') !== -1; } /** * Add a CSS class name to an element * * @param {Element} element Element to add class name to * @param {String} classToAdd Classname to add * @function addElClass */ function addElClass(element, classToAdd) { if (!hasElClass(element, classToAdd)) { element.className = element.className === '' ? classToAdd : element.className + ' ' + classToAdd; } } /** * Remove a CSS class name from an element * * @param {Element} element Element to remove from class name * @param {String} classToRemove Classname to remove * @function removeElClass */ function removeElClass(element, classToRemove) { if (!hasElClass(element, classToRemove)) { return; } var classNames = element.className.split(' '); // no arr.indexOf in ie8, and we don't want to add a big shim for (var i = classNames.length - 1; i >= 0; i--) { if (classNames[i] === classToRemove) { classNames.splice(i, 1); } } element.className = classNames.join(' '); } /** * Apply attributes to an HTML element. * * @param {Element} el Target element. * @param {Object=} attributes Element attributes to be applied. * @private * @function setElAttributes */ function setElAttributes(el, attributes) { Object.getOwnPropertyNames(attributes).forEach(function (attrName) { var attrValue = attributes[attrName]; if (attrValue === null || typeof attrValue === 'undefined' || attrValue === false) { el.removeAttribute(attrName); } else { el.setAttribute(attrName, attrValue === true ? '' : attrValue); } }); } /** * Get an element's attribute values, as defined on the HTML tag * Attributes are not the same as properties. They're defined on the tag * or with setAttribute (which shouldn't be used with HTML) * This will return true or false for boolean attributes. * * @param {Element} tag Element from which to get tag attributes * @return {Object} * @private * @function getElAttributes */ function getElAttributes(tag) { var obj, knownBooleans, attrs, attrName, attrVal; obj = {}; // known boolean attributes // we can check for matching boolean properties, but older browsers // won't know about HTML5 boolean attributes that we still read from knownBooleans = ',' + 'autoplay,controls,loop,muted,default' + ','; if (tag && tag.attributes && tag.attributes.length > 0) { attrs = tag.attributes; for (var i = attrs.length - 1; i >= 0; i--) { attrName = attrs[i].name; attrVal = attrs[i].value; // check for known booleans // the matching element property will return a value for typeof if (typeof tag[attrName] === 'boolean' || knownBooleans.indexOf(',' + attrName + ',') !== -1) { // the value of an included boolean attribute is typically an empty // string ('') which would equal false if we just check for a false value. // we also don't want support bad code like autoplay='false' attrVal = attrVal !== null ? true : false; } obj[attrName] = attrVal; } } return obj; } /** * Attempt to block the ability to select text while dragging controls * * @return {Boolean} * @method blockTextSelection */ function blockTextSelection() { _globalDocument2['default'].body.focus(); _globalDocument2['default'].onselectstart = function () { return false; }; } /** * Turn off text selection blocking * * @return {Boolean} * @method unblockTextSelection */ function unblockTextSelection() { _globalDocument2['default'].onselectstart = function () { return true; }; } /** * Offset Left * getBoundingClientRect technique from * John Resig http://ejohn.org/blog/getboundingclientrect-is-awesome/ * * @param {Element} el Element from which to get offset * @return {Object=} * @method findElPosition */ function findElPosition(el) { var box = undefined; if (el.getBoundingClientRect && el.parentNode) { box = el.getBoundingClientRect(); } if (!box) { return { left: 0, top: 0 }; } var docEl = _globalDocument2['default'].documentElement; var body = _globalDocument2['default'].body; var clientLeft = docEl.clientLeft || body.clientLeft || 0; var scrollLeft = _globalWindow2['default'].pageXOffset || body.scrollLeft; var left = box.left + scrollLeft - clientLeft; var clientTop = docEl.clientTop || body.clientTop || 0; var scrollTop = _globalWindow2['default'].pageYOffset || body.scrollTop; var top = box.top + scrollTop - clientTop; // Android sometimes returns slightly off decimal values, so need to round return { left: Math.round(left), top: Math.round(top) }; } },{"./guid.js":111,"global/document":1,"global/window":2}],108:[function(_dereq_,module,exports){ /** * @file events.js * * Event System (John Resig - Secrets of a JS Ninja http://jsninja.com/) * (Original book version wasn't completely usable, so fixed some things and made Closure Compiler compatible) * This should work very similarly to jQuery's events, however it's based off the book version which isn't as * robust as jquery's, so there's probably some differences. */ 'use strict'; exports.__esModule = true; exports.on = on; exports.off = off; exports.trigger = trigger; exports.one = one; exports.fixEvent = fixEvent; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj['default'] = obj; return newObj; } } var _domJs = _dereq_('./dom.js'); var Dom = _interopRequireWildcard(_domJs); var _guidJs = _dereq_('./guid.js'); var Guid = _interopRequireWildcard(_guidJs); var _globalWindow = _dereq_('global/window'); var _globalWindow2 = _interopRequireDefault(_globalWindow); var _globalDocument = _dereq_('global/document'); var _globalDocument2 = _interopRequireDefault(_globalDocument); /** * Add an event listener to element * It stores the handler function in a separate cache object * and adds a generic handler to the element's event, * along with a unique id (guid) to the element. * * @param {Element|Object} elem Element or object to bind listeners to * @param {String|Array} type Type of event to bind to. * @param {Function} fn Event listener. * @method on */ function on(elem, type, fn) { if (Array.isArray(type)) { return _handleMultipleEvents(on, elem, type, fn); } var data = Dom.getElData(elem); // We need a place to store all our handler data if (!data.handlers) data.handlers = {}; if (!data.handlers[type]) data.handlers[type] = []; if (!fn.guid) fn.guid = Guid.newGUID(); data.handlers[type].push(fn); if (!data.dispatcher) { data.disabled = false; data.dispatcher = function (event, hash) { if (data.disabled) return; event = fixEvent(event); var handlers = data.handlers[event.type]; if (handlers) { // Copy handlers so if handlers are added/removed during the process it doesn't throw everything off. var handlersCopy = handlers.slice(0); for (var m = 0, n = handlersCopy.length; m < n; m++) { if (event.isImmediatePropagationStopped()) { break; } else { handlersCopy[m].call(elem, event, hash); } } } }; } if (data.handlers[type].length === 1) { if (elem.addEventListener) { elem.addEventListener(type, data.dispatcher, false); } else if (elem.attachEvent) { elem.attachEvent('on' + type, data.dispatcher); } } } /** * Removes event listeners from an element * * @param {Element|Object} elem Object to remove listeners from * @param {String|Array=} type Type of listener to remove. Don't include to remove all events from element. * @param {Function} fn Specific listener to remove. Don't include to remove listeners for an event type. * @method off */ function off(elem, type, fn) { // Don't want to add a cache object through getElData if not needed if (!Dom.hasElData(elem)) return; var data = Dom.getElData(elem); // If no events exist, nothing to unbind if (!data.handlers) { return; } if (Array.isArray(type)) { return _handleMultipleEvents(off, elem, type, fn); } // Utility function var removeType = function removeType(t) { data.handlers[t] = []; _cleanUpEvents(elem, t); }; // Are we removing all bound events? if (!type) { for (var t in data.handlers) { removeType(t); }return; } var handlers = data.handlers[type]; // If no handlers exist, nothing to unbind if (!handlers) return; // If no listener was provided, remove all listeners for type if (!fn) { removeType(type); return; } // We're only removing a single handler if (fn.guid) { for (var n = 0; n < handlers.length; n++) { if (handlers[n].guid === fn.guid) { handlers.splice(n--, 1); } } } _cleanUpEvents(elem, type); } /** * Trigger an event for an element * * @param {Element|Object} elem Element to trigger an event on * @param {Event|Object|String} event A string (the type) or an event object with a type attribute * @param {Object} [hash] data hash to pass along with the event * @return {Boolean=} Returned only if default was prevented * @method trigger */ function trigger(elem, event, hash) { // Fetches element data and a reference to the parent (for bubbling). // Don't want to add a data object to cache for every parent, // so checking hasElData first. var elemData = Dom.hasElData(elem) ? Dom.getElData(elem) : {}; var parent = elem.parentNode || elem.ownerDocument; // type = event.type || event, // handler; // If an event name was passed as a string, creates an event out of it if (typeof event === 'string') { event = { type: event, target: elem }; } // Normalizes the event properties. event = fixEvent(event); // If the passed element has a dispatcher, executes the established handlers. if (elemData.dispatcher) { elemData.dispatcher.call(elem, event, hash); } // Unless explicitly stopped or the event does not bubble (e.g. media events) // recursively calls this function to bubble the event up the DOM. if (parent && !event.isPropagationStopped() && event.bubbles === true) { trigger.call(null, parent, event, hash); // If at the top of the DOM, triggers the default action unless disabled. } else if (!parent && !event.defaultPrevented) { var targetData = Dom.getElData(event.target); // Checks if the target has a default action for this event. if (event.target[event.type]) { // Temporarily disables event dispatching on the target as we have already executed the handler. targetData.disabled = true; // Executes the default action. if (typeof event.target[event.type] === 'function') { event.target[event.type](); } // Re-enables event dispatching. targetData.disabled = false; } } // Inform the triggerer if the default was prevented by returning false return !event.defaultPrevented; } /** * Trigger a listener only once for an event * * @param {Element|Object} elem Element or object to * @param {String|Array} type Name/type of event * @param {Function} fn Event handler function * @method one */ function one(elem, type, fn) { if (Array.isArray(type)) { return _handleMultipleEvents(one, elem, type, fn); } var func = function func() { off(elem, type, func); fn.apply(this, arguments); }; // copy the guid to the new function so it can removed using the original function's ID func.guid = fn.guid = fn.guid || Guid.newGUID(); on(elem, type, func); } /** * Fix a native event to have standard property values * * @param {Object} event Event object to fix * @return {Object} * @private * @method fixEvent */ function fixEvent(event) { function returnTrue() { return true; } function returnFalse() { return false; } // Test if fixing up is needed // Used to check if !event.stopPropagation instead of isPropagationStopped // But native events return true for stopPropagation, but don't have // other expected methods like isPropagationStopped. Seems to be a problem // with the Javascript Ninja code. So we're just overriding all events now. if (!event || !event.isPropagationStopped) { var old = event || _globalWindow2['default'].event; event = {}; // Clone the old object so that we can modify the values event = {}; // IE8 Doesn't like when you mess with native event properties // Firefox returns false for event.hasOwnProperty('type') and other props // which makes copying more difficult. // TODO: Probably best to create a whitelist of event props for (var key in old) { // Safari 6.0.3 warns you if you try to copy deprecated layerX/Y // Chrome warns you if you try to copy deprecated keyboardEvent.keyLocation if (key !== 'layerX' && key !== 'layerY' && key !== 'keyLocation') { // Chrome 32+ warns if you try to copy deprecated returnValue, but // we still want to if preventDefault isn't supported (IE8). if (!(key === 'returnValue' && old.preventDefault)) { event[key] = old[key]; } } } // The event occurred on this element if (!event.target) { event.target = event.srcElement || _globalDocument2['default']; } // Handle which other element the event is related to if (!event.relatedTarget) { event.relatedTarget = event.fromElement === event.target ? event.toElement : event.fromElement; } // Stop the default browser action event.preventDefault = function () { if (old.preventDefault) { old.preventDefault(); } event.returnValue = false; old.returnValue = false; event.defaultPrevented = true; }; event.defaultPrevented = false; // Stop the event from bubbling event.stopPropagation = function () { if (old.stopPropagation) { old.stopPropagation(); } event.cancelBubble = true; old.cancelBubble = true; event.isPropagationStopped = returnTrue; }; event.isPropagationStopped = returnFalse; // Stop the event from bubbling and executing other handlers event.stopImmediatePropagation = function () { if (old.stopImmediatePropagation) { old.stopImmediatePropagation(); } event.isImmediatePropagationStopped = returnTrue; event.stopPropagation(); }; event.isImmediatePropagationStopped = returnFalse; // Handle mouse position if (event.clientX != null) { var doc = _globalDocument2['default'].documentElement, body = _globalDocument2['default'].body; event.pageX = event.clientX + (doc && doc.scrollLeft || body && body.scrollLeft || 0) - (doc && doc.clientLeft || body && body.clientLeft || 0); event.pageY = event.clientY + (doc && doc.scrollTop || body && body.scrollTop || 0) - (doc && doc.clientTop || body && body.clientTop || 0); } // Handle key presses event.which = event.charCode || event.keyCode; // Fix button for mouse clicks: // 0 == left; 1 == middle; 2 == right if (event.button != null) { event.button = event.button & 1 ? 0 : event.button & 4 ? 1 : event.button & 2 ? 2 : 0; } } // Returns fixed-up instance return event; } /** * Clean up the listener cache and dispatchers * * @param {Element|Object} elem Element to clean up * @param {String} type Type of event to clean up * @private * @method _cleanUpEvents */ function _cleanUpEvents(elem, type) { var data = Dom.getElData(elem); // Remove the events of a particular type if there are none left if (data.handlers[type].length === 0) { delete data.handlers[type]; // data.handlers[type] = null; // Setting to null was causing an error with data.handlers // Remove the meta-handler from the element if (elem.removeEventListener) { elem.removeEventListener(type, data.dispatcher, false); } else if (elem.detachEvent) { elem.detachEvent('on' + type, data.dispatcher); } } // Remove the events object if there are no types left if (Object.getOwnPropertyNames(data.handlers).length <= 0) { delete data.handlers; delete data.dispatcher; delete data.disabled; } // Finally remove the element data if there is no data left if (Object.getOwnPropertyNames(data).length === 0) { Dom.removeElData(elem); } } /** * Loops through an array of event types and calls the requested method for each type. * * @param {Function} fn The event method we want to use. * @param {Element|Object} elem Element or object to bind listeners to * @param {String} type Type of event to bind to. * @param {Function} callback Event listener. * @private * @function _handleMultipleEvents */ function _handleMultipleEvents(fn, elem, types, callback) { types.forEach(function (type) { //Call the event method for each one of the types fn(elem, type, callback); }); } },{"./dom.js":107,"./guid.js":111,"global/document":1,"global/window":2}],109:[function(_dereq_,module,exports){ /** * @file fn.js */ 'use strict'; exports.__esModule = true; var _guidJs = _dereq_('./guid.js'); /** * Bind (a.k.a proxy or Context). A simple method for changing the context of a function * It also stores a unique id on the function so it can be easily removed from events * * @param {*} context The object to bind as scope * @param {Function} fn The function to be bound to a scope * @param {Number=} uid An optional unique ID for the function to be set * @return {Function} * @private * @method bind */ var bind = function bind(context, fn, uid) { // Make sure the function has a unique ID if (!fn.guid) { fn.guid = _guidJs.newGUID(); } // Create the new function that changes the context var ret = function ret() { return fn.apply(context, arguments); }; // Allow for the ability to individualize this function // Needed in the case where multiple objects might share the same prototype // IF both items add an event listener with the same function, then you try to remove just one // it will remove both because they both have the same guid. // when using this, you need to use the bind method when you remove the listener as well. // currently used in text tracks ret.guid = uid ? uid + '_' + fn.guid : fn.guid; return ret; }; exports.bind = bind; },{"./guid.js":111}],110:[function(_dereq_,module,exports){ /** * @file format-time.js * * Format seconds as a time string, H:MM:SS or M:SS * Supplying a guide (in seconds) will force a number of leading zeros * to cover the length of the guide * * @param {Number} seconds Number of seconds to be turned into a string * @param {Number} guide Number (in seconds) to model the string after * @return {String} Time formatted as H:MM:SS or M:SS * @private * @function formatTime */ 'use strict'; exports.__esModule = true; function formatTime(seconds) { var guide = arguments.length <= 1 || arguments[1] === undefined ? seconds : arguments[1]; return (function () { var s = Math.floor(seconds % 60); var m = Math.floor(seconds / 60 % 60); var h = Math.floor(seconds / 3600); var gm = Math.floor(guide / 60 % 60); var gh = Math.floor(guide / 3600); // handle invalid times if (isNaN(seconds) || seconds === Infinity) { // '-' is false for all relational operators (e.g. <, >=) so this setting // will add the minimum number of fields specified by the guide h = m = s = '-'; } // Check if we need to show hours h = h > 0 || gh > 0 ? h + ':' : ''; // If hours are showing, we may need to add a leading zero. // Always show at least one digit of minutes. m = ((h || gm >= 10) && m < 10 ? '0' + m : m) + ':'; // Check if leading zero is need for seconds s = s < 10 ? '0' + s : s; return h + m + s; })(); } exports['default'] = formatTime; module.exports = exports['default']; },{}],111:[function(_dereq_,module,exports){ /** * @file guid.js * * Unique ID for an element or function * @type {Number} * @private */ "use strict"; exports.__esModule = true; exports.newGUID = newGUID; var _guid = 1; /** * Get the next unique ID * * @return {String} * @function newGUID */ function newGUID() { return _guid++; } },{}],112:[function(_dereq_,module,exports){ /** * @file log.js */ 'use strict'; exports.__esModule = true; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } var _globalWindow = _dereq_('global/window'); var _globalWindow2 = _interopRequireDefault(_globalWindow); /** * Log plain debug messages */ var log = function log() { _logType(null, arguments); }; /** * Keep a history of log messages * @type {Array} */ log.history = []; /** * Log error messages */ log.error = function () { _logType('error', arguments); }; /** * Log warning messages */ log.warn = function () { _logType('warn', arguments); }; /** * Log messages to the console and history based on the type of message * * @param {String} type The type of message, or `null` for `log` * @param {Object} args The args to be passed to the log * @private * @method _logType */ function _logType(type, args) { // convert args to an array to get array functions var argsArray = Array.prototype.slice.call(args); // if there's no console then don't try to output messages // they will still be stored in log.history // Was setting these once outside of this function, but containing them // in the function makes it easier to test cases where console doesn't exist var noop = function noop() {}; var console = _globalWindow2['default']['console'] || { 'log': noop, 'warn': noop, 'error': noop }; if (type) { // add the type to the front of the message argsArray.unshift(type.toUpperCase() + ':'); } else { // default to log with no prefix type = 'log'; } // add to history log.history.push(argsArray); // add console prefix after adding to history argsArray.unshift('VIDEOJS:'); // call appropriate log function if (console[type].apply) { console[type].apply(console, argsArray); } else { // ie8 doesn't allow error.apply, but it will just join() the array anyway console[type](argsArray.join(' ')); } } exports['default'] = log; module.exports = exports['default']; },{"global/window":2}],113:[function(_dereq_,module,exports){ /** * @file merge-options.js */ 'use strict'; exports.__esModule = true; exports['default'] = mergeOptions; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } var _lodashCompatObjectMerge = _dereq_('lodash-compat/object/merge'); var _lodashCompatObjectMerge2 = _interopRequireDefault(_lodashCompatObjectMerge); function isPlain(obj) { return !!obj && typeof obj === 'object' && obj.toString() === '[object Object]' && obj.constructor === Object; } /** * Merge customizer. video.js simply overwrites non-simple objects * (like arrays) instead of attempting to overlay them. * @see https://lodash.com/docs#merge */ var customizer = function customizer(destination, source) { // If we're not working with a plain object, copy the value as is // If source is an array, for instance, it will replace destination if (!isPlain(source)) { return source; } // If the new value is a plain object but the first object value is not // we need to create a new object for the first object to merge with. // This makes it consistent with how merge() works by default // and also protects from later changes the to first object affecting // the second object's values. if (!isPlain(destination)) { return mergeOptions(source); } }; /** * Merge one or more options objects, recursively merging **only** * plain object properties. Previously `deepMerge`. * * @param {...Object} source One or more objects to merge * @returns {Object} a new object that is the union of all * provided objects * @function mergeOptions */ function mergeOptions() { // contruct the call dynamically to handle the variable number of // objects to merge var args = Array.prototype.slice.call(arguments); // unshift an empty object into the front of the call as the target // of the merge args.unshift({}); // customize conflict resolution to match our historical merge behavior args.push(customizer); _lodashCompatObjectMerge2['default'].apply(null, args); // return the mutated result object return args[0]; } module.exports = exports['default']; },{"lodash-compat/object/merge":37}],114:[function(_dereq_,module,exports){ 'use strict'; exports.__esModule = true; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } var _globalDocument = _dereq_('global/document'); var _globalDocument2 = _interopRequireDefault(_globalDocument); var createStyleElement = function createStyleElement(className) { var style = _globalDocument2['default'].createElement('style'); style.className = className; return style; }; exports.createStyleElement = createStyleElement; var setTextContent = function setTextContent(el, content) { if (el.styleSheet) { el.styleSheet.cssText = content; } else { el.textContent = content; } }; exports.setTextContent = setTextContent; },{"global/document":1}],115:[function(_dereq_,module,exports){ /** * @file time-ranges.js * * Should create a fake TimeRange object * Mimics an HTML5 time range instance, which has functions that * return the start and end times for a range * TimeRanges are returned by the buffered() method * * @param {Number} start Start time in seconds * @param {Number} end End time in seconds * @return {Object} Fake TimeRange object * @private * @method createTimeRange */ 'use strict'; exports.__esModule = true; exports.createTimeRange = createTimeRange; function createTimeRange(_start, _end) { if (_start === undefined && _end === undefined) { return { length: 0, start: function start() { throw new Error('This TimeRanges object is empty'); }, end: function end() { throw new Error('This TimeRanges object is empty'); } }; } return { length: 1, start: function start() { return _start; }, end: function end() { return _end; } }; } },{}],116:[function(_dereq_,module,exports){ /** * @file to-title-case.js * * Uppercase the first letter of a string * * @param {String} string String to be uppercased * @return {String} * @private * @method toTitleCase */ "use strict"; exports.__esModule = true; function toTitleCase(string) { return string.charAt(0).toUpperCase() + string.slice(1); } exports["default"] = toTitleCase; module.exports = exports["default"]; },{}],117:[function(_dereq_,module,exports){ /** * @file url.js */ 'use strict'; exports.__esModule = true; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } var _globalDocument = _dereq_('global/document'); var _globalDocument2 = _interopRequireDefault(_globalDocument); /** * Resolve and parse the elements of a URL * * @param {String} url The url to parse * @return {Object} An object of url details * @method parseUrl */ var parseUrl = function parseUrl(url) { var props = ['protocol', 'hostname', 'port', 'pathname', 'search', 'hash', 'host']; // add the url to an anchor and let the browser parse the URL var a = _globalDocument2['default'].createElement('a'); a.href = url; // IE8 (and 9?) Fix // ie8 doesn't parse the URL correctly until the anchor is actually // added to the body, and an innerHTML is needed to trigger the parsing var addToBody = a.host === '' && a.protocol !== 'file:'; var div = undefined; if (addToBody) { div = _globalDocument2['default'].createElement('div'); div.innerHTML = '<a href="' + url + '"></a>'; a = div.firstChild; // prevent the div from affecting layout div.setAttribute('style', 'display:none; position:absolute;'); _globalDocument2['default'].body.appendChild(div); } // Copy the specific URL properties to a new object // This is also needed for IE8 because the anchor loses its // properties when it's removed from the dom var details = {}; for (var i = 0; i < props.length; i++) { details[props[i]] = a[props[i]]; } // IE9 adds the port to the host property unlike everyone else. If // a port identifier is added for standard ports, strip it. if (details.protocol === 'http:') { details.host = details.host.replace(/:80$/, ''); } if (details.protocol === 'https:') { details.host = details.host.replace(/:443$/, ''); } if (addToBody) { _globalDocument2['default'].body.removeChild(div); } return details; }; exports.parseUrl = parseUrl; /** * Get absolute version of relative URL. Used to tell flash correct URL. * http://stackoverflow.com/questions/470832/getting-an-absolute-url-from-a-relative-one-ie6-issue * * @param {String} url URL to make absolute * @return {String} Absolute URL * @private * @method getAbsoluteURL */ var getAbsoluteURL = function getAbsoluteURL(url) { // Check if absolute URL if (!url.match(/^https?:\/\//)) { // Convert to absolute URL. Flash hosted off-site needs an absolute URL. var div = _globalDocument2['default'].createElement('div'); div.innerHTML = '<a href="' + url + '">x</a>'; url = div.firstChild.href; } return url; }; exports.getAbsoluteURL = getAbsoluteURL; /** * Returns the extension of the passed file name. It will return an empty string if you pass an invalid path * * @param {String} path The fileName path like '/path/to/file.mp4' * @returns {String} The extension in lower case or an empty string if no extension could be found. * @method getFileExtension */ var getFileExtension = function getFileExtension(path) { if (typeof path === 'string') { var splitPathRe = /^(\/?)([\s\S]*?)((?:\.{1,2}|[^\/]+?)(\.([^\.\/\?]+)))(?:[\/]*|[\?].*)$/i; var pathParts = splitPathRe.exec(path); if (pathParts) { return pathParts.pop().toLowerCase(); } } return ''; }; exports.getFileExtension = getFileExtension; },{"global/document":1}],118:[function(_dereq_,module,exports){ /** * @file video.js */ 'use strict'; exports.__esModule = true; function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj['default'] = obj; return newObj; } } function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } var _globalDocument = _dereq_('global/document'); var _globalDocument2 = _interopRequireDefault(_globalDocument); var _setup = _dereq_('./setup'); var setup = _interopRequireWildcard(_setup); var _utilsStylesheetJs = _dereq_('./utils/stylesheet.js'); var stylesheet = _interopRequireWildcard(_utilsStylesheetJs); var _component = _dereq_('./component'); var _component2 = _interopRequireDefault(_component); var _eventTarget = _dereq_('./event-target'); var _eventTarget2 = _interopRequireDefault(_eventTarget); var _utilsEventsJs = _dereq_('./utils/events.js'); var Events = _interopRequireWildcard(_utilsEventsJs); var _player = _dereq_('./player'); var _player2 = _interopRequireDefault(_player); var _pluginsJs = _dereq_('./plugins.js'); var _pluginsJs2 = _interopRequireDefault(_pluginsJs); var _srcJsUtilsMergeOptionsJs = _dereq_('../../src/js/utils/merge-options.js'); var _srcJsUtilsMergeOptionsJs2 = _interopRequireDefault(_srcJsUtilsMergeOptionsJs); var _utilsFnJs = _dereq_('./utils/fn.js'); var Fn = _interopRequireWildcard(_utilsFnJs); var _objectAssign = _dereq_('object.assign'); var _objectAssign2 = _interopRequireDefault(_objectAssign); var _utilsTimeRangesJs = _dereq_('./utils/time-ranges.js'); var _utilsFormatTimeJs = _dereq_('./utils/format-time.js'); var _utilsFormatTimeJs2 = _interopRequireDefault(_utilsFormatTimeJs); var _utilsLogJs = _dereq_('./utils/log.js'); var _utilsLogJs2 = _interopRequireDefault(_utilsLogJs); var _xhrJs = _dereq_('./xhr.js'); var _xhrJs2 = _interopRequireDefault(_xhrJs); var _utilsDomJs = _dereq_('./utils/dom.js'); var Dom = _interopRequireWildcard(_utilsDomJs); var _utilsBrowserJs = _dereq_('./utils/browser.js'); var browser = _interopRequireWildcard(_utilsBrowserJs); var _utilsUrlJs = _dereq_('./utils/url.js'); var Url = _interopRequireWildcard(_utilsUrlJs); var _extendsJs = _dereq_('./extends.js'); var _extendsJs2 = _interopRequireDefault(_extendsJs); var _lodashCompatObjectMerge = _dereq_('lodash-compat/object/merge'); var _lodashCompatObjectMerge2 = _interopRequireDefault(_lodashCompatObjectMerge); var _utilsCreateDeprecationProxyJs = _dereq_('./utils/create-deprecation-proxy.js'); var _utilsCreateDeprecationProxyJs2 = _interopRequireDefault(_utilsCreateDeprecationProxyJs); // Include the built-in techs var _techHtml5Js = _dereq_('./tech/html5.js'); var _techHtml5Js2 = _interopRequireDefault(_techHtml5Js); var _techFlashJs = _dereq_('./tech/flash.js'); var _techFlashJs2 = _interopRequireDefault(_techFlashJs); // HTML5 Element Shim for IE8 if (typeof HTMLVideoElement === 'undefined') { _globalDocument2['default'].createElement('video'); _globalDocument2['default'].createElement('audio'); _globalDocument2['default'].createElement('track'); } /** * Doubles as the main function for users to create a player instance and also * the main library object. * The `videojs` function can be used to initialize or retrieve a player. * ```js * var myPlayer = videojs('my_video_id'); * ``` * * @param {String|Element} id Video element or video element ID * @param {Object=} options Optional options object for config/settings * @param {Function=} ready Optional ready callback * @return {Player} A player instance * @mixes videojs * @method videojs */ var videojs = function videojs(id, options, ready) { var tag; // Element of ID // Allow for element or ID to be passed in // String ID if (typeof id === 'string') { // Adjust for jQuery ID syntax if (id.indexOf('#') === 0) { id = id.slice(1); } // If a player instance has already been created for this ID return it. if (videojs.getPlayers()[id]) { // If options or ready funtion are passed, warn if (options) { _utilsLogJs2['default'].warn('Player "' + id + '" is already initialised. Options will not be applied.'); } if (ready) { videojs.getPlayers()[id].ready(ready); } return videojs.getPlayers()[id]; // Otherwise get element for ID } else { tag = Dom.getEl(id); } // ID is a media element } else { tag = id; } // Check for a useable element if (!tag || !tag.nodeName) { // re: nodeName, could be a box div also throw new TypeError('The element or ID supplied is not valid. (videojs)'); // Returns } // Element may have a player attr referring to an already created player instance. // If not, set up a new player and return the instance. return tag['player'] || new _player2['default'](tag, options, ready); }; // Add default styles var style = stylesheet.createStyleElement('vjs-styles-defaults'); var head = _globalDocument2['default'].querySelector('head'); head.insertBefore(style, head.firstChild); stylesheet.setTextContent(style, '\n .video-js {\n width: 300px;\n height: 150px;\n'); // Run Auto-load players // You have to wait at least once in case this script is loaded after your video in the DOM (weird behavior only with minified version) setup.autoSetupTimeout(1, videojs); /* * Current software version (semver) * * @type {String} */ videojs.VERSION = '5.0.0-rc.80'; /** * The global options object. These are the settings that take effect * if no overrides are specified when the player is created. * * ```js * videojs.options.autoplay = true * // -> all players will autoplay by default * ``` * * @type {Object} */ videojs.options = _player2['default'].prototype.options_; /** * Get an object with the currently created players, keyed by player ID * * @return {Object} The created players * @mixes videojs * @method getPlayers */ videojs.getPlayers = function () { return _player2['default'].players; }; /** * For backward compatibility, expose players object. * * @deprecated * @memberOf videojs * @property {Object|Proxy} players */ videojs.players = _utilsCreateDeprecationProxyJs2['default'](_player2['default'].players, { get: 'Access to videojs.players is deprecated; use videojs.getPlayers instead', set: 'Modification of videojs.players is deprecated' }); /** * Get a component class object by name * ```js * var VjsButton = videojs.getComponent('Button'); * // Create a new instance of the component * var myButton = new VjsButton(myPlayer); * ``` * * @return {Component} Component identified by name * @mixes videojs * @method getComponent */ videojs.getComponent = _component2['default'].getComponent; /** * Register a component so it can referred to by name * Used when adding to other * components, either through addChild * `component.addChild('myComponent')` * or through default children options * `{ children: ['myComponent'] }`. * ```js * // Get a component to subclass * var VjsButton = videojs.getComponent('Button'); * // Subclass the component (see 'extends' doc for more info) * var MySpecialButton = videojs.extends(VjsButton, {}); * // Register the new component * VjsButton.registerComponent('MySepcialButton', MySepcialButton); * // (optionally) add the new component as a default player child * myPlayer.addChild('MySepcialButton'); * ``` * NOTE: You could also just initialize the component before adding. * `component.addChild(new MyComponent());` * * @param {String} The class name of the component * @param {Component} The component class * @return {Component} The newly registered component * @mixes videojs * @method registerComponent */ videojs.registerComponent = _component2['default'].registerComponent; /** * A suite of browser and device tests * * @type {Object} * @private */ videojs.browser = browser; /** * Whether or not the browser supports touch events. Included for backward * compatibility with 4.x, but deprecated. Use `videojs.browser.TOUCH_ENABLED` * instead going forward. * * @deprecated * @type {Boolean} */ videojs.TOUCH_ENABLED = browser.TOUCH_ENABLED; /** * Subclass an existing class * Mimics ES6 subclassing with the `extends` keyword * ```js * // Create a basic javascript 'class' * function MyClass(name){ * // Set a property at initialization * this.myName = name; * } * // Create an instance method * MyClass.prototype.sayMyName = function(){ * alert(this.myName); * }; * // Subclass the exisitng class and change the name * // when initializing * var MySubClass = videojs.extends(MyClass, { * constructor: function(name) { * // Call the super class constructor for the subclass * MyClass.call(this, name) * } * }); * // Create an instance of the new sub class * var myInstance = new MySubClass('John'); * myInstance.sayMyName(); // -> should alert "John" * ``` * * @param {Function} The Class to subclass * @param {Object} An object including instace methods for the new class * Optionally including a `constructor` function * @return {Function} The newly created subclass * @mixes videojs * @method extends */ videojs['extends'] = _extendsJs2['default']; /** * Merge two options objects recursively * Performs a deep merge like lodash.merge but **only merges plain objects** * (not arrays, elements, anything else) * Other values will be copied directly from the second object. * ```js * var defaultOptions = { * foo: true, * bar: { * a: true, * b: [1,2,3] * } * }; * var newOptions = { * foo: false, * bar: { * b: [4,5,6] * } * }; * var result = videojs.mergeOptions(defaultOptions, newOptions); * // result.foo = false; * // result.bar.a = true; * // result.bar.b = [4,5,6]; * ``` * * @param {Object} The options object whose values will be overriden * @param {Object} The options object with values to override the first * @param {Object} Any number of additional options objects * * @return {Object} a new object with the merged values * @mixes videojs * @method mergeOptions */ videojs.mergeOptions = _srcJsUtilsMergeOptionsJs2['default']; /** * Change the context (this) of a function * * videojs.bind(newContext, function(){ * this === newContext * }); * * NOTE: as of v5.0 we require an ES5 shim, so you should use the native * `function(){}.bind(newContext);` instead of this. * * @param {*} context The object to bind as scope * @param {Function} fn The function to be bound to a scope * @param {Number=} uid An optional unique ID for the function to be set * @return {Function} */ videojs.bind = Fn.bind; /** * Create a Video.js player plugin * Plugins are only initialized when options for the plugin are included * in the player options, or the plugin function on the player instance is * called. * **See the plugin guide in the docs for a more detailed example** * ```js * // Make a plugin that alerts when the player plays * videojs.plugin('myPlugin', function(myPluginOptions) { * myPluginOptions = myPluginOptions || {}; * * var player = this; * var alertText = myPluginOptions.text || 'Player is playing!' * * player.on('play', function(){ * alert(alertText); * }); * }); * // USAGE EXAMPLES * // EXAMPLE 1: New player with plugin options, call plugin immediately * var player1 = videojs('idOne', { * myPlugin: { * text: 'Custom text!' * } * }); * // Click play * // --> Should alert 'Custom text!' * // EXAMPLE 3: New player, initialize plugin later * var player3 = videojs('idThree'); * // Click play * // --> NO ALERT * // Click pause * // Initialize plugin using the plugin function on the player instance * player3.myPlugin({ * text: 'Plugin added later!' * }); * // Click play * // --> Should alert 'Plugin added later!' * ``` * * @param {String} The plugin name * @param {Function} The plugin function that will be called with options * @mixes videojs * @method plugin */ videojs.plugin = _pluginsJs2['default']; /** * Adding languages so that they're available to all players. * ```js * videojs.addLanguage('es', { 'Hello': 'Hola' }); * ``` * * @param {String} code The language code or dictionary property * @param {Object} data The data values to be translated * @return {Object} The resulting language dictionary object * @mixes videojs * @method addLanguage */ videojs.addLanguage = function (code, data) { var _merge; code = ('' + code).toLowerCase(); return _lodashCompatObjectMerge2['default'](videojs.options.languages, (_merge = {}, _merge[code] = data, _merge))[code]; }; /** * Log debug messages. * * @param {...Object} messages One or more messages to log */ videojs.log = _utilsLogJs2['default']; /** * Creates an emulated TimeRange object. * * @param {Number} start Start time in seconds * @param {Number} end End time in seconds * @return {Object} Fake TimeRange object * @method createTimeRange */ videojs.createTimeRange = _utilsTimeRangesJs.createTimeRange; /** * Format seconds as a time string, H:MM:SS or M:SS * Supplying a guide (in seconds) will force a number of leading zeros * to cover the length of the guide * * @param {Number} seconds Number of seconds to be turned into a string * @param {Number} guide Number (in seconds) to model the string after * @return {String} Time formatted as H:MM:SS or M:SS * @method formatTime */ videojs.formatTime = _utilsFormatTimeJs2['default']; /** * Simple http request for retrieving external files (e.g. text tracks) * * ##### Example * * // using url string * videojs.xhr('http://example.com/myfile.vtt', function(error, response, responseBody){}); * * // or options block * videojs.xhr({ * uri: 'http://example.com/myfile.vtt', * method: 'GET', * responseType: 'text' * }, function(error, response, responseBody){ * if (error) { * // log the error * } else { * // successful, do something with the response * } * }); * * * API is modeled after the Raynos/xhr. * https://github.com/Raynos/xhr/blob/master/index.js * * @param {Object|String} options Options block or URL string * @param {Function} callback The callback function * @returns {Object} The request */ videojs.xhr = _xhrJs2['default']; /** * Resolve and parse the elements of a URL * * @param {String} url The url to parse * @return {Object} An object of url details * @method parseUrl */ videojs.parseUrl = Url.parseUrl; /** * Event target class. * * @type {Function} */ videojs.EventTarget = _eventTarget2['default']; /** * Add an event listener to element * It stores the handler function in a separate cache object * and adds a generic handler to the element's event, * along with a unique id (guid) to the element. * * @param {Element|Object} elem Element or object to bind listeners to * @param {String|Array} type Type of event to bind to. * @param {Function} fn Event listener. * @method on */ videojs.on = Events.on; /** * Trigger a listener only once for an event * * @param {Element|Object} elem Element or object to * @param {String|Array} type Name/type of event * @param {Function} fn Event handler function * @method one */ videojs.one = Events.one; /** * Removes event listeners from an element * * @param {Element|Object} elem Object to remove listeners from * @param {String|Array=} type Type of listener to remove. Don't include to remove all events from element. * @param {Function} fn Specific listener to remove. Don't include to remove listeners for an event type. * @method off */ videojs.off = Events.off; /** * Trigger an event for an element * * @param {Element|Object} elem Element to trigger an event on * @param {Event|Object|String} event A string (the type) or an event object with a type attribute * @param {Object} [hash] data hash to pass along with the event * @return {Boolean=} Returned only if default was prevented * @method trigger */ videojs.trigger = Events.trigger; // REMOVING: We probably should add this to the migration plugin // // Expose but deprecate the window[componentName] method for accessing components // Object.getOwnPropertyNames(Component.components).forEach(function(name){ // let component = Component.components[name]; // // // A deprecation warning as the constuctor // module.exports[name] = function(player, options, ready){ // log.warn('Using videojs.'+name+' to access the '+name+' component has been deprecated. Please use videojs.getComponent("componentName")'); // // return new Component(player, options, ready); // }; // // // Allow the prototype and class methods to be accessible still this way // // Though anything that attempts to override class methods will no longer work // assign(module.exports[name], component); // }); /* * Custom Universal Module Definition (UMD) * * Video.js will never be a non-browser lib so we can simplify UMD a bunch and * still support requirejs and browserify. This also needs to be closure * compiler compatible, so string keys are used. */ if (typeof define === 'function' && define['amd']) { define('videojs', [], function () { return videojs; }); // checking that module is an object too because of umdjs/umd#35 } else if (typeof exports === 'object' && typeof module === 'object') { module['exports'] = videojs; } exports['default'] = videojs; module.exports = exports['default']; },{"../../src/js/utils/merge-options.js":113,"./component":48,"./event-target":79,"./extends.js":80,"./player":87,"./plugins.js":88,"./setup":90,"./tech/flash.js":93,"./tech/html5.js":94,"./utils/browser.js":104,"./utils/create-deprecation-proxy.js":106,"./utils/dom.js":107,"./utils/events.js":108,"./utils/fn.js":109,"./utils/format-time.js":110,"./utils/log.js":112,"./utils/stylesheet.js":114,"./utils/time-ranges.js":115,"./utils/url.js":117,"./xhr.js":119,"global/document":1,"lodash-compat/object/merge":37,"object.assign":40}],119:[function(_dereq_,module,exports){ /** * @file xhr.js */ 'use strict'; exports.__esModule = true; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj['default'] = obj; return newObj; } } var _utilsUrlJs = _dereq_('./utils/url.js'); var Url = _interopRequireWildcard(_utilsUrlJs); var _utilsLogJs = _dereq_('./utils/log.js'); var _utilsLogJs2 = _interopRequireDefault(_utilsLogJs); var _utilsMergeOptionsJs = _dereq_('./utils/merge-options.js'); var _utilsMergeOptionsJs2 = _interopRequireDefault(_utilsMergeOptionsJs); var _globalWindow = _dereq_('global/window'); var _globalWindow2 = _interopRequireDefault(_globalWindow); /* * Simple http request for retrieving external files (e.g. text tracks) * ##### Example * // using url string * videojs.xhr('http://example.com/myfile.vtt', function(error, response, responseBody){}); * * // or options block * videojs.xhr({ * uri: 'http://example.com/myfile.vtt', * method: 'GET', * responseType: 'text' * }, function(error, response, responseBody){ * if (error) { * // log the error * } else { * // successful, do something with the response * } * }); * ///////////// * API is modeled after the Raynos/xhr, which we hope to use after * getting browserify implemented. * https://github.com/Raynos/xhr/blob/master/index.js * * @param {Object|String} options Options block or URL string * @param {Function} callback The callback function * @return {Object} The request * @method xhr */ var xhr = function xhr(options, callback) { var abortTimeout = undefined; // If options is a string it's the url if (typeof options === 'string') { options = { uri: options }; } // Merge with default options options = _utilsMergeOptionsJs2['default']({ method: 'GET', timeout: 45 * 1000 }, options); callback = callback || function () {}; var XHR = _globalWindow2['default'].XMLHttpRequest; if (typeof XHR === 'undefined') { // Shim XMLHttpRequest for older IEs XHR = function () { try { return new _globalWindow2['default'].ActiveXObject('Msxml2.XMLHTTP.6.0'); } catch (e) {} try { return new _globalWindow2['default'].ActiveXObject('Msxml2.XMLHTTP.3.0'); } catch (f) {} try { return new _globalWindow2['default'].ActiveXObject('Msxml2.XMLHTTP'); } catch (g) {} throw new Error('This browser does not support XMLHttpRequest.'); }; } var request = new XHR(); // Store a reference to the url on the request instance request.uri = options.uri; var urlInfo = Url.parseUrl(options.uri); var winLoc = _globalWindow2['default'].location; var successHandler = function successHandler() { _globalWindow2['default'].clearTimeout(abortTimeout); callback(null, request, request.response || request.responseText); }; var errorHandler = function errorHandler(err) { _globalWindow2['default'].clearTimeout(abortTimeout); if (!err || typeof err === 'string') { err = new Error(err || 'XHR Failed with a response of: ' + (request && (request.response || request.responseText))); } callback(err, request); }; // Check if url is for another domain/origin // IE8 doesn't know location.origin, so we won't rely on it here var crossOrigin = urlInfo.protocol + urlInfo.host !== winLoc.protocol + winLoc.host; // XDomainRequest -- Use for IE if XMLHTTPRequest2 isn't available // 'withCredentials' is only available in XMLHTTPRequest2 // Also XDomainRequest has a lot of gotchas, so only use if cross domain if (crossOrigin && _globalWindow2['default'].XDomainRequest && !('withCredentials' in request)) { request = new _globalWindow2['default'].XDomainRequest(); request.onload = successHandler; request.onerror = errorHandler; // These blank handlers need to be set to fix ie9 // http://cypressnorth.com/programming/internet-explorer-aborting-ajax-requests-fixed/ request.onprogress = function () {}; request.ontimeout = function () {}; // XMLHTTPRequest } else { (function () { var fileUrl = urlInfo.protocol === 'file:' || winLoc.protocol === 'file:'; request.onreadystatechange = function () { if (request.readyState === 4) { if (request.timedout) { return errorHandler('timeout'); } if (request.status === 200 || fileUrl && request.status === 0) { successHandler(); } else { errorHandler(); } } }; if (options.timeout) { abortTimeout = _globalWindow2['default'].setTimeout(function () { if (request.readyState !== 4) { request.timedout = true; request.abort(); } }, options.timeout); } })(); } // open the connection try { // Third arg is async, or ignored by XDomainRequest request.open(options.method || 'GET', options.uri, true); } catch (err) { return errorHandler(err); } // withCredentials only supported by XMLHttpRequest2 if (options.withCredentials) { request.withCredentials = true; } if (options.responseType) { request.responseType = options.responseType; } // send the request try { request.send(); } catch (err) { return errorHandler(err); } return request; }; exports['default'] = xhr; module.exports = exports['default']; },{"./utils/log.js":112,"./utils/merge-options.js":113,"./utils/url.js":117,"global/window":2}]},{},[118])(118) }); //# sourceMappingURL=video.js.map /* vtt.js - v0.12.1 (https://github.com/mozilla/vtt.js) built on 08-07-2015 */ (function(root) { var vttjs = root.vttjs = {}; var cueShim = vttjs.VTTCue; var regionShim = vttjs.VTTRegion; var oldVTTCue = root.VTTCue; var oldVTTRegion = root.VTTRegion; vttjs.shim = function() { vttjs.VTTCue = cueShim; vttjs.VTTRegion = regionShim; }; vttjs.restore = function() { vttjs.VTTCue = oldVTTCue; vttjs.VTTRegion = oldVTTRegion; }; }(this)); /** * Copyright 2013 vtt.js Contributors * * 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(root, vttjs) { var autoKeyword = "auto"; var directionSetting = { "": true, "lr": true, "rl": true }; var alignSetting = { "start": true, "middle": true, "end": true, "left": true, "right": true }; function findDirectionSetting(value) { if (typeof value !== "string") { return false; } var dir = directionSetting[value.toLowerCase()]; return dir ? value.toLowerCase() : false; } function findAlignSetting(value) { if (typeof value !== "string") { return false; } var align = alignSetting[value.toLowerCase()]; return align ? value.toLowerCase() : false; } function extend(obj) { var i = 1; for (; i < arguments.length; i++) { var cobj = arguments[i]; for (var p in cobj) { obj[p] = cobj[p]; } } return obj; } function VTTCue(startTime, endTime, text) { var cue = this; var isIE8 = (/MSIE\s8\.0/).test(navigator.userAgent); var baseObj = {}; if (isIE8) { cue = document.createElement('custom'); } else { baseObj.enumerable = true; } /** * Shim implementation specific properties. These properties are not in * the spec. */ // Lets us know when the VTTCue's data has changed in such a way that we need // to recompute its display state. This lets us compute its display state // lazily. cue.hasBeenReset = false; /** * VTTCue and TextTrackCue properties * http://dev.w3.org/html5/webvtt/#vttcue-interface */ var _id = ""; var _pauseOnExit = false; var _startTime = startTime; var _endTime = endTime; var _text = text; var _region = null; var _vertical = ""; var _snapToLines = true; var _line = "auto"; var _lineAlign = "start"; var _position = 50; var _positionAlign = "middle"; var _size = 50; var _align = "middle"; Object.defineProperty(cue, "id", extend({}, baseObj, { get: function() { return _id; }, set: function(value) { _id = "" + value; } })); Object.defineProperty(cue, "pauseOnExit", extend({}, baseObj, { get: function() { return _pauseOnExit; }, set: function(value) { _pauseOnExit = !!value; } })); Object.defineProperty(cue, "startTime", extend({}, baseObj, { get: function() { return _startTime; }, set: function(value) { if (typeof value !== "number") { throw new TypeError("Start time must be set to a number."); } _startTime = value; this.hasBeenReset = true; } })); Object.defineProperty(cue, "endTime", extend({}, baseObj, { get: function() { return _endTime; }, set: function(value) { if (typeof value !== "number") { throw new TypeError("End time must be set to a number."); } _endTime = value; this.hasBeenReset = true; } })); Object.defineProperty(cue, "text", extend({}, baseObj, { get: function() { return _text; }, set: function(value) { _text = "" + value; this.hasBeenReset = true; } })); Object.defineProperty(cue, "region", extend({}, baseObj, { get: function() { return _region; }, set: function(value) { _region = value; this.hasBeenReset = true; } })); Object.defineProperty(cue, "vertical", extend({}, baseObj, { get: function() { return _vertical; }, set: function(value) { var setting = findDirectionSetting(value); // Have to check for false because the setting an be an empty string. if (setting === false) { throw new SyntaxError("An invalid or illegal string was specified."); } _vertical = setting; this.hasBeenReset = true; } })); Object.defineProperty(cue, "snapToLines", extend({}, baseObj, { get: function() { return _snapToLines; }, set: function(value) { _snapToLines = !!value; this.hasBeenReset = true; } })); Object.defineProperty(cue, "line", extend({}, baseObj, { get: function() { return _line; }, set: function(value) { if (typeof value !== "number" && value !== autoKeyword) { throw new SyntaxError("An invalid number or illegal string was specified."); } _line = value; this.hasBeenReset = true; } })); Object.defineProperty(cue, "lineAlign", extend({}, baseObj, { get: function() { return _lineAlign; }, set: function(value) { var setting = findAlignSetting(value); if (!setting) { throw new SyntaxError("An invalid or illegal string was specified."); } _lineAlign = setting; this.hasBeenReset = true; } })); Object.defineProperty(cue, "position", extend({}, baseObj, { get: function() { return _position; }, set: function(value) { if (value < 0 || value > 100) { throw new Error("Position must be between 0 and 100."); } _position = value; this.hasBeenReset = true; } })); Object.defineProperty(cue, "positionAlign", extend({}, baseObj, { get: function() { return _positionAlign; }, set: function(value) { var setting = findAlignSetting(value); if (!setting) { throw new SyntaxError("An invalid or illegal string was specified."); } _positionAlign = setting; this.hasBeenReset = true; } })); Object.defineProperty(cue, "size", extend({}, baseObj, { get: function() { return _size; }, set: function(value) { if (value < 0 || value > 100) { throw new Error("Size must be between 0 and 100."); } _size = value; this.hasBeenReset = true; } })); Object.defineProperty(cue, "align", extend({}, baseObj, { get: function() { return _align; }, set: function(value) { var setting = findAlignSetting(value); if (!setting) { throw new SyntaxError("An invalid or illegal string was specified."); } _align = setting; this.hasBeenReset = true; } })); /** * Other <track> spec defined properties */ // http://www.whatwg.org/specs/web-apps/current-work/multipage/the-video-element.html#text-track-cue-display-state cue.displayState = undefined; if (isIE8) { return cue; } } /** * VTTCue methods */ VTTCue.prototype.getCueAsHTML = function() { // Assume WebVTT.convertCueToDOMTree is on the global. return WebVTT.convertCueToDOMTree(window, this.text); }; root.VTTCue = root.VTTCue || VTTCue; vttjs.VTTCue = VTTCue; }(this, (this.vttjs || {}))); /** * Copyright 2013 vtt.js Contributors * * 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(root, vttjs) { var scrollSetting = { "": true, "up": true }; function findScrollSetting(value) { if (typeof value !== "string") { return false; } var scroll = scrollSetting[value.toLowerCase()]; return scroll ? value.toLowerCase() : false; } function isValidPercentValue(value) { return typeof value === "number" && (value >= 0 && value <= 100); } // VTTRegion shim http://dev.w3.org/html5/webvtt/#vttregion-interface function VTTRegion() { var _width = 100; var _lines = 3; var _regionAnchorX = 0; var _regionAnchorY = 100; var _viewportAnchorX = 0; var _viewportAnchorY = 100; var _scroll = ""; Object.defineProperties(this, { "width": { enumerable: true, get: function() { return _width; }, set: function(value) { if (!isValidPercentValue(value)) { throw new Error("Width must be between 0 and 100."); } _width = value; } }, "lines": { enumerable: true, get: function() { return _lines; }, set: function(value) { if (typeof value !== "number") { throw new TypeError("Lines must be set to a number."); } _lines = value; } }, "regionAnchorY": { enumerable: true, get: function() { return _regionAnchorY; }, set: function(value) { if (!isValidPercentValue(value)) { throw new Error("RegionAnchorX must be between 0 and 100."); } _regionAnchorY = value; } }, "regionAnchorX": { enumerable: true, get: function() { return _regionAnchorX; }, set: function(value) { if(!isValidPercentValue(value)) { throw new Error("RegionAnchorY must be between 0 and 100."); } _regionAnchorX = value; } }, "viewportAnchorY": { enumerable: true, get: function() { return _viewportAnchorY; }, set: function(value) { if (!isValidPercentValue(value)) { throw new Error("ViewportAnchorY must be between 0 and 100."); } _viewportAnchorY = value; } }, "viewportAnchorX": { enumerable: true, get: function() { return _viewportAnchorX; }, set: function(value) { if (!isValidPercentValue(value)) { throw new Error("ViewportAnchorX must be between 0 and 100."); } _viewportAnchorX = value; } }, "scroll": { enumerable: true, get: function() { return _scroll; }, set: function(value) { var setting = findScrollSetting(value); // Have to check for false as an empty string is a legal value. if (setting === false) { throw new SyntaxError("An invalid or illegal string was specified."); } _scroll = setting; } } }); } root.VTTRegion = root.VTTRegion || VTTRegion; vttjs.VTTRegion = VTTRegion; }(this, (this.vttjs || {}))); /** * Copyright 2013 vtt.js Contributors * * 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. */ /* -*- Mode: Java; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ /* vim: set shiftwidth=2 tabstop=2 autoindent cindent expandtab: */ (function(global) { var _objCreate = Object.create || (function() { function F() {} return function(o) { if (arguments.length !== 1) { throw new Error('Object.create shim only accepts one parameter.'); } F.prototype = o; return new F(); }; })(); // Creates a new ParserError object from an errorData object. The errorData // object should have default code and message properties. The default message // property can be overriden by passing in a message parameter. // See ParsingError.Errors below for acceptable errors. function ParsingError(errorData, message) { this.name = "ParsingError"; this.code = errorData.code; this.message = message || errorData.message; } ParsingError.prototype = _objCreate(Error.prototype); ParsingError.prototype.constructor = ParsingError; // ParsingError metadata for acceptable ParsingErrors. ParsingError.Errors = { BadSignature: { code: 0, message: "Malformed WebVTT signature." }, BadTimeStamp: { code: 1, message: "Malformed time stamp." } }; // Try to parse input as a time stamp. function parseTimeStamp(input) { function computeSeconds(h, m, s, f) { return (h | 0) * 3600 + (m | 0) * 60 + (s | 0) + (f | 0) / 1000; } var m = input.match(/^(\d+):(\d{2})(:\d{2})?\.(\d{3})/); if (!m) { return null; } if (m[3]) { // Timestamp takes the form of [hours]:[minutes]:[seconds].[milliseconds] return computeSeconds(m[1], m[2], m[3].replace(":", ""), m[4]); } else if (m[1] > 59) { // Timestamp takes the form of [hours]:[minutes].[milliseconds] // First position is hours as it's over 59. return computeSeconds(m[1], m[2], 0, m[4]); } else { // Timestamp takes the form of [minutes]:[seconds].[milliseconds] return computeSeconds(0, m[1], m[2], m[4]); } } // A settings object holds key/value pairs and will ignore anything but the first // assignment to a specific key. function Settings() { this.values = _objCreate(null); } Settings.prototype = { // Only accept the first assignment to any key. set: function(k, v) { if (!this.get(k) && v !== "") { this.values[k] = v; } }, // Return the value for a key, or a default value. // If 'defaultKey' is passed then 'dflt' is assumed to be an object with // a number of possible default values as properties where 'defaultKey' is // the key of the property that will be chosen; otherwise it's assumed to be // a single value. get: function(k, dflt, defaultKey) { if (defaultKey) { return this.has(k) ? this.values[k] : dflt[defaultKey]; } return this.has(k) ? this.values[k] : dflt; }, // Check whether we have a value for a key. has: function(k) { return k in this.values; }, // Accept a setting if its one of the given alternatives. alt: function(k, v, a) { for (var n = 0; n < a.length; ++n) { if (v === a[n]) { this.set(k, v); break; } } }, // Accept a setting if its a valid (signed) integer. integer: function(k, v) { if (/^-?\d+$/.test(v)) { // integer this.set(k, parseInt(v, 10)); } }, // Accept a setting if its a valid percentage. percent: function(k, v) { var m; if ((m = v.match(/^([\d]{1,3})(\.[\d]*)?%$/))) { v = parseFloat(v); if (v >= 0 && v <= 100) { this.set(k, v); return true; } } return false; } }; // Helper function to parse input into groups separated by 'groupDelim', and // interprete each group as a key/value pair separated by 'keyValueDelim'. function parseOptions(input, callback, keyValueDelim, groupDelim) { var groups = groupDelim ? input.split(groupDelim) : [input]; for (var i in groups) { if (typeof groups[i] !== "string") { continue; } var kv = groups[i].split(keyValueDelim); if (kv.length !== 2) { continue; } var k = kv[0]; var v = kv[1]; callback(k, v); } } function parseCue(input, cue, regionList) { // Remember the original input if we need to throw an error. var oInput = input; // 4.1 WebVTT timestamp function consumeTimeStamp() { var ts = parseTimeStamp(input); if (ts === null) { throw new ParsingError(ParsingError.Errors.BadTimeStamp, "Malformed timestamp: " + oInput); } // Remove time stamp from input. input = input.replace(/^[^\sa-zA-Z-]+/, ""); return ts; } // 4.4.2 WebVTT cue settings function consumeCueSettings(input, cue) { var settings = new Settings(); parseOptions(input, function (k, v) { switch (k) { case "region": // Find the last region we parsed with the same region id. for (var i = regionList.length - 1; i >= 0; i--) { if (regionList[i].id === v) { settings.set(k, regionList[i].region); break; } } break; case "vertical": settings.alt(k, v, ["rl", "lr"]); break; case "line": var vals = v.split(","), vals0 = vals[0]; settings.integer(k, vals0); settings.percent(k, vals0) ? settings.set("snapToLines", false) : null; settings.alt(k, vals0, ["auto"]); if (vals.length === 2) { settings.alt("lineAlign", vals[1], ["start", "middle", "end"]); } break; case "position": vals = v.split(","); settings.percent(k, vals[0]); if (vals.length === 2) { settings.alt("positionAlign", vals[1], ["start", "middle", "end"]); } break; case "size": settings.percent(k, v); break; case "align": settings.alt(k, v, ["start", "middle", "end", "left", "right"]); break; } }, /:/, /\s/); // Apply default values for any missing fields. cue.region = settings.get("region", null); cue.vertical = settings.get("vertical", ""); cue.line = settings.get("line", "auto"); cue.lineAlign = settings.get("lineAlign", "start"); cue.snapToLines = settings.get("snapToLines", true); cue.size = settings.get("size", 100); cue.align = settings.get("align", "middle"); cue.position = settings.get("position", { start: 0, left: 0, middle: 50, end: 100, right: 100 }, cue.align); cue.positionAlign = settings.get("positionAlign", { start: "start", left: "start", middle: "middle", end: "end", right: "end" }, cue.align); } function skipWhitespace() { input = input.replace(/^\s+/, ""); } // 4.1 WebVTT cue timings. skipWhitespace(); cue.startTime = consumeTimeStamp(); // (1) collect cue start time skipWhitespace(); if (input.substr(0, 3) !== "-->") { // (3) next characters must match "-->" throw new ParsingError(ParsingError.Errors.BadTimeStamp, "Malformed time stamp (time stamps must be separated by '-->'): " + oInput); } input = input.substr(3); skipWhitespace(); cue.endTime = consumeTimeStamp(); // (5) collect cue end time // 4.1 WebVTT cue settings list. skipWhitespace(); consumeCueSettings(input, cue); } var ESCAPE = { "&amp;": "&", "&lt;": "<", "&gt;": ">", "&lrm;": "\u200e", "&rlm;": "\u200f", "&nbsp;": "\u00a0" }; var TAG_NAME = { c: "span", i: "i", b: "b", u: "u", ruby: "ruby", rt: "rt", v: "span", lang: "span" }; var TAG_ANNOTATION = { v: "title", lang: "lang" }; var NEEDS_PARENT = { rt: "ruby" }; // Parse content into a document fragment. function parseContent(window, input) { function nextToken() { // Check for end-of-string. if (!input) { return null; } // Consume 'n' characters from the input. function consume(result) { input = input.substr(result.length); return result; } var m = input.match(/^([^<]*)(<[^>]+>?)?/); // If there is some text before the next tag, return it, otherwise return // the tag. return consume(m[1] ? m[1] : m[2]); } // Unescape a string 's'. function unescape1(e) { return ESCAPE[e]; } function unescape(s) { while ((m = s.match(/&(amp|lt|gt|lrm|rlm|nbsp);/))) { s = s.replace(m[0], unescape1); } return s; } function shouldAdd(current, element) { return !NEEDS_PARENT[element.localName] || NEEDS_PARENT[element.localName] === current.localName; } // Create an element for this tag. function createElement(type, annotation) { var tagName = TAG_NAME[type]; if (!tagName) { return null; } var element = window.document.createElement(tagName); element.localName = tagName; var name = TAG_ANNOTATION[type]; if (name && annotation) { element[name] = annotation.trim(); } return element; } var rootDiv = window.document.createElement("div"), current = rootDiv, t, tagStack = []; while ((t = nextToken()) !== null) { if (t[0] === '<') { if (t[1] === "/") { // If the closing tag matches, move back up to the parent node. if (tagStack.length && tagStack[tagStack.length - 1] === t.substr(2).replace(">", "")) { tagStack.pop(); current = current.parentNode; } // Otherwise just ignore the end tag. continue; } var ts = parseTimeStamp(t.substr(1, t.length - 2)); var node; if (ts) { // Timestamps are lead nodes as well. node = window.document.createProcessingInstruction("timestamp", ts); current.appendChild(node); continue; } var m = t.match(/^<([^.\s/0-9>]+)(\.[^\s\\>]+)?([^>\\]+)?(\\?)>?$/); // If we can't parse the tag, skip to the next tag. if (!m) { continue; } // Try to construct an element, and ignore the tag if we couldn't. node = createElement(m[1], m[3]); if (!node) { continue; } // Determine if the tag should be added based on the context of where it // is placed in the cuetext. if (!shouldAdd(current, node)) { continue; } // Set the class list (as a list of classes, separated by space). if (m[2]) { node.className = m[2].substr(1).replace('.', ' '); } // Append the node to the current node, and enter the scope of the new // node. tagStack.push(m[1]); current.appendChild(node); current = node; continue; } // Text nodes are leaf nodes. current.appendChild(window.document.createTextNode(unescape(t))); } return rootDiv; } // This is a list of all the Unicode characters that have a strong // right-to-left category. What this means is that these characters are // written right-to-left for sure. It was generated by pulling all the strong // right-to-left characters out of the Unicode data table. That table can // found at: http://www.unicode.org/Public/UNIDATA/UnicodeData.txt var strongRTLChars = [0x05BE, 0x05C0, 0x05C3, 0x05C6, 0x05D0, 0x05D1, 0x05D2, 0x05D3, 0x05D4, 0x05D5, 0x05D6, 0x05D7, 0x05D8, 0x05D9, 0x05DA, 0x05DB, 0x05DC, 0x05DD, 0x05DE, 0x05DF, 0x05E0, 0x05E1, 0x05E2, 0x05E3, 0x05E4, 0x05E5, 0x05E6, 0x05E7, 0x05E8, 0x05E9, 0x05EA, 0x05F0, 0x05F1, 0x05F2, 0x05F3, 0x05F4, 0x0608, 0x060B, 0x060D, 0x061B, 0x061E, 0x061F, 0x0620, 0x0621, 0x0622, 0x0623, 0x0624, 0x0625, 0x0626, 0x0627, 0x0628, 0x0629, 0x062A, 0x062B, 0x062C, 0x062D, 0x062E, 0x062F, 0x0630, 0x0631, 0x0632, 0x0633, 0x0634, 0x0635, 0x0636, 0x0637, 0x0638, 0x0639, 0x063A, 0x063B, 0x063C, 0x063D, 0x063E, 0x063F, 0x0640, 0x0641, 0x0642, 0x0643, 0x0644, 0x0645, 0x0646, 0x0647, 0x0648, 0x0649, 0x064A, 0x066D, 0x066E, 0x066F, 0x0671, 0x0672, 0x0673, 0x0674, 0x0675, 0x0676, 0x0677, 0x0678, 0x0679, 0x067A, 0x067B, 0x067C, 0x067D, 0x067E, 0x067F, 0x0680, 0x0681, 0x0682, 0x0683, 0x0684, 0x0685, 0x0686, 0x0687, 0x0688, 0x0689, 0x068A, 0x068B, 0x068C, 0x068D, 0x068E, 0x068F, 0x0690, 0x0691, 0x0692, 0x0693, 0x0694, 0x0695, 0x0696, 0x0697, 0x0698, 0x0699, 0x069A, 0x069B, 0x069C, 0x069D, 0x069E, 0x069F, 0x06A0, 0x06A1, 0x06A2, 0x06A3, 0x06A4, 0x06A5, 0x06A6, 0x06A7, 0x06A8, 0x06A9, 0x06AA, 0x06AB, 0x06AC, 0x06AD, 0x06AE, 0x06AF, 0x06B0, 0x06B1, 0x06B2, 0x06B3, 0x06B4, 0x06B5, 0x06B6, 0x06B7, 0x06B8, 0x06B9, 0x06BA, 0x06BB, 0x06BC, 0x06BD, 0x06BE, 0x06BF, 0x06C0, 0x06C1, 0x06C2, 0x06C3, 0x06C4, 0x06C5, 0x06C6, 0x06C7, 0x06C8, 0x06C9, 0x06CA, 0x06CB, 0x06CC, 0x06CD, 0x06CE, 0x06CF, 0x06D0, 0x06D1, 0x06D2, 0x06D3, 0x06D4, 0x06D5, 0x06E5, 0x06E6, 0x06EE, 0x06EF, 0x06FA, 0x06FB, 0x06FC, 0x06FD, 0x06FE, 0x06FF, 0x0700, 0x0701, 0x0702, 0x0703, 0x0704, 0x0705, 0x0706, 0x0707, 0x0708, 0x0709, 0x070A, 0x070B, 0x070C, 0x070D, 0x070F, 0x0710, 0x0712, 0x0713, 0x0714, 0x0715, 0x0716, 0x0717, 0x0718, 0x0719, 0x071A, 0x071B, 0x071C, 0x071D, 0x071E, 0x071F, 0x0720, 0x0721, 0x0722, 0x0723, 0x0724, 0x0725, 0x0726, 0x0727, 0x0728, 0x0729, 0x072A, 0x072B, 0x072C, 0x072D, 0x072E, 0x072F, 0x074D, 0x074E, 0x074F, 0x0750, 0x0751, 0x0752, 0x0753, 0x0754, 0x0755, 0x0756, 0x0757, 0x0758, 0x0759, 0x075A, 0x075B, 0x075C, 0x075D, 0x075E, 0x075F, 0x0760, 0x0761, 0x0762, 0x0763, 0x0764, 0x0765, 0x0766, 0x0767, 0x0768, 0x0769, 0x076A, 0x076B, 0x076C, 0x076D, 0x076E, 0x076F, 0x0770, 0x0771, 0x0772, 0x0773, 0x0774, 0x0775, 0x0776, 0x0777, 0x0778, 0x0779, 0x077A, 0x077B, 0x077C, 0x077D, 0x077E, 0x077F, 0x0780, 0x0781, 0x0782, 0x0783, 0x0784, 0x0785, 0x0786, 0x0787, 0x0788, 0x0789, 0x078A, 0x078B, 0x078C, 0x078D, 0x078E, 0x078F, 0x0790, 0x0791, 0x0792, 0x0793, 0x0794, 0x0795, 0x0796, 0x0797, 0x0798, 0x0799, 0x079A, 0x079B, 0x079C, 0x079D, 0x079E, 0x079F, 0x07A0, 0x07A1, 0x07A2, 0x07A3, 0x07A4, 0x07A5, 0x07B1, 0x07C0, 0x07C1, 0x07C2, 0x07C3, 0x07C4, 0x07C5, 0x07C6, 0x07C7, 0x07C8, 0x07C9, 0x07CA, 0x07CB, 0x07CC, 0x07CD, 0x07CE, 0x07CF, 0x07D0, 0x07D1, 0x07D2, 0x07D3, 0x07D4, 0x07D5, 0x07D6, 0x07D7, 0x07D8, 0x07D9, 0x07DA, 0x07DB, 0x07DC, 0x07DD, 0x07DE, 0x07DF, 0x07E0, 0x07E1, 0x07E2, 0x07E3, 0x07E4, 0x07E5, 0x07E6, 0x07E7, 0x07E8, 0x07E9, 0x07EA, 0x07F4, 0x07F5, 0x07FA, 0x0800, 0x0801, 0x0802, 0x0803, 0x0804, 0x0805, 0x0806, 0x0807, 0x0808, 0x0809, 0x080A, 0x080B, 0x080C, 0x080D, 0x080E, 0x080F, 0x0810, 0x0811, 0x0812, 0x0813, 0x0814, 0x0815, 0x081A, 0x0824, 0x0828, 0x0830, 0x0831, 0x0832, 0x0833, 0x0834, 0x0835, 0x0836, 0x0837, 0x0838, 0x0839, 0x083A, 0x083B, 0x083C, 0x083D, 0x083E, 0x0840, 0x0841, 0x0842, 0x0843, 0x0844, 0x0845, 0x0846, 0x0847, 0x0848, 0x0849, 0x084A, 0x084B, 0x084C, 0x084D, 0x084E, 0x084F, 0x0850, 0x0851, 0x0852, 0x0853, 0x0854, 0x0855, 0x0856, 0x0857, 0x0858, 0x085E, 0x08A0, 0x08A2, 0x08A3, 0x08A4, 0x08A5, 0x08A6, 0x08A7, 0x08A8, 0x08A9, 0x08AA, 0x08AB, 0x08AC, 0x200F, 0xFB1D, 0xFB1F, 0xFB20, 0xFB21, 0xFB22, 0xFB23, 0xFB24, 0xFB25, 0xFB26, 0xFB27, 0xFB28, 0xFB2A, 0xFB2B, 0xFB2C, 0xFB2D, 0xFB2E, 0xFB2F, 0xFB30, 0xFB31, 0xFB32, 0xFB33, 0xFB34, 0xFB35, 0xFB36, 0xFB38, 0xFB39, 0xFB3A, 0xFB3B, 0xFB3C, 0xFB3E, 0xFB40, 0xFB41, 0xFB43, 0xFB44, 0xFB46, 0xFB47, 0xFB48, 0xFB49, 0xFB4A, 0xFB4B, 0xFB4C, 0xFB4D, 0xFB4E, 0xFB4F, 0xFB50, 0xFB51, 0xFB52, 0xFB53, 0xFB54, 0xFB55, 0xFB56, 0xFB57, 0xFB58, 0xFB59, 0xFB5A, 0xFB5B, 0xFB5C, 0xFB5D, 0xFB5E, 0xFB5F, 0xFB60, 0xFB61, 0xFB62, 0xFB63, 0xFB64, 0xFB65, 0xFB66, 0xFB67, 0xFB68, 0xFB69, 0xFB6A, 0xFB6B, 0xFB6C, 0xFB6D, 0xFB6E, 0xFB6F, 0xFB70, 0xFB71, 0xFB72, 0xFB73, 0xFB74, 0xFB75, 0xFB76, 0xFB77, 0xFB78, 0xFB79, 0xFB7A, 0xFB7B, 0xFB7C, 0xFB7D, 0xFB7E, 0xFB7F, 0xFB80, 0xFB81, 0xFB82, 0xFB83, 0xFB84, 0xFB85, 0xFB86, 0xFB87, 0xFB88, 0xFB89, 0xFB8A, 0xFB8B, 0xFB8C, 0xFB8D, 0xFB8E, 0xFB8F, 0xFB90, 0xFB91, 0xFB92, 0xFB93, 0xFB94, 0xFB95, 0xFB96, 0xFB97, 0xFB98, 0xFB99, 0xFB9A, 0xFB9B, 0xFB9C, 0xFB9D, 0xFB9E, 0xFB9F, 0xFBA0, 0xFBA1, 0xFBA2, 0xFBA3, 0xFBA4, 0xFBA5, 0xFBA6, 0xFBA7, 0xFBA8, 0xFBA9, 0xFBAA, 0xFBAB, 0xFBAC, 0xFBAD, 0xFBAE, 0xFBAF, 0xFBB0, 0xFBB1, 0xFBB2, 0xFBB3, 0xFBB4, 0xFBB5, 0xFBB6, 0xFBB7, 0xFBB8, 0xFBB9, 0xFBBA, 0xFBBB, 0xFBBC, 0xFBBD, 0xFBBE, 0xFBBF, 0xFBC0, 0xFBC1, 0xFBD3, 0xFBD4, 0xFBD5, 0xFBD6, 0xFBD7, 0xFBD8, 0xFBD9, 0xFBDA, 0xFBDB, 0xFBDC, 0xFBDD, 0xFBDE, 0xFBDF, 0xFBE0, 0xFBE1, 0xFBE2, 0xFBE3, 0xFBE4, 0xFBE5, 0xFBE6, 0xFBE7, 0xFBE8, 0xFBE9, 0xFBEA, 0xFBEB, 0xFBEC, 0xFBED, 0xFBEE, 0xFBEF, 0xFBF0, 0xFBF1, 0xFBF2, 0xFBF3, 0xFBF4, 0xFBF5, 0xFBF6, 0xFBF7, 0xFBF8, 0xFBF9, 0xFBFA, 0xFBFB, 0xFBFC, 0xFBFD, 0xFBFE, 0xFBFF, 0xFC00, 0xFC01, 0xFC02, 0xFC03, 0xFC04, 0xFC05, 0xFC06, 0xFC07, 0xFC08, 0xFC09, 0xFC0A, 0xFC0B, 0xFC0C, 0xFC0D, 0xFC0E, 0xFC0F, 0xFC10, 0xFC11, 0xFC12, 0xFC13, 0xFC14, 0xFC15, 0xFC16, 0xFC17, 0xFC18, 0xFC19, 0xFC1A, 0xFC1B, 0xFC1C, 0xFC1D, 0xFC1E, 0xFC1F, 0xFC20, 0xFC21, 0xFC22, 0xFC23, 0xFC24, 0xFC25, 0xFC26, 0xFC27, 0xFC28, 0xFC29, 0xFC2A, 0xFC2B, 0xFC2C, 0xFC2D, 0xFC2E, 0xFC2F, 0xFC30, 0xFC31, 0xFC32, 0xFC33, 0xFC34, 0xFC35, 0xFC36, 0xFC37, 0xFC38, 0xFC39, 0xFC3A, 0xFC3B, 0xFC3C, 0xFC3D, 0xFC3E, 0xFC3F, 0xFC40, 0xFC41, 0xFC42, 0xFC43, 0xFC44, 0xFC45, 0xFC46, 0xFC47, 0xFC48, 0xFC49, 0xFC4A, 0xFC4B, 0xFC4C, 0xFC4D, 0xFC4E, 0xFC4F, 0xFC50, 0xFC51, 0xFC52, 0xFC53, 0xFC54, 0xFC55, 0xFC56, 0xFC57, 0xFC58, 0xFC59, 0xFC5A, 0xFC5B, 0xFC5C, 0xFC5D, 0xFC5E, 0xFC5F, 0xFC60, 0xFC61, 0xFC62, 0xFC63, 0xFC64, 0xFC65, 0xFC66, 0xFC67, 0xFC68, 0xFC69, 0xFC6A, 0xFC6B, 0xFC6C, 0xFC6D, 0xFC6E, 0xFC6F, 0xFC70, 0xFC71, 0xFC72, 0xFC73, 0xFC74, 0xFC75, 0xFC76, 0xFC77, 0xFC78, 0xFC79, 0xFC7A, 0xFC7B, 0xFC7C, 0xFC7D, 0xFC7E, 0xFC7F, 0xFC80, 0xFC81, 0xFC82, 0xFC83, 0xFC84, 0xFC85, 0xFC86, 0xFC87, 0xFC88, 0xFC89, 0xFC8A, 0xFC8B, 0xFC8C, 0xFC8D, 0xFC8E, 0xFC8F, 0xFC90, 0xFC91, 0xFC92, 0xFC93, 0xFC94, 0xFC95, 0xFC96, 0xFC97, 0xFC98, 0xFC99, 0xFC9A, 0xFC9B, 0xFC9C, 0xFC9D, 0xFC9E, 0xFC9F, 0xFCA0, 0xFCA1, 0xFCA2, 0xFCA3, 0xFCA4, 0xFCA5, 0xFCA6, 0xFCA7, 0xFCA8, 0xFCA9, 0xFCAA, 0xFCAB, 0xFCAC, 0xFCAD, 0xFCAE, 0xFCAF, 0xFCB0, 0xFCB1, 0xFCB2, 0xFCB3, 0xFCB4, 0xFCB5, 0xFCB6, 0xFCB7, 0xFCB8, 0xFCB9, 0xFCBA, 0xFCBB, 0xFCBC, 0xFCBD, 0xFCBE, 0xFCBF, 0xFCC0, 0xFCC1, 0xFCC2, 0xFCC3, 0xFCC4, 0xFCC5, 0xFCC6, 0xFCC7, 0xFCC8, 0xFCC9, 0xFCCA, 0xFCCB, 0xFCCC, 0xFCCD, 0xFCCE, 0xFCCF, 0xFCD0, 0xFCD1, 0xFCD2, 0xFCD3, 0xFCD4, 0xFCD5, 0xFCD6, 0xFCD7, 0xFCD8, 0xFCD9, 0xFCDA, 0xFCDB, 0xFCDC, 0xFCDD, 0xFCDE, 0xFCDF, 0xFCE0, 0xFCE1, 0xFCE2, 0xFCE3, 0xFCE4, 0xFCE5, 0xFCE6, 0xFCE7, 0xFCE8, 0xFCE9, 0xFCEA, 0xFCEB, 0xFCEC, 0xFCED, 0xFCEE, 0xFCEF, 0xFCF0, 0xFCF1, 0xFCF2, 0xFCF3, 0xFCF4, 0xFCF5, 0xFCF6, 0xFCF7, 0xFCF8, 0xFCF9, 0xFCFA, 0xFCFB, 0xFCFC, 0xFCFD, 0xFCFE, 0xFCFF, 0xFD00, 0xFD01, 0xFD02, 0xFD03, 0xFD04, 0xFD05, 0xFD06, 0xFD07, 0xFD08, 0xFD09, 0xFD0A, 0xFD0B, 0xFD0C, 0xFD0D, 0xFD0E, 0xFD0F, 0xFD10, 0xFD11, 0xFD12, 0xFD13, 0xFD14, 0xFD15, 0xFD16, 0xFD17, 0xFD18, 0xFD19, 0xFD1A, 0xFD1B, 0xFD1C, 0xFD1D, 0xFD1E, 0xFD1F, 0xFD20, 0xFD21, 0xFD22, 0xFD23, 0xFD24, 0xFD25, 0xFD26, 0xFD27, 0xFD28, 0xFD29, 0xFD2A, 0xFD2B, 0xFD2C, 0xFD2D, 0xFD2E, 0xFD2F, 0xFD30, 0xFD31, 0xFD32, 0xFD33, 0xFD34, 0xFD35, 0xFD36, 0xFD37, 0xFD38, 0xFD39, 0xFD3A, 0xFD3B, 0xFD3C, 0xFD3D, 0xFD50, 0xFD51, 0xFD52, 0xFD53, 0xFD54, 0xFD55, 0xFD56, 0xFD57, 0xFD58, 0xFD59, 0xFD5A, 0xFD5B, 0xFD5C, 0xFD5D, 0xFD5E, 0xFD5F, 0xFD60, 0xFD61, 0xFD62, 0xFD63, 0xFD64, 0xFD65, 0xFD66, 0xFD67, 0xFD68, 0xFD69, 0xFD6A, 0xFD6B, 0xFD6C, 0xFD6D, 0xFD6E, 0xFD6F, 0xFD70, 0xFD71, 0xFD72, 0xFD73, 0xFD74, 0xFD75, 0xFD76, 0xFD77, 0xFD78, 0xFD79, 0xFD7A, 0xFD7B, 0xFD7C, 0xFD7D, 0xFD7E, 0xFD7F, 0xFD80, 0xFD81, 0xFD82, 0xFD83, 0xFD84, 0xFD85, 0xFD86, 0xFD87, 0xFD88, 0xFD89, 0xFD8A, 0xFD8B, 0xFD8C, 0xFD8D, 0xFD8E, 0xFD8F, 0xFD92, 0xFD93, 0xFD94, 0xFD95, 0xFD96, 0xFD97, 0xFD98, 0xFD99, 0xFD9A, 0xFD9B, 0xFD9C, 0xFD9D, 0xFD9E, 0xFD9F, 0xFDA0, 0xFDA1, 0xFDA2, 0xFDA3, 0xFDA4, 0xFDA5, 0xFDA6, 0xFDA7, 0xFDA8, 0xFDA9, 0xFDAA, 0xFDAB, 0xFDAC, 0xFDAD, 0xFDAE, 0xFDAF, 0xFDB0, 0xFDB1, 0xFDB2, 0xFDB3, 0xFDB4, 0xFDB5, 0xFDB6, 0xFDB7, 0xFDB8, 0xFDB9, 0xFDBA, 0xFDBB, 0xFDBC, 0xFDBD, 0xFDBE, 0xFDBF, 0xFDC0, 0xFDC1, 0xFDC2, 0xFDC3, 0xFDC4, 0xFDC5, 0xFDC6, 0xFDC7, 0xFDF0, 0xFDF1, 0xFDF2, 0xFDF3, 0xFDF4, 0xFDF5, 0xFDF6, 0xFDF7, 0xFDF8, 0xFDF9, 0xFDFA, 0xFDFB, 0xFDFC, 0xFE70, 0xFE71, 0xFE72, 0xFE73, 0xFE74, 0xFE76, 0xFE77, 0xFE78, 0xFE79, 0xFE7A, 0xFE7B, 0xFE7C, 0xFE7D, 0xFE7E, 0xFE7F, 0xFE80, 0xFE81, 0xFE82, 0xFE83, 0xFE84, 0xFE85, 0xFE86, 0xFE87, 0xFE88, 0xFE89, 0xFE8A, 0xFE8B, 0xFE8C, 0xFE8D, 0xFE8E, 0xFE8F, 0xFE90, 0xFE91, 0xFE92, 0xFE93, 0xFE94, 0xFE95, 0xFE96, 0xFE97, 0xFE98, 0xFE99, 0xFE9A, 0xFE9B, 0xFE9C, 0xFE9D, 0xFE9E, 0xFE9F, 0xFEA0, 0xFEA1, 0xFEA2, 0xFEA3, 0xFEA4, 0xFEA5, 0xFEA6, 0xFEA7, 0xFEA8, 0xFEA9, 0xFEAA, 0xFEAB, 0xFEAC, 0xFEAD, 0xFEAE, 0xFEAF, 0xFEB0, 0xFEB1, 0xFEB2, 0xFEB3, 0xFEB4, 0xFEB5, 0xFEB6, 0xFEB7, 0xFEB8, 0xFEB9, 0xFEBA, 0xFEBB, 0xFEBC, 0xFEBD, 0xFEBE, 0xFEBF, 0xFEC0, 0xFEC1, 0xFEC2, 0xFEC3, 0xFEC4, 0xFEC5, 0xFEC6, 0xFEC7, 0xFEC8, 0xFEC9, 0xFECA, 0xFECB, 0xFECC, 0xFECD, 0xFECE, 0xFECF, 0xFED0, 0xFED1, 0xFED2, 0xFED3, 0xFED4, 0xFED5, 0xFED6, 0xFED7, 0xFED8, 0xFED9, 0xFEDA, 0xFEDB, 0xFEDC, 0xFEDD, 0xFEDE, 0xFEDF, 0xFEE0, 0xFEE1, 0xFEE2, 0xFEE3, 0xFEE4, 0xFEE5, 0xFEE6, 0xFEE7, 0xFEE8, 0xFEE9, 0xFEEA, 0xFEEB, 0xFEEC, 0xFEED, 0xFEEE, 0xFEEF, 0xFEF0, 0xFEF1, 0xFEF2, 0xFEF3, 0xFEF4, 0xFEF5, 0xFEF6, 0xFEF7, 0xFEF8, 0xFEF9, 0xFEFA, 0xFEFB, 0xFEFC, 0x10800, 0x10801, 0x10802, 0x10803, 0x10804, 0x10805, 0x10808, 0x1080A, 0x1080B, 0x1080C, 0x1080D, 0x1080E, 0x1080F, 0x10810, 0x10811, 0x10812, 0x10813, 0x10814, 0x10815, 0x10816, 0x10817, 0x10818, 0x10819, 0x1081A, 0x1081B, 0x1081C, 0x1081D, 0x1081E, 0x1081F, 0x10820, 0x10821, 0x10822, 0x10823, 0x10824, 0x10825, 0x10826, 0x10827, 0x10828, 0x10829, 0x1082A, 0x1082B, 0x1082C, 0x1082D, 0x1082E, 0x1082F, 0x10830, 0x10831, 0x10832, 0x10833, 0x10834, 0x10835, 0x10837, 0x10838, 0x1083C, 0x1083F, 0x10840, 0x10841, 0x10842, 0x10843, 0x10844, 0x10845, 0x10846, 0x10847, 0x10848, 0x10849, 0x1084A, 0x1084B, 0x1084C, 0x1084D, 0x1084E, 0x1084F, 0x10850, 0x10851, 0x10852, 0x10853, 0x10854, 0x10855, 0x10857, 0x10858, 0x10859, 0x1085A, 0x1085B, 0x1085C, 0x1085D, 0x1085E, 0x1085F, 0x10900, 0x10901, 0x10902, 0x10903, 0x10904, 0x10905, 0x10906, 0x10907, 0x10908, 0x10909, 0x1090A, 0x1090B, 0x1090C, 0x1090D, 0x1090E, 0x1090F, 0x10910, 0x10911, 0x10912, 0x10913, 0x10914, 0x10915, 0x10916, 0x10917, 0x10918, 0x10919, 0x1091A, 0x1091B, 0x10920, 0x10921, 0x10922, 0x10923, 0x10924, 0x10925, 0x10926, 0x10927, 0x10928, 0x10929, 0x1092A, 0x1092B, 0x1092C, 0x1092D, 0x1092E, 0x1092F, 0x10930, 0x10931, 0x10932, 0x10933, 0x10934, 0x10935, 0x10936, 0x10937, 0x10938, 0x10939, 0x1093F, 0x10980, 0x10981, 0x10982, 0x10983, 0x10984, 0x10985, 0x10986, 0x10987, 0x10988, 0x10989, 0x1098A, 0x1098B, 0x1098C, 0x1098D, 0x1098E, 0x1098F, 0x10990, 0x10991, 0x10992, 0x10993, 0x10994, 0x10995, 0x10996, 0x10997, 0x10998, 0x10999, 0x1099A, 0x1099B, 0x1099C, 0x1099D, 0x1099E, 0x1099F, 0x109A0, 0x109A1, 0x109A2, 0x109A3, 0x109A4, 0x109A5, 0x109A6, 0x109A7, 0x109A8, 0x109A9, 0x109AA, 0x109AB, 0x109AC, 0x109AD, 0x109AE, 0x109AF, 0x109B0, 0x109B1, 0x109B2, 0x109B3, 0x109B4, 0x109B5, 0x109B6, 0x109B7, 0x109BE, 0x109BF, 0x10A00, 0x10A10, 0x10A11, 0x10A12, 0x10A13, 0x10A15, 0x10A16, 0x10A17, 0x10A19, 0x10A1A, 0x10A1B, 0x10A1C, 0x10A1D, 0x10A1E, 0x10A1F, 0x10A20, 0x10A21, 0x10A22, 0x10A23, 0x10A24, 0x10A25, 0x10A26, 0x10A27, 0x10A28, 0x10A29, 0x10A2A, 0x10A2B, 0x10A2C, 0x10A2D, 0x10A2E, 0x10A2F, 0x10A30, 0x10A31, 0x10A32, 0x10A33, 0x10A40, 0x10A41, 0x10A42, 0x10A43, 0x10A44, 0x10A45, 0x10A46, 0x10A47, 0x10A50, 0x10A51, 0x10A52, 0x10A53, 0x10A54, 0x10A55, 0x10A56, 0x10A57, 0x10A58, 0x10A60, 0x10A61, 0x10A62, 0x10A63, 0x10A64, 0x10A65, 0x10A66, 0x10A67, 0x10A68, 0x10A69, 0x10A6A, 0x10A6B, 0x10A6C, 0x10A6D, 0x10A6E, 0x10A6F, 0x10A70, 0x10A71, 0x10A72, 0x10A73, 0x10A74, 0x10A75, 0x10A76, 0x10A77, 0x10A78, 0x10A79, 0x10A7A, 0x10A7B, 0x10A7C, 0x10A7D, 0x10A7E, 0x10A7F, 0x10B00, 0x10B01, 0x10B02, 0x10B03, 0x10B04, 0x10B05, 0x10B06, 0x10B07, 0x10B08, 0x10B09, 0x10B0A, 0x10B0B, 0x10B0C, 0x10B0D, 0x10B0E, 0x10B0F, 0x10B10, 0x10B11, 0x10B12, 0x10B13, 0x10B14, 0x10B15, 0x10B16, 0x10B17, 0x10B18, 0x10B19, 0x10B1A, 0x10B1B, 0x10B1C, 0x10B1D, 0x10B1E, 0x10B1F, 0x10B20, 0x10B21, 0x10B22, 0x10B23, 0x10B24, 0x10B25, 0x10B26, 0x10B27, 0x10B28, 0x10B29, 0x10B2A, 0x10B2B, 0x10B2C, 0x10B2D, 0x10B2E, 0x10B2F, 0x10B30, 0x10B31, 0x10B32, 0x10B33, 0x10B34, 0x10B35, 0x10B40, 0x10B41, 0x10B42, 0x10B43, 0x10B44, 0x10B45, 0x10B46, 0x10B47, 0x10B48, 0x10B49, 0x10B4A, 0x10B4B, 0x10B4C, 0x10B4D, 0x10B4E, 0x10B4F, 0x10B50, 0x10B51, 0x10B52, 0x10B53, 0x10B54, 0x10B55, 0x10B58, 0x10B59, 0x10B5A, 0x10B5B, 0x10B5C, 0x10B5D, 0x10B5E, 0x10B5F, 0x10B60, 0x10B61, 0x10B62, 0x10B63, 0x10B64, 0x10B65, 0x10B66, 0x10B67, 0x10B68, 0x10B69, 0x10B6A, 0x10B6B, 0x10B6C, 0x10B6D, 0x10B6E, 0x10B6F, 0x10B70, 0x10B71, 0x10B72, 0x10B78, 0x10B79, 0x10B7A, 0x10B7B, 0x10B7C, 0x10B7D, 0x10B7E, 0x10B7F, 0x10C00, 0x10C01, 0x10C02, 0x10C03, 0x10C04, 0x10C05, 0x10C06, 0x10C07, 0x10C08, 0x10C09, 0x10C0A, 0x10C0B, 0x10C0C, 0x10C0D, 0x10C0E, 0x10C0F, 0x10C10, 0x10C11, 0x10C12, 0x10C13, 0x10C14, 0x10C15, 0x10C16, 0x10C17, 0x10C18, 0x10C19, 0x10C1A, 0x10C1B, 0x10C1C, 0x10C1D, 0x10C1E, 0x10C1F, 0x10C20, 0x10C21, 0x10C22, 0x10C23, 0x10C24, 0x10C25, 0x10C26, 0x10C27, 0x10C28, 0x10C29, 0x10C2A, 0x10C2B, 0x10C2C, 0x10C2D, 0x10C2E, 0x10C2F, 0x10C30, 0x10C31, 0x10C32, 0x10C33, 0x10C34, 0x10C35, 0x10C36, 0x10C37, 0x10C38, 0x10C39, 0x10C3A, 0x10C3B, 0x10C3C, 0x10C3D, 0x10C3E, 0x10C3F, 0x10C40, 0x10C41, 0x10C42, 0x10C43, 0x10C44, 0x10C45, 0x10C46, 0x10C47, 0x10C48, 0x1EE00, 0x1EE01, 0x1EE02, 0x1EE03, 0x1EE05, 0x1EE06, 0x1EE07, 0x1EE08, 0x1EE09, 0x1EE0A, 0x1EE0B, 0x1EE0C, 0x1EE0D, 0x1EE0E, 0x1EE0F, 0x1EE10, 0x1EE11, 0x1EE12, 0x1EE13, 0x1EE14, 0x1EE15, 0x1EE16, 0x1EE17, 0x1EE18, 0x1EE19, 0x1EE1A, 0x1EE1B, 0x1EE1C, 0x1EE1D, 0x1EE1E, 0x1EE1F, 0x1EE21, 0x1EE22, 0x1EE24, 0x1EE27, 0x1EE29, 0x1EE2A, 0x1EE2B, 0x1EE2C, 0x1EE2D, 0x1EE2E, 0x1EE2F, 0x1EE30, 0x1EE31, 0x1EE32, 0x1EE34, 0x1EE35, 0x1EE36, 0x1EE37, 0x1EE39, 0x1EE3B, 0x1EE42, 0x1EE47, 0x1EE49, 0x1EE4B, 0x1EE4D, 0x1EE4E, 0x1EE4F, 0x1EE51, 0x1EE52, 0x1EE54, 0x1EE57, 0x1EE59, 0x1EE5B, 0x1EE5D, 0x1EE5F, 0x1EE61, 0x1EE62, 0x1EE64, 0x1EE67, 0x1EE68, 0x1EE69, 0x1EE6A, 0x1EE6C, 0x1EE6D, 0x1EE6E, 0x1EE6F, 0x1EE70, 0x1EE71, 0x1EE72, 0x1EE74, 0x1EE75, 0x1EE76, 0x1EE77, 0x1EE79, 0x1EE7A, 0x1EE7B, 0x1EE7C, 0x1EE7E, 0x1EE80, 0x1EE81, 0x1EE82, 0x1EE83, 0x1EE84, 0x1EE85, 0x1EE86, 0x1EE87, 0x1EE88, 0x1EE89, 0x1EE8B, 0x1EE8C, 0x1EE8D, 0x1EE8E, 0x1EE8F, 0x1EE90, 0x1EE91, 0x1EE92, 0x1EE93, 0x1EE94, 0x1EE95, 0x1EE96, 0x1EE97, 0x1EE98, 0x1EE99, 0x1EE9A, 0x1EE9B, 0x1EEA1, 0x1EEA2, 0x1EEA3, 0x1EEA5, 0x1EEA6, 0x1EEA7, 0x1EEA8, 0x1EEA9, 0x1EEAB, 0x1EEAC, 0x1EEAD, 0x1EEAE, 0x1EEAF, 0x1EEB0, 0x1EEB1, 0x1EEB2, 0x1EEB3, 0x1EEB4, 0x1EEB5, 0x1EEB6, 0x1EEB7, 0x1EEB8, 0x1EEB9, 0x1EEBA, 0x1EEBB, 0x10FFFD]; function determineBidi(cueDiv) { var nodeStack = [], text = "", charCode; if (!cueDiv || !cueDiv.childNodes) { return "ltr"; } function pushNodes(nodeStack, node) { for (var i = node.childNodes.length - 1; i >= 0; i--) { nodeStack.push(node.childNodes[i]); } } function nextTextNode(nodeStack) { if (!nodeStack || !nodeStack.length) { return null; } var node = nodeStack.pop(), text = node.textContent || node.innerText; if (text) { // TODO: This should match all unicode type B characters (paragraph // separator characters). See issue #115. var m = text.match(/^.*(\n|\r)/); if (m) { nodeStack.length = 0; return m[0]; } return text; } if (node.tagName === "ruby") { return nextTextNode(nodeStack); } if (node.childNodes) { pushNodes(nodeStack, node); return nextTextNode(nodeStack); } } pushNodes(nodeStack, cueDiv); while ((text = nextTextNode(nodeStack))) { for (var i = 0; i < text.length; i++) { charCode = text.charCodeAt(i); for (var j = 0; j < strongRTLChars.length; j++) { if (strongRTLChars[j] === charCode) { return "rtl"; } } } } return "ltr"; } function computeLinePos(cue) { if (typeof cue.line === "number" && (cue.snapToLines || (cue.line >= 0 && cue.line <= 100))) { return cue.line; } if (!cue.track || !cue.track.textTrackList || !cue.track.textTrackList.mediaElement) { return -1; } var track = cue.track, trackList = track.textTrackList, count = 0; for (var i = 0; i < trackList.length && trackList[i] !== track; i++) { if (trackList[i].mode === "showing") { count++; } } return ++count * -1; } function StyleBox() { } // Apply styles to a div. If there is no div passed then it defaults to the // div on 'this'. StyleBox.prototype.applyStyles = function(styles, div) { div = div || this.div; for (var prop in styles) { if (styles.hasOwnProperty(prop)) { div.style[prop] = styles[prop]; } } }; StyleBox.prototype.formatStyle = function(val, unit) { return val === 0 ? 0 : val + unit; }; // Constructs the computed display state of the cue (a div). Places the div // into the overlay which should be a block level element (usually a div). function CueStyleBox(window, cue, styleOptions) { var isIE8 = (/MSIE\s8\.0/).test(navigator.userAgent); var color = "rgba(255, 255, 255, 1)"; var backgroundColor = "rgba(0, 0, 0, 0.8)"; if (isIE8) { color = "rgb(255, 255, 255)"; backgroundColor = "rgb(0, 0, 0)"; } StyleBox.call(this); this.cue = cue; // Parse our cue's text into a DOM tree rooted at 'cueDiv'. This div will // have inline positioning and will function as the cue background box. this.cueDiv = parseContent(window, cue.text); var styles = { color: color, backgroundColor: backgroundColor, position: "relative", left: 0, right: 0, top: 0, bottom: 0, display: "inline" }; if (!isIE8) { styles.writingMode = cue.vertical === "" ? "horizontal-tb" : cue.vertical === "lr" ? "vertical-lr" : "vertical-rl"; styles.unicodeBidi = "plaintext"; } this.applyStyles(styles, this.cueDiv); // Create an absolutely positioned div that will be used to position the cue // div. Note, all WebVTT cue-setting alignments are equivalent to the CSS // mirrors of them except "middle" which is "center" in CSS. this.div = window.document.createElement("div"); styles = { textAlign: cue.align === "middle" ? "center" : cue.align, font: styleOptions.font, whiteSpace: "pre-line", position: "absolute" }; if (!isIE8) { styles.direction = determineBidi(this.cueDiv); styles.writingMode = cue.vertical === "" ? "horizontal-tb" : cue.vertical === "lr" ? "vertical-lr" : "vertical-rl". stylesunicodeBidi = "plaintext"; } this.applyStyles(styles); this.div.appendChild(this.cueDiv); // Calculate the distance from the reference edge of the viewport to the text // position of the cue box. The reference edge will be resolved later when // the box orientation styles are applied. var textPos = 0; switch (cue.positionAlign) { case "start": textPos = cue.position; break; case "middle": textPos = cue.position - (cue.size / 2); break; case "end": textPos = cue.position - cue.size; break; } // Horizontal box orientation; textPos is the distance from the left edge of the // area to the left edge of the box and cue.size is the distance extending to // the right from there. if (cue.vertical === "") { this.applyStyles({ left: this.formatStyle(textPos, "%"), width: this.formatStyle(cue.size, "%") }); // Vertical box orientation; textPos is the distance from the top edge of the // area to the top edge of the box and cue.size is the height extending // downwards from there. } else { this.applyStyles({ top: this.formatStyle(textPos, "%"), height: this.formatStyle(cue.size, "%") }); } this.move = function(box) { this.applyStyles({ top: this.formatStyle(box.top, "px"), bottom: this.formatStyle(box.bottom, "px"), left: this.formatStyle(box.left, "px"), right: this.formatStyle(box.right, "px"), height: this.formatStyle(box.height, "px"), width: this.formatStyle(box.width, "px") }); }; } CueStyleBox.prototype = _objCreate(StyleBox.prototype); CueStyleBox.prototype.constructor = CueStyleBox; // Represents the co-ordinates of an Element in a way that we can easily // compute things with such as if it overlaps or intersects with another Element. // Can initialize it with either a StyleBox or another BoxPosition. function BoxPosition(obj) { var isIE8 = (/MSIE\s8\.0/).test(navigator.userAgent); // Either a BoxPosition was passed in and we need to copy it, or a StyleBox // was passed in and we need to copy the results of 'getBoundingClientRect' // as the object returned is readonly. All co-ordinate values are in reference // to the viewport origin (top left). var lh, height, width, top; if (obj.div) { height = obj.div.offsetHeight; width = obj.div.offsetWidth; top = obj.div.offsetTop; var rects = (rects = obj.div.childNodes) && (rects = rects[0]) && rects.getClientRects && rects.getClientRects(); obj = obj.div.getBoundingClientRect(); // In certain cases the outter div will be slightly larger then the sum of // the inner div's lines. This could be due to bold text, etc, on some platforms. // In this case we should get the average line height and use that. This will // result in the desired behaviour. lh = rects ? Math.max((rects[0] && rects[0].height) || 0, obj.height / rects.length) : 0; } this.left = obj.left; this.right = obj.right; this.top = obj.top || top; this.height = obj.height || height; this.bottom = obj.bottom || (top + (obj.height || height)); this.width = obj.width || width; this.lineHeight = lh !== undefined ? lh : obj.lineHeight; if (isIE8 && !this.lineHeight) { this.lineHeight = 13; } } // Move the box along a particular axis. Optionally pass in an amount to move // the box. If no amount is passed then the default is the line height of the // box. BoxPosition.prototype.move = function(axis, toMove) { toMove = toMove !== undefined ? toMove : this.lineHeight; switch (axis) { case "+x": this.left += toMove; this.right += toMove; break; case "-x": this.left -= toMove; this.right -= toMove; break; case "+y": this.top += toMove; this.bottom += toMove; break; case "-y": this.top -= toMove; this.bottom -= toMove; break; } }; // Check if this box overlaps another box, b2. BoxPosition.prototype.overlaps = function(b2) { return this.left < b2.right && this.right > b2.left && this.top < b2.bottom && this.bottom > b2.top; }; // Check if this box overlaps any other boxes in boxes. BoxPosition.prototype.overlapsAny = function(boxes) { for (var i = 0; i < boxes.length; i++) { if (this.overlaps(boxes[i])) { return true; } } return false; }; // Check if this box is within another box. BoxPosition.prototype.within = function(container) { return this.top >= container.top && this.bottom <= container.bottom && this.left >= container.left && this.right <= container.right; }; // Check if this box is entirely within the container or it is overlapping // on the edge opposite of the axis direction passed. For example, if "+x" is // passed and the box is overlapping on the left edge of the container, then // return true. BoxPosition.prototype.overlapsOppositeAxis = function(container, axis) { switch (axis) { case "+x": return this.left < container.left; case "-x": return this.right > container.right; case "+y": return this.top < container.top; case "-y": return this.bottom > container.bottom; } }; // Find the percentage of the area that this box is overlapping with another // box. BoxPosition.prototype.intersectPercentage = function(b2) { var x = Math.max(0, Math.min(this.right, b2.right) - Math.max(this.left, b2.left)), y = Math.max(0, Math.min(this.bottom, b2.bottom) - Math.max(this.top, b2.top)), intersectArea = x * y; return intersectArea / (this.height * this.width); }; // Convert the positions from this box to CSS compatible positions using // the reference container's positions. This has to be done because this // box's positions are in reference to the viewport origin, whereas, CSS // values are in referecne to their respective edges. BoxPosition.prototype.toCSSCompatValues = function(reference) { return { top: this.top - reference.top, bottom: reference.bottom - this.bottom, left: this.left - reference.left, right: reference.right - this.right, height: this.height, width: this.width }; }; // Get an object that represents the box's position without anything extra. // Can pass a StyleBox, HTMLElement, or another BoxPositon. BoxPosition.getSimpleBoxPosition = function(obj) { var height = obj.div ? obj.div.offsetHeight : obj.tagName ? obj.offsetHeight : 0; var width = obj.div ? obj.div.offsetWidth : obj.tagName ? obj.offsetWidth : 0; var top = obj.div ? obj.div.offsetTop : obj.tagName ? obj.offsetTop : 0; obj = obj.div ? obj.div.getBoundingClientRect() : obj.tagName ? obj.getBoundingClientRect() : obj; var ret = { left: obj.left, right: obj.right, top: obj.top || top, height: obj.height || height, bottom: obj.bottom || (top + (obj.height || height)), width: obj.width || width }; return ret; }; // Move a StyleBox to its specified, or next best, position. The containerBox // is the box that contains the StyleBox, such as a div. boxPositions are // a list of other boxes that the styleBox can't overlap with. function moveBoxToLinePosition(window, styleBox, containerBox, boxPositions) { // Find the best position for a cue box, b, on the video. The axis parameter // is a list of axis, the order of which, it will move the box along. For example: // Passing ["+x", "-x"] will move the box first along the x axis in the positive // direction. If it doesn't find a good position for it there it will then move // it along the x axis in the negative direction. function findBestPosition(b, axis) { var bestPosition, specifiedPosition = new BoxPosition(b), percentage = 1; // Highest possible so the first thing we get is better. for (var i = 0; i < axis.length; i++) { while (b.overlapsOppositeAxis(containerBox, axis[i]) || (b.within(containerBox) && b.overlapsAny(boxPositions))) { b.move(axis[i]); } // We found a spot where we aren't overlapping anything. This is our // best position. if (b.within(containerBox)) { return b; } var p = b.intersectPercentage(containerBox); // If we're outside the container box less then we were on our last try // then remember this position as the best position. if (percentage > p) { bestPosition = new BoxPosition(b); percentage = p; } // Reset the box position to the specified position. b = new BoxPosition(specifiedPosition); } return bestPosition || specifiedPosition; } var boxPosition = new BoxPosition(styleBox), cue = styleBox.cue, linePos = computeLinePos(cue), axis = []; // If we have a line number to align the cue to. if (cue.snapToLines) { var size; switch (cue.vertical) { case "": axis = [ "+y", "-y" ]; size = "height"; break; case "rl": axis = [ "+x", "-x" ]; size = "width"; break; case "lr": axis = [ "-x", "+x" ]; size = "width"; break; } var step = boxPosition.lineHeight, position = step * Math.round(linePos), maxPosition = containerBox[size] + step, initialAxis = axis[0]; // If the specified intial position is greater then the max position then // clamp the box to the amount of steps it would take for the box to // reach the max position. if (Math.abs(position) > maxPosition) { position = position < 0 ? -1 : 1; position *= Math.ceil(maxPosition / step) * step; } // If computed line position returns negative then line numbers are // relative to the bottom of the video instead of the top. Therefore, we // need to increase our initial position by the length or width of the // video, depending on the writing direction, and reverse our axis directions. if (linePos < 0) { position += cue.vertical === "" ? containerBox.height : containerBox.width; axis = axis.reverse(); } // Move the box to the specified position. This may not be its best // position. boxPosition.move(initialAxis, position); } else { // If we have a percentage line value for the cue. var calculatedPercentage = (boxPosition.lineHeight / containerBox.height) * 100; switch (cue.lineAlign) { case "middle": linePos -= (calculatedPercentage / 2); break; case "end": linePos -= calculatedPercentage; break; } // Apply initial line position to the cue box. switch (cue.vertical) { case "": styleBox.applyStyles({ top: styleBox.formatStyle(linePos, "%") }); break; case "rl": styleBox.applyStyles({ left: styleBox.formatStyle(linePos, "%") }); break; case "lr": styleBox.applyStyles({ right: styleBox.formatStyle(linePos, "%") }); break; } axis = [ "+y", "-x", "+x", "-y" ]; // Get the box position again after we've applied the specified positioning // to it. boxPosition = new BoxPosition(styleBox); } var bestPosition = findBestPosition(boxPosition, axis); styleBox.move(bestPosition.toCSSCompatValues(containerBox)); } function WebVTT() { // Nothing } // Helper to allow strings to be decoded instead of the default binary utf8 data. WebVTT.StringDecoder = function() { return { decode: function(data) { if (!data) { return ""; } if (typeof data !== "string") { throw new Error("Error - expected string data."); } return decodeURIComponent(encodeURIComponent(data)); } }; }; WebVTT.convertCueToDOMTree = function(window, cuetext) { if (!window || !cuetext) { return null; } return parseContent(window, cuetext); }; var FONT_SIZE_PERCENT = 0.05; var FONT_STYLE = "sans-serif"; var CUE_BACKGROUND_PADDING = "1.5%"; // Runs the processing model over the cues and regions passed to it. // @param overlay A block level element (usually a div) that the computed cues // and regions will be placed into. WebVTT.processCues = function(window, cues, overlay) { if (!window || !cues || !overlay) { return null; } // Remove all previous children. while (overlay.firstChild) { overlay.removeChild(overlay.firstChild); } var paddedOverlay = window.document.createElement("div"); paddedOverlay.style.position = "absolute"; paddedOverlay.style.left = "0"; paddedOverlay.style.right = "0"; paddedOverlay.style.top = "0"; paddedOverlay.style.bottom = "0"; paddedOverlay.style.margin = CUE_BACKGROUND_PADDING; overlay.appendChild(paddedOverlay); // Determine if we need to compute the display states of the cues. This could // be the case if a cue's state has been changed since the last computation or // if it has not been computed yet. function shouldCompute(cues) { for (var i = 0; i < cues.length; i++) { if (cues[i].hasBeenReset || !cues[i].displayState) { return true; } } return false; } // We don't need to recompute the cues' display states. Just reuse them. if (!shouldCompute(cues)) { for (var i = 0; i < cues.length; i++) { paddedOverlay.appendChild(cues[i].displayState); } return; } var boxPositions = [], containerBox = BoxPosition.getSimpleBoxPosition(paddedOverlay), fontSize = Math.round(containerBox.height * FONT_SIZE_PERCENT * 100) / 100; var styleOptions = { font: fontSize + "px " + FONT_STYLE }; (function() { var styleBox, cue; for (var i = 0; i < cues.length; i++) { cue = cues[i]; // Compute the intial position and styles of the cue div. styleBox = new CueStyleBox(window, cue, styleOptions); paddedOverlay.appendChild(styleBox.div); // Move the cue div to it's correct line position. moveBoxToLinePosition(window, styleBox, containerBox, boxPositions); // Remember the computed div so that we don't have to recompute it later // if we don't have too. cue.displayState = styleBox.div; boxPositions.push(BoxPosition.getSimpleBoxPosition(styleBox)); } })(); }; WebVTT.Parser = function(window, vttjs, decoder) { if (!decoder) { decoder = vttjs; vttjs = {}; } if (!vttjs) { vttjs = {}; } this.window = window; this.vttjs = vttjs; this.state = "INITIAL"; this.buffer = ""; this.decoder = decoder || new TextDecoder("utf8"); this.regionList = []; }; WebVTT.Parser.prototype = { // If the error is a ParsingError then report it to the consumer if // possible. If it's not a ParsingError then throw it like normal. reportOrThrowError: function(e) { if (e instanceof ParsingError) { this.onparsingerror && this.onparsingerror(e); } else { throw e; } }, parse: function (data) { var self = this; // If there is no data then we won't decode it, but will just try to parse // whatever is in buffer already. This may occur in circumstances, for // example when flush() is called. if (data) { // Try to decode the data that we received. self.buffer += self.decoder.decode(data, {stream: true}); } function collectNextLine() { var buffer = self.buffer; var pos = 0; while (pos < buffer.length && buffer[pos] !== '\r' && buffer[pos] !== '\n') { ++pos; } var line = buffer.substr(0, pos); // Advance the buffer early in case we fail below. if (buffer[pos] === '\r') { ++pos; } if (buffer[pos] === '\n') { ++pos; } self.buffer = buffer.substr(pos); return line; } // 3.4 WebVTT region and WebVTT region settings syntax function parseRegion(input) { var settings = new Settings(); parseOptions(input, function (k, v) { switch (k) { case "id": settings.set(k, v); break; case "width": settings.percent(k, v); break; case "lines": settings.integer(k, v); break; case "regionanchor": case "viewportanchor": var xy = v.split(','); if (xy.length !== 2) { break; } // We have to make sure both x and y parse, so use a temporary // settings object here. var anchor = new Settings(); anchor.percent("x", xy[0]); anchor.percent("y", xy[1]); if (!anchor.has("x") || !anchor.has("y")) { break; } settings.set(k + "X", anchor.get("x")); settings.set(k + "Y", anchor.get("y")); break; case "scroll": settings.alt(k, v, ["up"]); break; } }, /=/, /\s/); // Create the region, using default values for any values that were not // specified. if (settings.has("id")) { var region = new (self.vttjs.VTTRegion || self.window.VTTRegion)(); region.width = settings.get("width", 100); region.lines = settings.get("lines", 3); region.regionAnchorX = settings.get("regionanchorX", 0); region.regionAnchorY = settings.get("regionanchorY", 100); region.viewportAnchorX = settings.get("viewportanchorX", 0); region.viewportAnchorY = settings.get("viewportanchorY", 100); region.scroll = settings.get("scroll", ""); // Register the region. self.onregion && self.onregion(region); // Remember the VTTRegion for later in case we parse any VTTCues that // reference it. self.regionList.push({ id: settings.get("id"), region: region }); } } // 3.2 WebVTT metadata header syntax function parseHeader(input) { parseOptions(input, function (k, v) { switch (k) { case "Region": // 3.3 WebVTT region metadata header syntax parseRegion(v); break; } }, /:/); } // 5.1 WebVTT file parsing. try { var line; if (self.state === "INITIAL") { // We can't start parsing until we have the first line. if (!/\r\n|\n/.test(self.buffer)) { return this; } line = collectNextLine(); var m = line.match(/^WEBVTT([ \t].*)?$/); if (!m || !m[0]) { throw new ParsingError(ParsingError.Errors.BadSignature); } self.state = "HEADER"; } var alreadyCollectedLine = false; while (self.buffer) { // We can't parse a line until we have the full line. if (!/\r\n|\n/.test(self.buffer)) { return this; } if (!alreadyCollectedLine) { line = collectNextLine(); } else { alreadyCollectedLine = false; } switch (self.state) { case "HEADER": // 13-18 - Allow a header (metadata) under the WEBVTT line. if (/:/.test(line)) { parseHeader(line); } else if (!line) { // An empty line terminates the header and starts the body (cues). self.state = "ID"; } continue; case "NOTE": // Ignore NOTE blocks. if (!line) { self.state = "ID"; } continue; case "ID": // Check for the start of NOTE blocks. if (/^NOTE($|[ \t])/.test(line)) { self.state = "NOTE"; break; } // 19-29 - Allow any number of line terminators, then initialize new cue values. if (!line) { continue; } self.cue = new (self.vttjs.VTTCue || self.window.VTTCue)(0, 0, ""); self.state = "CUE"; // 30-39 - Check if self line contains an optional identifier or timing data. if (line.indexOf("-->") === -1) { self.cue.id = line; continue; } // Process line as start of a cue. /*falls through*/ case "CUE": // 40 - Collect cue timings and settings. try { parseCue(line, self.cue, self.regionList); } catch (e) { self.reportOrThrowError(e); // In case of an error ignore rest of the cue. self.cue = null; self.state = "BADCUE"; continue; } self.state = "CUETEXT"; continue; case "CUETEXT": var hasSubstring = line.indexOf("-->") !== -1; // 34 - If we have an empty line then report the cue. // 35 - If we have the special substring '-->' then report the cue, // but do not collect the line as we need to process the current // one as a new cue. if (!line || hasSubstring && (alreadyCollectedLine = true)) { // We are done parsing self cue. self.oncue && self.oncue(self.cue); self.cue = null; self.state = "ID"; continue; } if (self.cue.text) { self.cue.text += "\n"; } self.cue.text += line; continue; case "BADCUE": // BADCUE // 54-62 - Collect and discard the remaining cue. if (!line) { self.state = "ID"; } continue; } } } catch (e) { self.reportOrThrowError(e); // If we are currently parsing a cue, report what we have. if (self.state === "CUETEXT" && self.cue && self.oncue) { self.oncue(self.cue); } self.cue = null; // Enter BADWEBVTT state if header was not parsed correctly otherwise // another exception occurred so enter BADCUE state. self.state = self.state === "INITIAL" ? "BADWEBVTT" : "BADCUE"; } return this; }, flush: function () { var self = this; try { // Finish decoding the stream. self.buffer += self.decoder.decode(); // Synthesize the end of the current cue or region. if (self.cue || self.state === "HEADER") { self.buffer += "\n\n"; self.parse(); } // If we've flushed, parsed, and we're still on the INITIAL state then // that means we don't have enough of the stream to parse the first // line. if (self.state === "INITIAL") { throw new ParsingError(ParsingError.Errors.BadSignature); } } catch(e) { self.reportOrThrowError(e); } self.onflush && self.onflush(); return this; } }; global.WebVTT = WebVTT; }(this, (this.vttjs || {})));
ajax/libs/rxjs/2.2.27/rx.all.compat.js
andersem/cdnjs
// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.txt in the project root for license information. ;(function (undefined) { var objectTypes = { 'boolean': false, 'function': true, 'object': true, 'number': false, 'string': false, 'undefined': false }; var root = (objectTypes[typeof window] && window) || this, freeExports = objectTypes[typeof exports] && exports && !exports.nodeType && exports, freeModule = objectTypes[typeof module] && module && !module.nodeType && module, moduleExports = freeModule && freeModule.exports === freeExports && freeExports, freeGlobal = objectTypes[typeof global] && global; if (freeGlobal && (freeGlobal.global === freeGlobal || freeGlobal.window === freeGlobal)) { root = freeGlobal; } var Rx = { internals: {}, config: { Promise: root.Promise // Detect if promise exists }, helpers: { } }; // Defaults var noop = Rx.helpers.noop = function () { }, identity = Rx.helpers.identity = function (x) { return x; }, pluck = Rx.helpers.pluck = function (property) { return function (x) { return x[property]; }; }, just = Rx.helpers.just = function (value) { return function () { return value; }; }, 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.then === 'function' && p.then !== Rx.Observable.prototype.then; }, asArray = Rx.helpers.asArray = function () { return Array.prototype.slice.call(arguments); }, not = Rx.helpers.not = function (a) { return !a; }; // Errors var sequenceContainsNoElements = 'Sequence contains no elements.'; var argumentOutOfRange = 'Argument out of range'; var objectDisposed = 'Object has been disposed'; function checkDisposed() { if (this.isDisposed) { throw new Error(objectDisposed); } } // Shim in iterator support var $iterator$ = (typeof Symbol === 'object' && Symbol.iterator) || '_es6shim_iterator_'; // Firefox ships a partial implementation using the name @@iterator. // https://bugzilla.mozilla.org/show_bug.cgi?id=907077#c14 // So use that name if we detect it. if (root.Set && typeof new root.Set()['@@iterator'] === 'function') { $iterator$ = '@@iterator'; } var doneEnumerator = { done: true, value: undefined }; /** `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 suportNodeClass, errorProto = Error.prototype, objectProto = Object.prototype, propertyIsEnumerable = objectProto.propertyIsEnumerable; try { suportNodeClass = !(toString.call(document) == objectClass && !({ 'toString': 0 } + '')); } catch(e) { suportNodeClass = true; } var shadowedProps = [ 'constructor', 'hasOwnProperty', 'isPrototypeOf', 'propertyIsEnumerable', 'toLocaleString', 'toString', 'valueOf' ]; 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)); function isObject(value) { // check if the value is the ECMAScript language type of Object // http://es5.github.io/#x8 // and avoid a V8 bug // https://code.google.com/p/v8/issues/detail?id=2291 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 = shadowedProps.length; if (object === (ctor && ctor.prototype)) { var className = object === stringProto ? stringClass : object === errorProto ? errorClass : toString.call(object), nonEnum = nonEnumProps[className]; } while (++index < length) { key = shadowedProps[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'; } function isArguments(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; }; } function isFunction(value) { return typeof value == 'function' || false; } // fallback for older versions of Chrome and Safari if (isFunction(/x/)) { isFunction = function(value) { return typeof value == 'function' && toString.call(value) == funcClass; }; } 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; 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 slice = Array.prototype.slice; function argsOrArray(args, idx) { return args.length === 1 && Array.isArray(args[idx]) ? args[idx] : slice.call(args); } var hasProp = {}.hasOwnProperty; /** @private */ var inherits = this.inherits = Rx.internals.inherits = function (child, parent) { function __() { this.constructor = child; } __.prototype = parent.prototype; child.prototype = new __(); }; /** @private */ var addProperties = Rx.internals.addProperties = function (obj) { var sources = slice.call(arguments, 1); for (var i = 0, len = sources.length; i < len; i++) { var source = sources[i]; 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)); }); }; // Collection polyfills function arrayInitialize(count, factory) { var a = new Array(count); for (var i = 0; i < count; i++) { a[i] = factory(); } return a; } // Utilities 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; }; } 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 = 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 Object.prototype.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; }; } // Collections var IndexedItem = function (id, value) { this.id = id; this.value = value; }; IndexedItem.prototype.compareTo = function (other) { var c = this.value.compareTo(other.value); if (c === 0) { c = this.id - other.id; } return c; }; // Priority Queue for Scheduling var PriorityQueue = Rx.internals.PriorityQueue = function (capacity) { this.items = new Array(capacity); this.length = 0; }; var priorityProto = PriorityQueue.prototype; priorityProto.isHigherPriority = function (left, right) { return this.items[left].compareTo(this.items[right]) < 0; }; priorityProto.percolate = function (index) { if (index >= this.length || index < 0) { return; } var parent = index - 1 >> 1; if (parent < 0 || parent === index) { return; } if (this.isHigherPriority(index, parent)) { var temp = this.items[index]; this.items[index] = this.items[parent]; this.items[parent] = temp; this.percolate(parent); } }; priorityProto.heapify = function (index) { if (index === undefined) { index = 0; } if (index >= this.length || index < 0) { return; } var left = 2 * index + 1, right = 2 * index + 2, first = index; if (left < this.length && this.isHigherPriority(left, first)) { first = left; } if (right < this.length && this.isHigherPriority(right, first)) { first = right; } if (first !== index) { var temp = this.items[index]; this.items[index] = this.items[first]; this.items[first] = temp; this.heapify(first); } }; priorityProto.peek = function () { return this.items[0].value; }; priorityProto.removeAt = function (index) { this.items[index] = this.items[--this.length]; delete this.items[this.length]; this.heapify(); }; priorityProto.dequeue = function () { var result = this.peek(); this.removeAt(0); return result; }; priorityProto.enqueue = function (item) { var index = this.length++; this.items[index] = new IndexedItem(PriorityQueue.count++, item); this.percolate(index); }; priorityProto.remove = function (item) { for (var i = 0; i < this.length; i++) { if (this.items[i].value === item) { this.removeAt(i); return true; } } return false; }; PriorityQueue.count = 0; /** * Represents a group of disposable resources that are disposed together. * @constructor */ var CompositeDisposable = Rx.CompositeDisposable = function () { this.disposables = argsOrArray(arguments, 0); this.isDisposed = false; this.length = this.disposables.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 currentDisposables = this.disposables.slice(0); this.disposables = []; this.length = 0; for (var i = 0, len = currentDisposables.length; i < len; i++) { currentDisposables[i].dispose(); } } }; /** * Removes and disposes all disposables from the CompositeDisposable, but does not dispose the CompositeDisposable. */ CompositeDisposablePrototype.clear = function () { var currentDisposables = this.disposables.slice(0); this.disposables = []; this.length = 0; for (var i = 0, len = currentDisposables.length; i < len; i++) { currentDisposables[i].dispose(); } }; /** * Determines whether the CompositeDisposable contains a specific disposable. * @param {Mixed} item Disposable to search for. * @returns {Boolean} true if the disposable was found; otherwise, false. */ CompositeDisposablePrototype.contains = function (item) { return this.disposables.indexOf(item) !== -1; }; /** * Converts the existing CompositeDisposable to an array of disposables * @returns {Array} An array of disposable objects. */ CompositeDisposablePrototype.toArray = function () { return this.disposables.slice(0); }; /** * Provides a set of static methods for creating Disposables. * * @constructor * @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 }; var BooleanDisposable = (function () { function BooleanDisposable (isSingle) { this.isSingle = isSingle; this.isDisposed = false; this.current = null; } var booleanDisposablePrototype = BooleanDisposable.prototype; /** * Gets the underlying disposable. * @return The underlying disposable. */ booleanDisposablePrototype.getDisposable = function () { return this.current; }; /** * Sets the underlying disposable. * @param {Disposable} value The new underlying disposable. */ booleanDisposablePrototype.setDisposable = function (value) { if (this.current && this.isSingle) { throw new Error('Disposable has already been assigned'); } var shouldDispose = this.isDisposed, old; if (!shouldDispose) { old = this.current; this.current = value; } if (old) { old.dispose(); } if (shouldDispose && value) { value.dispose(); } }; /** * Disposes the underlying disposable as well as all future replacements. */ booleanDisposablePrototype.dispose = function () { var old; if (!this.isDisposed) { this.isDisposed = true; old = this.current; this.current = null; } if (old) { old.dispose(); } }; return BooleanDisposable; }()); /** * Represents a disposable resource which only allows a single assignment of its underlying disposable resource. * If an underlying disposable resource has already been set, future attempts to set the underlying disposable resource will throw an Error. */ var SingleAssignmentDisposable = Rx.SingleAssignmentDisposable = (function (super_) { inherits(SingleAssignmentDisposable, super_); function SingleAssignmentDisposable() { super_.call(this, true); } return SingleAssignmentDisposable; }(BooleanDisposable)); /** * Represents a disposable resource whose underlying disposable resource can be replaced by another disposable resource, causing automatic disposal of the previous underlying disposable resource. */ var SerialDisposable = Rx.SerialDisposable = (function (super_) { inherits(SerialDisposable, super_); function SerialDisposable() { super_.call(this, false); } return SerialDisposable; }(BooleanDisposable)); /** * 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) { if (!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) { if (!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; } ScheduledDisposable.prototype.dispose = function () { var parent = this; this.scheduler.schedule(function () { if (!parent.isDisposed) { parent.isDisposed = true; parent.disposable.dispose(); } }); }; 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 () { /** * @constructor * @private */ function Scheduler(now, schedule, scheduleRelative, scheduleAbsolute) { this.now = now; this._schedule = schedule; this._scheduleRelative = scheduleRelative; this._scheduleAbsolute = scheduleAbsolute; } function invokeRecImmediate(scheduler, pair) { var state = pair.first, action = pair.second, group = new CompositeDisposable(), recursiveAction = function (state1) { action(state1, function (state2) { var isAdded = false, isDone = false, d = scheduler.scheduleWithState(state2, function (scheduler1, state3) { if (isAdded) { group.remove(d); } else { isDone = true; } recursiveAction(state3); return disposableEmpty; }); if (!isDone) { group.add(d); isAdded = true; } }); }; recursiveAction(state); return group; } function invokeRecDate(scheduler, pair, method) { var state = pair.first, action = pair.second, group = new CompositeDisposable(), recursiveAction = function (state1) { action(state1, function (state2, dueTime1) { var isAdded = false, isDone = false, d = scheduler[method].call(scheduler, state2, dueTime1, function (scheduler1, state3) { if (isAdded) { group.remove(d); } else { isDone = true; } recursiveAction(state3); return disposableEmpty; }); if (!isDone) { group.add(d); isAdded = true; } }); }; recursiveAction(state); return group; } function invokeAction(scheduler, action) { action(); return disposableEmpty; } var schedulerProto = Scheduler.prototype; /** * 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.catchException = schedulerProto['catch'] = function (handler) { return new CatchScheduler(this, handler); }; /** * 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). */ schedulerProto.schedulePeriodic = function (period, action) { return this.schedulePeriodicWithState(null, period, function () { 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). */ schedulerProto.schedulePeriodicWithState = function (state, period, action) { var s = state, id = setInterval(function () { s = action(s); }, period); return disposableCreate(function () { clearInterval(id); }); }; /** * 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); }; /** * 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, function (_action, self) { _action(function () { self(_action); }); }); }; /** * 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({ first: state, second: action }, function (s, p) { return invokeRecImmediate(s, p); }); }; /** * 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, function (_action, self) { _action(function (dt) { self(_action, dt); }); }); }; /** * 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({ first: state, second: action }, dueTime, function (s, p) { return invokeRecDate(s, p, 'scheduleWithRelativeAndState'); }); }; /** * 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, function (_action, self) { _action(function (dt) { self(_action, dt); }); }); }; /** * 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({ first: state, second: action }, dueTime, function (s, p) { return invokeRecDate(s, p, 'scheduleWithAbsoluteAndState'); }); }; /** 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) { if (timeSpan < 0) { timeSpan = 0; } return timeSpan; }; return Scheduler; }()); var normalizeTime = Scheduler.normalize; 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); } function scheduleRelative(state, dueTime, action) { var dt = normalizeTime(dt); while (dt - this.now() > 0) { } return action(this, state); } function scheduleAbsolute(state, dueTime, action) { return this.scheduleWithRelativeAndState(state, dueTime - this.now(), action); } return new Scheduler(defaultNow, scheduleNow, scheduleRelative, scheduleAbsolute); }()); /** * Gets a scheduler that schedules work as soon as possible on the current thread. */ var currentThreadScheduler = Scheduler.currentThread = (function () { var queue; function runTrampoline (q) { var item; while (q.length > 0) { item = q.dequeue(); if (!item.isCancelled()) { // Note, do not schedule blocking work! while (item.dueTime - Scheduler.now() > 0) { } if (!item.isCancelled()) { item.invoke(); } } } } function scheduleNow(state, action) { return this.scheduleWithRelativeAndState(state, 0, action); } function scheduleRelative(state, dueTime, action) { var dt = this.now() + Scheduler.normalize(dueTime), si = new ScheduledItem(this, state, action, dt), t; if (!queue) { queue = new PriorityQueue(4); queue.enqueue(si); try { runTrampoline(queue); } catch (e) { throw e; } finally { queue = null; } } else { queue.enqueue(si); } return si.disposable; } function scheduleAbsolute(state, dueTime, action) { return this.scheduleWithRelativeAndState(state, dueTime - this.now(), action); } var currentScheduler = new Scheduler(defaultNow, scheduleNow, scheduleRelative, scheduleAbsolute); currentScheduler.scheduleRequired = function () { return queue === null; }; currentScheduler.ensureTrampoline = function (action) { if (queue === null) { return this.schedule(action); } else { return action(); } }; return currentScheduler; }()); var scheduleMethod, clearMethod = noop; (function () { var reNative = RegExp('^' + String(toString) .replace(/[.*+?^${}()|[\]\\]/g, '\\$&') .replace(/toString| for [^\]]+/g, '.*?') + '$' ); var setImmediate = typeof (setImmediate = freeGlobal && moduleExports && freeGlobal.setImmediate) == 'function' && !reNative.test(setImmediate) && setImmediate, clearImmediate = typeof (clearImmediate = freeGlobal && moduleExports && freeGlobal.clearImmediate) == 'function' && !reNative.test(clearImmediate) && clearImmediate; 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, nextTick, setImmediate, postMessage, MessageChannel, script readystatechanged, setTimeout if (typeof process !== 'undefined' && {}.toString.call(process) === '[object process]') { scheduleMethod = process.nextTick; } else if (typeof setImmediate === 'function') { scheduleMethod = setImmediate; clearMethod = clearImmediate; } else if (postMessageSupported()) { var MSG_PREFIX = 'ms.rx.schedule' + Math.random(), tasks = {}, taskId = 0; 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) { var handleId = event.data.substring(MSG_PREFIX.length), action = tasks[handleId]; action(); delete tasks[handleId]; } } if (root.addEventListener) { root.addEventListener('message', onGlobalPostMessage, false); } else { root.attachEvent('onmessage', onGlobalPostMessage, false); } scheduleMethod = function (action) { var currentId = taskId++; tasks[currentId] = action; root.postMessage(MSG_PREFIX + currentId, '*'); }; } else if (!!root.MessageChannel) { var channel = new root.MessageChannel(), channelTasks = {}, channelTaskId = 0; channel.port1.onmessage = function (event) { var id = event.data, action = channelTasks[id]; action(); delete channelTasks[id]; }; scheduleMethod = function (action) { var id = channelTaskId++; channelTasks[id] = action; channel.port2.postMessage(id); }; } else if ('document' in root && 'onreadystatechange' in root.document.createElement('script')) { scheduleMethod = function (action) { var scriptElement = root.document.createElement('script'); scriptElement.onreadystatechange = function () { action(); scriptElement.onreadystatechange = null; scriptElement.parentNode.removeChild(scriptElement); scriptElement = null; }; root.document.documentElement.appendChild(scriptElement); }; } else { scheduleMethod = function (action) { return setTimeout(action, 0); }; clearMethod = clearTimeout; } }()); /** * Gets a scheduler that schedules work via a timed callback based upon platform. */ var timeoutScheduler = Scheduler.timeout = (function () { function scheduleNow(state, action) { var scheduler = this, disposable = new SingleAssignmentDisposable(); var id = scheduleMethod(function () { if (!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); if (dt === 0) { return scheduler.scheduleWithState(state, action); } var disposable = new SingleAssignmentDisposable(); var id = setTimeout(function () { if (!disposable.isDisposed) { disposable.setDisposable(action(scheduler, state)); } }, dt); return new CompositeDisposable(disposable, disposableCreate(function () { clearTimeout(id); })); } function scheduleAbsolute(state, dueTime, action) { return this.scheduleWithRelativeAndState(state, dueTime - this.now(), action); } return new Scheduler(defaultNow, scheduleNow, scheduleRelative, scheduleAbsolute); })(); /** @private */ var CatchScheduler = (function (_super) { function localNow() { return this._scheduler.now(); } 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); /** @private */ function CatchScheduler(scheduler, handler) { this._scheduler = scheduler; this._handler = handler; this._recursiveOriginal = null; this._recursiveWrapper = null; _super.call(this, localNow, scheduleNow, scheduleRelative, scheduleAbsolute); } /** @private */ CatchScheduler.prototype._clone = function (scheduler) { return new CatchScheduler(scheduler, this._handler); }; /** @private */ 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; } }; }; /** @private */ 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; }; /** @private */ 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, hasValue) { this.hasValue = hasValue == null ? false : hasValue; this.kind = kind; } var NotificationPrototype = Notification.prototype; /** * 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. */ NotificationPrototype.accept = function (observerOrOnNext, onError, onCompleted) { if (arguments.length === 1 && typeof observerOrOnNext === 'object') { return this._acceptObservable(observerOrOnNext); } return this._accept(observerOrOnNext, onError, onCompleted); }; /** * Returns an observable sequence with a single notification. * * @memberOf Notification * @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. */ NotificationPrototype.toObservable = function (scheduler) { var notification = this; scheduler || (scheduler = immediateScheduler); return new AnonymousObservable(function (observer) { return scheduler.schedule(function () { notification._acceptObservable(observer); if (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) { var notification = new Notification('N', true); notification.value = value; notification._accept = _accept; notification._acceptObservable = _acceptObservable; notification.toString = toString; return notification; }; }()); /** * 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 (exception) { var notification = new Notification('E'); notification.exception = exception; notification._accept = _accept; notification._acceptObservable = _acceptObservable; notification.toString = toString; return notification; }; }()); /** * 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 () { var notification = new Notification('C'); notification._accept = _accept; notification._acceptObservable = _acceptObservable; notification.toString = toString; return notification; }; }()); var Enumerator = Rx.internals.Enumerator = function (next) { this._next = next; }; Enumerator.prototype.next = function () { return this._next(); }; Enumerator.prototype[$iterator$] = function () { return this; } var Enumerable = Rx.internals.Enumerable = function (iterator) { this._iterator = iterator; }; Enumerable.prototype[$iterator$] = function () { return this._iterator(); }; Enumerable.prototype.concat = function () { var sources = this; return new AnonymousObservable(function (observer) { var e; try { e = sources[$iterator$](); } catch(err) { observer.onError(); return; } var isDisposed, subscription = new SerialDisposable(); var cancelable = immediateScheduler.scheduleRecursive(function (self) { var currentItem; if (isDisposed) { return; } try { currentItem = e.next(); } catch (ex) { observer.onError(ex); return; } if (currentItem.done) { observer.onCompleted(); return; } // Check if promise var currentValue = currentItem.value; isPromise(currentValue) && (currentValue = observableFromPromise(currentValue)); var d = new SingleAssignmentDisposable(); subscription.setDisposable(d); d.setDisposable(currentValue.subscribe( observer.onNext.bind(observer), observer.onError.bind(observer), function () { self(); }) ); }); return new CompositeDisposable(subscription, cancelable, disposableCreate(function () { isDisposed = true; })); }); }; Enumerable.prototype.catchException = function () { var sources = this; return new AnonymousObservable(function (observer) { var e; try { e = sources[$iterator$](); } catch(err) { observer.onError(); return; } var isDisposed, lastException, subscription = new SerialDisposable(); var cancelable = immediateScheduler.scheduleRecursive(function (self) { if (isDisposed) { return; } var currentItem; try { currentItem = e.next(); } catch (ex) { observer.onError(ex); return; } if (currentItem.done) { if (lastException) { observer.onError(lastException); } else { observer.onCompleted(); } return; } // Check if promise var currentValue = currentItem.value; isPromise(currentValue) && (currentValue = observableFromPromise(currentValue)); var d = new SingleAssignmentDisposable(); subscription.setDisposable(d); d.setDisposable(currentValue.subscribe( observer.onNext.bind(observer), function (exn) { lastException = exn; self(); }, observer.onCompleted.bind(observer))); }); return new CompositeDisposable(subscription, cancelable, disposableCreate(function () { isDisposed = true; })); }); }; var enumerableRepeat = Enumerable.repeat = function (value, repeatCount) { if (repeatCount == null) { repeatCount = -1; } return new Enumerable(function () { var left = repeatCount; return new Enumerator(function () { if (left === 0) { return doneEnumerator; } if (left > 0) { left--; } return { done: false, value: value }; }); }); }; var enumerableFor = Enumerable.forEach = function (source, selector, thisArg) { selector || (selector = identity); return new Enumerable(function () { var index = -1; return new Enumerator( function () { return ++index < source.length ? { done: false, value: selector.call(thisArg, source[index], index, source) } : doneEnumerator; }); }); }; /** * Supports push-style iteration over an observable sequence. */ var Observer = Rx.Observer = function () { }; /** * Creates a notification callback from an observer. * * @param observer Observer object. * @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 () { return new AnonymousObserver(this.onNext.bind(this), this.onError.bind(this), this.onCompleted.bind(this)); }; /** * 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. * * @static * @memberOf Observer * @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) { return new AnonymousObserver(function (x) { return handler(notificationCreateOnNext(x)); }, function (exception) { return handler(notificationCreateOnError(exception)); }, function () { return handler(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.notifyOn = function (scheduler) { return new ObserveOnObserver(scheduler, this); }; /** * 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. * * @constructor */ function AbstractObserver() { this.isStopped = false; _super.call(this); } /** * Notifies the observer of a new element in the sequence. * * @memberOf AbstractObserver * @param {Any} value Next element in the sequence. */ AbstractObserver.prototype.onNext = function (value) { if (!this.isStopped) { this.next(value); } }; /** * Notifies the observer that an exception has occurred. * * @memberOf AbstractObserver * @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 (exception) { this._onError(exception); }; /** * 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(); try { this._observer.onNext(value); } catch (e) { throw e; } finally { this._state = 0; } }; CheckedObserverPrototype.onError = function (err) { this.checkAccess(); try { this._observer.onError(err); } catch (e) { throw e; } finally { this._state = 2; } }; CheckedObserverPrototype.onCompleted = function () { this.checkAccess(); try { this._observer.onCompleted(); } catch (e) { throw e; } finally { this._state = 2; } }; 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 (exception) { var self = this; this.queue.push(function () { self.observer.onError(exception); }); }; ScheduledObserver.prototype.completed = function () { var self = this; this.queue.push(function () { self.observer.onCompleted(); }); }; ScheduledObserver.prototype.ensureActive = function () { var isOwner = false, parent = this; if (!this.hasFaulted && this.queue.length > 0) { isOwner = !this.isAcquired; this.isAcquired = true; } if (isOwner) { this.disposable.setDisposable(this.scheduler.scheduleRecursive(function (self) { var work; if (parent.queue.length > 0) { work = parent.queue.shift(); } else { parent.isAcquired = false; return; } try { work(); } catch (ex) { parent.queue = []; parent.hasFaulted = true; throw ex; } self(); })); } }; ScheduledObserver.prototype.dispose = function () { _super.prototype.dispose.call(this); this.disposable.dispose(); }; return ScheduledObserver; }(AbstractObserver)); /** @private */ var ObserveOnObserver = (function (_super) { inherits(ObserveOnObserver, _super); /** @private */ function ObserveOnObserver() { _super.apply(this, arguments); } /** @private */ ObserveOnObserver.prototype.next = function (value) { _super.prototype.next.call(this, value); this.ensureActive(); }; /** @private */ ObserveOnObserver.prototype.error = function (e) { _super.prototype.error.call(this, e); this.ensureActive(); }; /** @private */ ObserveOnObserver.prototype.completed = function () { _super.prototype.completed.call(this); this.ensureActive(); }; return ObserveOnObserver; })(ScheduledObserver); var observableProto; /** * Represents a push-style collection. */ var Observable = Rx.Observable = (function () { function Observable(subscribe) { this._subscribe = subscribe; } observableProto = Observable.prototype; /** * Subscribes an observer to the observable sequence. * * @example * 1 - source.subscribe(); * 2 - source.subscribe(observer); * 3 - source.subscribe(function (x) { console.log(x); }); * 4 - source.subscribe(function (x) { console.log(x); }, function (err) { console.log(err); }); * 5 - source.subscribe(function (x) { console.log(x); }, function (err) { console.log(err); }, function () { console.log('done'); }); * @param {Mixed} [observerOrOnNext] 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} The source sequence whose subscriptions and unsubscriptions happen on the specified scheduler. */ observableProto.subscribe = observableProto.forEach = function (observerOrOnNext, onError, onCompleted) { var subscriber = typeof observerOrOnNext === 'object' ? observerOrOnNext : observerCreate(observerOrOnNext, onError, onCompleted); return this._subscribe(subscriber); }; return Observable; })(); /** * 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)); }); }; /** * 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; }); }; /** * 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 AnonymousObservable(function (observer) { promise.then( function (value) { observer.onNext(value); observer.onCompleted(); }, function (reason) { observer.onError(reason); }); return function () { if (promise && promise.abort) { promise.abort(); } } }); }; /* * 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 Error('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; }, function (err) { reject(err); }, function () { if (hasValue) { resolve(value); } }); }); }; /** * Creates a list from an observable sequence. * @returns An observable sequence containing a single element with a list containing all the elements of the source sequence. */ observableProto.toArray = function () { var self = this; return new AnonymousObservable(function(observer) { var arr = []; return self.subscribe( arr.push.bind(arr), observer.onError.bind(observer), function () { observer.onNext(arr); observer.onCompleted(); }); }); }; /** * 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 = Observable.createWithDisposable = function (subscribe) { return new AnonymousObservable(subscribe); }; /** * 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); }); }; /** * 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) { scheduler || (scheduler = immediateScheduler); return new AnonymousObservable(function (observer) { return scheduler.schedule(function () { observer.onCompleted(); }); }); }; /** * Converts an array to an observable sequence, using an optional scheduler to enumerate the array. * * @example * var res = Rx.Observable.fromArray([1,2,3]); * var res = Rx.Observable.fromArray([1,2,3], Rx.Scheduler.timeout); * @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) { scheduler || (scheduler = currentThreadScheduler); return new AnonymousObservable(function (observer) { var count = 0; return scheduler.scheduleRecursive(function (self) { if (count < array.length) { observer.onNext(array[count++]); self(); } else { observer.onCompleted(); } }); }); }; /** * Converts an iterable into an Observable sequence * * @example * var res = Rx.Observable.fromIterable(new Map()); * var res = Rx.Observable.fromIterable(new Set(), Rx.Scheduler.timeout); * @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 generator sequence. */ Observable.fromIterable = function (iterable, scheduler) { scheduler || (scheduler = currentThreadScheduler); return new AnonymousObservable(function (observer) { var iterator; try { iterator = iterable[$iterator$](); } catch (e) { observer.onError(e); return; } return scheduler.scheduleRecursive(function (self) { var next; try { next = iterator.next(); } catch (err) { observer.onError(err); return; } if (next.done) { observer.onCompleted(); } else { observer.onNext(next.value); self(); } }); }); }; /** * 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) { scheduler || (scheduler = currentThreadScheduler); return new AnonymousObservable(function (observer) { var first = true, state = initialState; return scheduler.scheduleRecursive(function (self) { var hasResult, result; try { if (first) { first = false; } else { state = iterate(state); } hasResult = condition(state); if (hasResult) { result = resultSelector(state); } } catch (exception) { observer.onError(exception); return; } if (hasResult) { observer.onNext(result); self(); } else { observer.onCompleted(); } }); }); }; /** * 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 new AnonymousObservable(function () { return disposableEmpty; }); }; /** * Generates an observable sequence of integral numbers within a specified range, using the specified scheduler to send out observer messages. * * @example * var res = Rx.Observable.range(0, 10); * var res = Rx.Observable.range(0, 10, Rx.Scheduler.timeout); * @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) { scheduler || (scheduler = currentThreadScheduler); return new AnonymousObservable(function (observer) { return scheduler.scheduleRecursiveWithState(0, function (i, self) { if (i < count) { observer.onNext(start + i); self(i + 1); } else { observer.onCompleted(); } }); }); }; /** * Generates an observable sequence that repeats the given element the specified number of times, using the specified scheduler to send out observer messages. * * @example * var res = Rx.Observable.repeat(42); * var res = Rx.Observable.repeat(42, 4); * 3 - res = Rx.Observable.repeat(42, 4, Rx.Scheduler.timeout); * 4 - res = Rx.Observable.repeat(42, null, Rx.Scheduler.timeout); * @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) { scheduler || (scheduler = currentThreadScheduler); if (repeatCount == null) { repeatCount = -1; } return observableReturn(value, scheduler).repeat(repeatCount); }; /** * Returns an observable sequence that contains a single element, using the specified scheduler to send out observer messages. * There is an alias called 'returnValue' for browsers <IE9. * * @example * var res = Rx.Observable.return(42); * var res = Rx.Observable.return(42, Rx.Scheduler.timeout); * @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.returnValue = function (value, scheduler) { scheduler || (scheduler = immediateScheduler); return new AnonymousObservable(function (observer) { return scheduler.schedule(function () { observer.onNext(value); observer.onCompleted(); }); }); }; /** * 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 'throwException' for browsers <IE9. * * @example * var res = Rx.Observable.throwException(new Error('Error')); * var res = Rx.Observable.throwException(new Error('Error'), Rx.Scheduler.timeout); * @param {Mixed} exception 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'] = Observable.throwException = function (exception, scheduler) { scheduler || (scheduler = immediateScheduler); return new AnonymousObservable(function (observer) { return scheduler.schedule(function () { observer.onError(exception); }); }); }; /** * Constructs an observable sequence that depends on a resource object, whose lifetime is tied to the resulting observable sequence's lifetime. * * @example * var res = Rx.Observable.using(function () { return new AsyncSubject(); }, function (s) { return s; }); * @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 (observer) { var disposable = disposableEmpty, resource, source; try { resource = resourceFactory(); if (resource) { disposable = resource; } source = observableFactory(resource); } catch (exception) { return new CompositeDisposable(observableThrow(exception).subscribe(observer), disposable); } return new CompositeDisposable(source.subscribe(observer), 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(); } } leftSubscription.setDisposable(leftSource.subscribe(function (left) { choiceL(); if (choice === leftChoice) { observer.onNext(left); } }, function (err) { choiceL(); if (choice === leftChoice) { observer.onError(err); } }, function () { choiceL(); if (choice === leftChoice) { observer.onCompleted(); } })); rightSubscription.setDisposable(rightSource.subscribe(function (right) { choiceR(); if (choice === rightChoice) { observer.onNext(right); } }, function (err) { choiceR(); if (choice === rightChoice) { observer.onError(err); } }, function () { choiceR(); if (choice === rightChoice) { observer.onCompleted(); } })); return new CompositeDisposable(leftSubscription, rightSubscription); }); }; /** * Propagates the observable sequence or Promise that reacts first. * * @example * var = Rx.Observable.amb(xs, ys, zs); * @returns {Observable} An observable sequence that surfaces any of the given sequences, whichever reacted first. */ Observable.amb = function () { var acc = observableNever(), items = argsOrArray(arguments, 0); function func(previous, current) { return previous.amb(current); } for (var i = 0, len = items.length; i < len; i++) { acc = func(acc, items[i]); } return acc; }; function observableCatchHandler(source, handler) { return new AnonymousObservable(function (observer) { var d1 = new SingleAssignmentDisposable(), subscription = new SerialDisposable(); subscription.setDisposable(d1); d1.setDisposable(source.subscribe(observer.onNext.bind(observer), function (exception) { var d, result; try { result = handler(exception); } catch (ex) { observer.onError(ex); return; } isPromise(result) && (result = observableFromPromise(result)); d = new SingleAssignmentDisposable(); subscription.setDisposable(d); d.setDisposable(result.subscribe(observer)); }, observer.onCompleted.bind(observer))); return subscription; }); } /** * Continues an observable sequence that is terminated by an exception with the next observable sequence. * @example * 1 - xs.catchException(ys) * 2 - xs.catchException(function (ex) { return ys(ex); }) * @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'] = observableProto.catchException = function (handlerOrSecond) { return typeof handlerOrSecond === 'function' ? observableCatchHandler(this, handlerOrSecond) : observableCatch([this, handlerOrSecond]); }; /** * Continues an observable sequence that is terminated by an exception with the next observable sequence. * * @example * 1 - res = Rx.Observable.catchException(xs, ys, zs); * 2 - res = Rx.Observable.catchException([xs, ys, zs]); * @returns {Observable} An observable sequence containing elements from consecutive source sequences until a source sequence terminates successfully. */ var observableCatch = Observable.catchException = Observable['catch'] = function () { var items = argsOrArray(arguments, 0); return enumerableFor(items).catchException(); }; /** * 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 args = slice.call(arguments); if (Array.isArray(args[0])) { args[0].unshift(this); } else { args.unshift(this); } return combineLatest.apply(this, 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 args = slice.call(arguments), resultSelector = args.pop(); if (Array.isArray(args[0])) { args = args[0]; } return new AnonymousObservable(function (observer) { var falseFactory = function () { return false; }, n = args.length, hasValue = arrayInitialize(n, falseFactory), hasValueAll = false, isDone = arrayInitialize(n, falseFactory), values = new Array(n); function next(i) { var res; hasValue[i] = true; if (hasValueAll || (hasValueAll = hasValue.every(identity))) { try { res = resultSelector.apply(null, values); } catch (ex) { observer.onError(ex); return; } observer.onNext(res); } else if (isDone.filter(function (x, j) { return j !== i; }).every(identity)) { observer.onCompleted(); } } function done (i) { isDone[i] = true; if (isDone.every(identity)) { observer.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); }, observer.onError.bind(observer), function () { done(i); })); subscriptions[i] = sad; }(idx)); } return new CompositeDisposable(subscriptions); }); }; /** * Concatenates all the observable sequences. This takes in either an array or variable arguments to concatenate. * * @example * 1 - concatenated = xs.concat(ys, zs); * 2 - concatenated = xs.concat([ys, zs]); * @returns {Observable} An observable sequence that contains the elements of each given sequence, in sequential order. */ observableProto.concat = function () { var items = slice.call(arguments, 0); items.unshift(this); return observableConcat.apply(this, items); }; /** * Concatenates all the observable sequences. * * @example * 1 - res = Rx.Observable.concat(xs, ys, zs); * 2 - res = Rx.Observable.concat([xs, ys, zs]); * @returns {Observable} An observable sequence that contains the elements of each given sequence, in sequential order. */ var observableConcat = Observable.concat = function () { var sources = argsOrArray(arguments, 0); return enumerableFor(sources).concat(); }; /** * 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.concatObservable = observableProto.concatAll =function () { return this.merge(1); }; /** * 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) { if (typeof maxConcurrentOrOther !== 'number') { return observableMerge(this, maxConcurrentOrOther); } var sources = this; return new AnonymousObservable(function (observer) { var activeCount = 0, group = new CompositeDisposable(), isStopped = false, q = [], subscribe = function (xs) { var subscription = new SingleAssignmentDisposable(); group.add(subscription); // Check for promises support if (isPromise(xs)) { xs = observableFromPromise(xs); } subscription.setDisposable(xs.subscribe(observer.onNext.bind(observer), observer.onError.bind(observer), function () { var s; group.remove(subscription); if (q.length > 0) { s = q.shift(); subscribe(s); } else { activeCount--; if (isStopped && activeCount === 0) { observer.onCompleted(); } } })); }; group.add(sources.subscribe(function (innerSource) { if (activeCount < maxConcurrentOrOther) { activeCount++; subscribe(innerSource); } else { q.push(innerSource); } }, observer.onError.bind(observer), function () { isStopped = true; if (activeCount === 0) { observer.onCompleted(); } })); return group; }); }; /** * Merges all the observable sequences into a single observable sequence. * The scheduler is optional and if not specified, the immediate scheduler is used. * * @example * 1 - merged = Rx.Observable.merge(xs, ys, zs); * 2 - merged = Rx.Observable.merge([xs, ys, zs]); * 3 - merged = Rx.Observable.merge(scheduler, xs, ys, zs); * 4 - merged = Rx.Observable.merge(scheduler, [xs, ys, zs]); * @returns {Observable} The observable sequence that merges the elements of the observable sequences. */ var observableMerge = Observable.merge = function () { var scheduler, sources; if (!arguments[0]) { scheduler = immediateScheduler; sources = slice.call(arguments, 1); } else if (arguments[0].now) { scheduler = arguments[0]; sources = slice.call(arguments, 1); } else { scheduler = immediateScheduler; sources = slice.call(arguments, 0); } if (Array.isArray(sources[0])) { sources = sources[0]; } return observableFromArray(sources, scheduler).mergeObservable(); }; /** * 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.mergeObservable = observableProto.mergeAll =function () { var sources = this; return new AnonymousObservable(function (observer) { var group = new CompositeDisposable(), isStopped = false, m = new SingleAssignmentDisposable(); group.add(m); m.setDisposable(sources.subscribe(function (innerSource) { var innerSubscription = new SingleAssignmentDisposable(); group.add(innerSubscription); // Check if Promise or Observable if (isPromise(innerSource)) { innerSource = observableFromPromise(innerSource); } innerSubscription.setDisposable(innerSource.subscribe(function (x) { observer.onNext(x); }, observer.onError.bind(observer), function () { group.remove(innerSubscription); if (isStopped && group.length === 1) { observer.onCompleted(); } })); }, observer.onError.bind(observer), function () { isStopped = true; if (group.length === 1) { observer.onCompleted(); } })); 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 = argsOrArray(arguments, 0); 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), function () { self(); }, function () { 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 (observer) { var isOpen = false; var disposables = new CompositeDisposable(source.subscribe(function (left) { isOpen && observer.onNext(left); }, observer.onError.bind(observer), function () { isOpen && observer.onCompleted(); })); isPromise(other) && (other = observableFromPromise(other)); var rightSubscription = new SingleAssignmentDisposable(); disposables.add(rightSubscription); rightSubscription.setDisposable(other.subscribe(function () { isOpen = true; rightSubscription.dispose(); }, observer.onError.bind(observer), function () { rightSubscription.dispose(); })); return disposables; }); }; /** * 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 () { var sources = this; return new AnonymousObservable(function (observer) { var hasLatest = false, innerSubscription = new SerialDisposable(), isStopped = false, latest = 0, subscription = sources.subscribe(function (innerSource) { var d = new SingleAssignmentDisposable(), id = ++latest; hasLatest = true; innerSubscription.setDisposable(d); // Check if Promise or Observable if (isPromise(innerSource)) { innerSource = observableFromPromise(innerSource); } d.setDisposable(innerSource.subscribe(function (x) { if (latest === id) { observer.onNext(x); } }, function (e) { if (latest === id) { observer.onError(e); } }, function () { if (latest === id) { hasLatest = false; if (isStopped) { observer.onCompleted(); } } })); }, observer.onError.bind(observer), function () { isStopped = true; if (!hasLatest) { observer.onCompleted(); } }); return new CompositeDisposable(subscription, innerSubscription); }); }; /** * 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) { var source = this; return new AnonymousObservable(function (observer) { isPromise(other) && (other = observableFromPromise(other)); return new CompositeDisposable( source.subscribe(observer), other.subscribe(observer.onCompleted.bind(observer), observer.onError.bind(observer), noop) ); }); }; function zipArray(second, resultSelector) { var first = this; return new AnonymousObservable(function (observer) { var index = 0, len = second.length; return first.subscribe(function (left) { if (index < len) { var right = second[index++], result; try { result = resultSelector(left, right); } catch (e) { observer.onError(e); return; } observer.onNext(result); } else { observer.onCompleted(); } }, observer.onError.bind(observer), observer.onCompleted.bind(observer)); }); } /** * 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 sources. * * @example * 1 - res = obs1.zip(obs2, fn); * 1 - res = x1.zip([1,2,3], fn); * @returns {Observable} An observable sequence containing the result of combining elements of the sources using the specified result selector function. */ observableProto.zip = function () { if (Array.isArray(arguments[0])) { return zipArray.apply(this, arguments); } var parent = this, sources = slice.call(arguments), resultSelector = sources.pop(); sources.unshift(parent); return new AnonymousObservable(function (observer) { var n = sources.length, queues = arrayInitialize(n, function () { return []; }), isDone = arrayInitialize(n, function () { return false; }); function next(i) { var res, queuedValues; if (queues.every(function (x) { return x.length > 0; })) { try { queuedValues = queues.map(function (x) { return x.shift(); }); res = resultSelector.apply(parent, queuedValues); } catch (ex) { observer.onError(ex); return; } observer.onNext(res); } else if (isDone.filter(function (x, j) { return j !== i; }).every(identity)) { observer.onCompleted(); } }; function done(i) { isDone[i] = true; if (isDone.every(function (x) { return x; })) { observer.onCompleted(); } } var subscriptions = new Array(n); for (var idx = 0; idx < n; idx++) { (function (i) { var source = sources[i], sad = new SingleAssignmentDisposable(); isPromise(source) && (source = observableFromPromise(source)); sad.setDisposable(source.subscribe(function (x) { queues[i].push(x); next(i); }, observer.onError.bind(observer), function () { done(i); })); subscriptions[i] = sad; })(idx); } return new CompositeDisposable(subscriptions); }); }; /** * 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 args = slice.call(arguments, 0), first = args.shift(); return first.zip.apply(first, args); }; /** * Merges the specified observable sequences into one observable sequence by emitting a list with the elements of the observable sequences at corresponding indexes. * @param arguments Observable sources. * @returns {Observable} An observable sequence containing lists of elements at corresponding indexes. */ Observable.zipArray = function () { var sources = argsOrArray(arguments, 0); return new AnonymousObservable(function (observer) { var n = sources.length, queues = arrayInitialize(n, function () { return []; }), isDone = arrayInitialize(n, function () { return false; }); function next(i) { if (queues.every(function (x) { return x.length > 0; })) { var res = queues.map(function (x) { return x.shift(); }); observer.onNext(res); } else if (isDone.filter(function (x, j) { return j !== i; }).every(identity)) { observer.onCompleted(); return; } }; function done(i) { isDone[i] = true; if (isDone.every(identity)) { observer.onCompleted(); return; } } var subscriptions = new Array(n); for (var idx = 0; idx < n; idx++) { (function (i) { subscriptions[i] = new SingleAssignmentDisposable(); subscriptions[i].setDisposable(sources[i].subscribe(function (x) { queues[i].push(x); next(i); }, observer.onError.bind(observer), function () { done(i); })); })(idx); } var compositeDisposable = new CompositeDisposable(subscriptions); compositeDisposable.add(disposableCreate(function () { for (var qIdx = 0, qLen = queues.length; qIdx < qLen; qIdx++) { queues[qIdx] = []; } })); return compositeDisposable; }); }; /** * Hides the identity of an observable sequence. * @returns {Observable} An observable sequence that hides the identity of the source sequence. */ observableProto.asObservable = function () { var source = this; return new AnonymousObservable(function (observer) { return source.subscribe(observer); }); }; /** * Projects each element of an observable sequence into zero or more buffers which are produced based on element count information. * * @example * var res = xs.bufferWithCount(10); * var res = xs.bufferWithCount(10, 1); * @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) { if (typeof skip !== 'number') { skip = count; } return this.windowWithCount(count, skip).selectMany(function (x) { return x.toArray(); }).where(function (x) { return x.length > 0; }); }; /** * 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 (observer) { return source.subscribe(function (x) { return x.accept(observer); }, observer.onError.bind(observer), observer.onCompleted.bind(observer)); }); }; /** * Returns an observable sequence that contains only distinct contiguous elements according to the keySelector and the comparer. * * var obs = observable.distinctUntilChanged(); * var obs = observable.distinctUntilChanged(function (x) { return x.id; }); * var obs = observable.distinctUntilChanged(function (x) { return x.id; }, function (x, y) { return x === y; }); * * @param {Function} [keySelector] 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 (keySelector, comparer) { var source = this; keySelector || (keySelector = identity); comparer || (comparer = defaultComparer); return new AnonymousObservable(function (observer) { var hasCurrentKey = false, currentKey; return source.subscribe(function (value) { var comparerEquals = false, key; try { key = keySelector(value); } catch (exception) { observer.onError(exception); return; } if (hasCurrentKey) { try { comparerEquals = comparer(currentKey, key); } catch (exception) { observer.onError(exception); return; } } if (!hasCurrentKey || !comparerEquals) { hasCurrentKey = true; currentKey = key; observer.onNext(value); } }, observer.onError.bind(observer), observer.onCompleted.bind(observer)); }); }; /** * 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. * * @example * var res = observable.doAction(observer); * var res = observable.doAction(onNext); * var res = observable.doAction(onNext, onError); * var res = observable.doAction(onNext, onError, onCompleted); * @param {Mixed} observerOrOnNext Action to invoke for each element in the observable sequence or an observer. * @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.doAction = function (observerOrOnNext, onError, onCompleted) { var source = this, onNextFunc; if (typeof observerOrOnNext === 'function') { onNextFunc = observerOrOnNext; } else { onNextFunc = observerOrOnNext.onNext.bind(observerOrOnNext); onError = observerOrOnNext.onError.bind(observerOrOnNext); onCompleted = observerOrOnNext.onCompleted.bind(observerOrOnNext); } return new AnonymousObservable(function (observer) { return source.subscribe(function (x) { try { onNextFunc(x); } catch (e) { observer.onError(e); } observer.onNext(x); }, function (exception) { if (!onError) { observer.onError(exception); } else { try { onError(exception); } catch (e) { observer.onError(e); } observer.onError(exception); } }, function () { if (!onCompleted) { observer.onCompleted(); } else { try { onCompleted(); } catch (e) { observer.onError(e); } observer.onCompleted(); } }); }); }; /** * Invokes a specified action after the source observable sequence terminates gracefully or exceptionally. * * @example * var res = observable.finallyAction(function () { console.log('sequence ended'; }); * @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'] = observableProto.finallyAction = function (action) { var source = this; return new AnonymousObservable(function (observer) { var subscription; try { subscription = source.subscribe(observer); } catch (e) { action(); throw e; } return disposableCreate(function () { try { subscription.dispose(); } catch (e) { throw e; } finally { action(); } }); }); }; /** * 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 () { var source = this; return new AnonymousObservable(function (observer) { return source.subscribe(noop, observer.onError.bind(observer), observer.onCompleted.bind(observer)); }); }; /** * 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(); }); }); }; /** * Repeats the observable sequence a specified number of times. If the repeat count is not specified, the sequence repeats indefinitely. * * @example * var res = repeated = source.repeat(); * var res = repeated = source.repeat(42); * @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. * * @example * var res = retried = retry.repeat(); * var res = retried = retry.repeat(42); * @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).catchException(); }; /** * 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. * @example * var res = source.scan(function (acc, x) { return acc + x; }); * var res = source.scan(0, function (acc, x) { return acc + x; }); * @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, source = this; if (arguments.length === 2) { hasSeed = true; seed = arguments[0]; accumulator = arguments[1]; } else { accumulator = arguments[0]; } return new AnonymousObservable(function (observer) { var hasAccumulation, accumulation, hasValue; return source.subscribe ( function (x) { try { if (!hasValue) { hasValue = true; } if (hasAccumulation) { accumulation = accumulator(accumulation, x); } else { accumulation = hasSeed ? accumulator(seed, x) : x; hasAccumulation = true; } } catch (e) { observer.onError(e); return; } observer.onNext(accumulation); }, observer.onError.bind(observer), function () { if (!hasValue && hasSeed) { observer.onNext(seed); } observer.onCompleted(); } ); }); }; /** * 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) { var source = this; return new AnonymousObservable(function (observer) { var q = []; return source.subscribe(function (x) { q.push(x); if (q.length > count) { observer.onNext(q.shift()); } }, observer.onError.bind(observer), observer.onCompleted.bind(observer)); }); }; /** * Prepends a sequence of values to an observable sequence with an optional scheduler and an argument list of values to prepend. * * var res = source.startWith(1, 2, 3); * var res = source.startWith(Rx.Scheduler.timeout, 1, 2, 3); * * @memberOf Observable# * @returns {Observable} The source sequence prepended with the specified values. */ observableProto.startWith = function () { var values, scheduler, start = 0; if (!!arguments.length && 'now' in Object(arguments[0])) { scheduler = arguments[0]; start = 1; } else { scheduler = immediateScheduler; } values = slice.call(arguments, start); return enumerableFor([observableFromArray(values, scheduler), this]).concat(); }; /** * Returns a specified number of contiguous elements from the end of an observable sequence, using an optional scheduler to drain the queue. * * @example * var res = source.takeLast(5); * var res = source.takeLast(5, Rx.Scheduler.timeout); * * @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. * @param {Scheduler} [scheduler] Scheduler used to drain the queue upon completion 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, scheduler) { return this.takeLastBuffer(count).selectMany(function (xs) { return observableFromArray(xs, scheduler); }); }; /** * 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 (observer) { var q = []; return source.subscribe(function (x) { q.push(x); if (q.length > count) { q.shift(); } }, observer.onError.bind(observer), function () { observer.onNext(q); observer.onCompleted(); }); }); }; /** * 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; if (count <= 0) { throw new Error(argumentOutOfRange); } if (arguments.length === 1) { skip = count; } if (skip <= 0) { throw new Error(argumentOutOfRange); } return new AnonymousObservable(function (observer) { var m = new SingleAssignmentDisposable(), refCountDisposable = new RefCountDisposable(m), n = 0, q = [], createWindow = function () { var s = new Subject(); q.push(s); observer.onNext(addRef(s, refCountDisposable)); }; createWindow(); m.setDisposable(source.subscribe(function (x) { var s; for (var i = 0, len = q.length; i < len; i++) { q[i].onNext(x); } var c = n - count + 1; if (c >= 0 && c % skip === 0) { s = q.shift(); s.onCompleted(); } n++; if (n % skip === 0) { createWindow(); } }, function (exception) { while (q.length > 0) { q.shift().onError(exception); } observer.onError(exception); }, function () { while (q.length > 0) { q.shift().onCompleted(); } observer.onCompleted(); })); return refCountDisposable; }); }; function concatMap(selector) { return this.map(function (x, i) { var result = selector(x, i); return isPromise(result) ? observableFromPromise(result) : result; }).concatAll(); } function concatMapObserver(onNext, onError, onCompleted) { var source = this; return new AnonymousObservable(function (observer) { var index = 0; return source.subscribe( function (x) { observer.onNext(onNext(x, index++)); }, function (err) { observer.onNext(onError(err)); observer.completed(); }, function () { observer.onNext(onCompleted()); observer.onCompleted(); }); }).concatAll(); } /** * One of the Following: * Projects each element of an observable sequence to an observable sequence and merges the resulting observable sequences into one observable sequence. * * @example * var res = source.selectMany(function (x) { return Rx.Observable.range(0, x); }); * Or: * Projects each element of an observable sequence to an observable sequence, invokes the result selector for the source element and each of the corresponding inner sequence's elements, and merges the results into one observable sequence. * * var res = source.selectMany(function (x) { return Rx.Observable.range(0, x); }, function (x, y) { return x + y; }); * Or: * Projects each element of the source observable sequence to the other observable sequence and merges the resulting observable sequences into one observable sequence. * * var res = source.selectMany(Rx.Observable.fromArray([1,2,3])); * @param selector A transform function to apply to each element or an observable sequence to project each element from the * source sequence onto which could be either an observable or Promise. * @param {Function} [resultSelector] A transform function to apply to each element of the intermediate sequence. * @returns {Observable} An observable sequence whose elements are the result of invoking the one-to-many transform function collectionSelector on each element of the input sequence and then mapping each of those sequence elements and their corresponding source element to a result element. */ observableProto.selectConcat = observableProto.concatMap = function (selector, resultSelector) { if (resultSelector) { return this.concatMap(function (x, i) { var selectorResult = selector(x, i), result = isPromise(selectorResult) ? observableFromPromise(selectorResult) : selectorResult; return result.map(function (y) { return resultSelector(x, y, i); }); }); } if (typeof selector === 'function') { return concatMap.call(this, selector); } return concatMap.call(this, function () { return selector; }); }; /** * 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; if (defaultValue === undefined) { defaultValue = null; } return new AnonymousObservable(function (observer) { var found = false; return source.subscribe(function (x) { found = true; observer.onNext(x); }, observer.onError.bind(observer), function () { if (!found) { observer.onNext(defaultValue); } observer.onCompleted(); }); }); }; /** * 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 (x) { return x.toString(); }); * @param {Function} [keySelector] A function to compute the comparison key for each element. * @param {Function} [keySerializer] Used to serialize the given object into a string for object comparison. * @returns {Observable} An observable sequence only containing the distinct elements, based on a computed key value, from the source sequence. */ observableProto.distinct = function (keySelector, keySerializer) { var source = this; keySelector || (keySelector = identity); keySerializer || (keySerializer = defaultKeySerializer); return new AnonymousObservable(function (observer) { var hashSet = {}; return source.subscribe(function (x) { var key, serializedKey, otherKey, hasMatch = false; try { key = keySelector(x); serializedKey = keySerializer(key); } catch (exception) { observer.onError(exception); return; } for (otherKey in hashSet) { if (serializedKey === otherKey) { hasMatch = true; break; } } if (!hasMatch) { hashSet[serializedKey] = null; observer.onNext(x); } }, observer.onError.bind(observer), observer.onCompleted.bind(observer)); }); }; /** * Groups the elements of an observable sequence according to a specified key selector function and comparer and selects the resulting elements by using a specified function. * * @example * var res = observable.groupBy(function (x) { return x.id; }); * 2 - observable.groupBy(function (x) { return x.id; }), function (x) { return x.name; }); * 3 - observable.groupBy(function (x) { return x.id; }), function (x) { return x.name; }, function (x) { return x.toString(); }); * @param {Function} keySelector A function to extract the key for each element. * @param {Function} [elementSelector] A function to map each source element to an element in an observable group. * @param {Function} [keySerializer] Used to serialize the given object into a string for object comparison. * @returns {Observable} A sequence of observable groups, each of which corresponds to a unique key value, containing all elements that share that same key value. */ observableProto.groupBy = function (keySelector, elementSelector, keySerializer) { return this.groupByUntil(keySelector, elementSelector, function () { return observableNever(); }, keySerializer); }; /** * Groups the elements of an observable sequence according to a specified key selector function. * A duration selector function is used to control the lifetime of groups. When a group expires, it receives an OnCompleted notification. When a new element with the same * key value as a reclaimed group occurs, the group will be reborn with a new lifetime request. * * @example * var res = observable.groupByUntil(function (x) { return x.id; }, null, function () { return Rx.Observable.never(); }); * 2 - observable.groupBy(function (x) { return x.id; }), function (x) { return x.name; }, function () { return Rx.Observable.never(); }); * 3 - observable.groupBy(function (x) { return x.id; }), function (x) { return x.name; }, function () { return Rx.Observable.never(); }, function (x) { return x.toString(); }); * @param {Function} keySelector A function to extract the key for each element. * @param {Function} durationSelector A function to signal the expiration of a group. * @param {Function} [keySerializer] Used to serialize the given object into a string for object comparison. * @returns {Observable} * A sequence of observable groups, each of which corresponds to a unique key value, containing all elements that share that same key value. * If a group's lifetime expires, a new group with the same key value can be created once an element with such a key value is encoutered. * */ observableProto.groupByUntil = function (keySelector, elementSelector, durationSelector, keySerializer) { var source = this; elementSelector || (elementSelector = identity); keySerializer || (keySerializer = defaultKeySerializer); return new AnonymousObservable(function (observer) { var map = {}, groupDisposable = new CompositeDisposable(), refCountDisposable = new RefCountDisposable(groupDisposable); groupDisposable.add(source.subscribe(function (x) { var duration, durationGroup, element, fireNewMapEntry, group, key, serializedKey, md, writer, w; try { key = keySelector(x); serializedKey = keySerializer(key); } catch (e) { for (w in map) { map[w].onError(e); } observer.onError(e); return; } fireNewMapEntry = false; try { writer = map[serializedKey]; if (!writer) { writer = new Subject(); map[serializedKey] = writer; fireNewMapEntry = true; } } catch (e) { for (w in map) { map[w].onError(e); } observer.onError(e); return; } if (fireNewMapEntry) { group = new GroupedObservable(key, writer, refCountDisposable); durationGroup = new GroupedObservable(key, writer); try { duration = durationSelector(durationGroup); } catch (e) { for (w in map) { map[w].onError(e); } observer.onError(e); return; } observer.onNext(group); md = new SingleAssignmentDisposable(); groupDisposable.add(md); var expire = function () { if (serializedKey in map) { delete map[serializedKey]; writer.onCompleted(); } groupDisposable.remove(md); }; md.setDisposable(duration.take(1).subscribe(noop, function (exn) { for (w in map) { map[w].onError(exn); } observer.onError(exn); }, function () { expire(); })); } try { element = elementSelector(x); } catch (e) { for (w in map) { map[w].onError(e); } observer.onError(e); return; } writer.onNext(element); }, function (ex) { for (var w in map) { map[w].onError(ex); } observer.onError(ex); }, function () { for (var w in map) { map[w].onCompleted(); } observer.onCompleted(); })); return refCountDisposable; }); }; /** * 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.select = observableProto.map = function (selector, thisArg) { var parent = this; return new AnonymousObservable(function (observer) { var count = 0; return parent.subscribe(function (value) { var result; try { result = selector.call(thisArg, value, count++, parent); } catch (exception) { observer.onError(exception); return; } observer.onNext(result); }, observer.onError.bind(observer), observer.onCompleted.bind(observer)); }); }; /** * Retrieves the value of a specified property from all elements in the Observable sequence. * @param {String} property The property to pluck. * @returns {Observable} Returns a new Observable sequence of property values. */ observableProto.pluck = function (property) { return this.select(function (x) { return x[property]; }); }; function selectMany(selector) { return this.select(function (x, i) { var result = selector(x, i); return isPromise(result) ? observableFromPromise(result) : result; }).mergeObservable(); } function selectManyObserver(onNext, onError, onCompleted) { var source = this; return new AnonymousObservable(function (observer) { var index = 0; return source.subscribe( function (x) { observer.onNext(onNext(x, index++)); }, function (err) { observer.onNext(onError(err)); observer.completed(); }, function () { observer.onNext(onCompleted()); observer.onCompleted(); }); }).mergeAll(); } /** * One of the Following: * Projects each element of an observable sequence to an observable sequence and merges the resulting observable sequences into one observable sequence. * * @example * var res = source.selectMany(function (x) { return Rx.Observable.range(0, x); }); * Or: * Projects each element of an observable sequence to an observable sequence, invokes the result selector for the source element and each of the corresponding inner sequence's elements, and merges the results into one observable sequence. * * var res = source.selectMany(function (x) { return Rx.Observable.range(0, x); }, function (x, y) { return x + y; }); * Or: * Projects each element of the source observable sequence to the other observable sequence and merges the resulting observable sequences into one observable sequence. * * var res = source.selectMany(Rx.Observable.fromArray([1,2,3])); * @param selector A transform function to apply to each element or an observable sequence to project each element from the * source sequence onto which could be either an observable or Promise. * @param {Function} [resultSelector] A transform function to apply to each element of the intermediate sequence. * @returns {Observable} An observable sequence whose elements are the result of invoking the one-to-many transform function collectionSelector on each element of the input sequence and then mapping each of those sequence elements and their corresponding source element to a result element. */ observableProto.selectMany = observableProto.flatMap = function (selector, resultSelector) { if (resultSelector) { return this.selectMany(function (x, i) { var selectorResult = selector(x, i), result = isPromise(selectorResult) ? observableFromPromise(selectorResult) : selectorResult; return result.select(function (y) { return resultSelector(x, y, i); }); }); } if (typeof selector === 'function') { return selectMany.call(this, selector); } return selectMany.call(this, function () { return selector; }); }; /** * Projects each element of an observable sequence into a new sequence of observable sequences by incorporating the element's index and then * transforms an observable sequence of observable sequences into an observable sequence producing values only from the most recent observable sequence. * @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 producing an Observable of Observable sequences * and that at any point in time produces the elements of the most recent inner observable sequence that has been received. */ observableProto.selectSwitch = observableProto.flatMapLatest = function (selector, thisArg) { return this.select(selector, thisArg).switchLatest(); }; /** * 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 Error(argumentOutOfRange); } var observable = this; return new AnonymousObservable(function (observer) { var remaining = count; return observable.subscribe(function (x) { if (remaining <= 0) { observer.onNext(x); } else { remaining--; } }, observer.onError.bind(observer), observer.onCompleted.bind(observer)); }); }; /** * 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; return new AnonymousObservable(function (observer) { var i = 0, running = false; return source.subscribe(function (x) { if (!running) { try { running = !predicate.call(thisArg, x, i++, source); } catch (e) { observer.onError(e); return; } } if (running) { observer.onNext(x); } }, observer.onError.bind(observer), observer.onCompleted.bind(observer)); }); }; /** * 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 Error(argumentOutOfRange); } if (count === 0) { return observableEmpty(scheduler); } var observable = this; return new AnonymousObservable(function (observer) { var remaining = count; return observable.subscribe(function (x) { if (remaining > 0) { remaining--; observer.onNext(x); if (remaining === 0) { observer.onCompleted(); } } }, observer.onError.bind(observer), observer.onCompleted.bind(observer)); }); }; /** * 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. * * @example * var res = source.takeWhile(function (value) { return value < 10; }); * var res = source.takeWhile(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 that occur before the element at which the test no longer passes. */ observableProto.takeWhile = function (predicate, thisArg) { var observable = this; return new AnonymousObservable(function (observer) { var i = 0, running = true; return observable.subscribe(function (x) { if (running) { try { running = predicate.call(thisArg, x, i++, observable); } catch (e) { observer.onError(e); return; } if (running) { observer.onNext(x); } else { observer.onCompleted(); } } }, observer.onError.bind(observer), observer.onCompleted.bind(observer)); }); }; /** * Filters the elements of an observable sequence based on a predicate by incorporating the element's index. * * @example * var res = source.where(function (value) { return value < 10; }); * var res = source.where(function (value, index) { return value < 10 || index < 10; }); * @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.where = observableProto.filter = function (predicate, thisArg) { var parent = this; return new AnonymousObservable(function (observer) { var count = 0; return parent.subscribe(function (value) { var shouldRun; try { shouldRun = predicate.call(thisArg, value, count++, parent); } catch (exception) { observer.onError(exception); return; } if (shouldRun) { observer.onNext(value); } }, observer.onError.bind(observer), observer.onCompleted.bind(observer)); }); }; observableProto.finalValue = function () { var source = this; return new AnonymousObservable(function (observer) { var hasValue = false, value; return source.subscribe(function (x) { hasValue = true; value = x; }, observer.onError.bind(observer), function () { if (!hasValue) { observer.onError(new Error(sequenceContainsNoElements)); } else { observer.onNext(value); observer.onCompleted(); } }); }); }; function extremaBy(source, keySelector, comparer) { return new AnonymousObservable(function (observer) { var hasValue = false, lastKey = null, list = []; return source.subscribe(function (x) { var comparison, key; try { key = keySelector(x); } catch (ex) { observer.onError(ex); return; } comparison = 0; if (!hasValue) { hasValue = true; lastKey = key; } else { try { comparison = comparer(key, lastKey); } catch (ex1) { observer.onError(ex1); return; } } if (comparison > 0) { lastKey = key; list = []; } if (comparison >= 0) { list.push(x); } }, observer.onError.bind(observer), function () { observer.onNext(list); observer.onCompleted(); }); }); } function firstOnly(x) { if (x.length === 0) { throw new Error(sequenceContainsNoElements); } return x[0]; } /** * Applies an accumulator function over an observable sequence, returning the result of the aggregation as a single element in the result sequence. The specified seed value is used as the initial accumulator value. * For aggregation behavior with incremental intermediate results, see Observable.scan. * @example * 1 - res = source.aggregate(function (acc, x) { return acc + x; }); * 2 - res = source.aggregate(0, function (acc, x) { return acc + x; }); * @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 a single element with the final accumulator value. */ observableProto.aggregate = function () { var seed, hasSeed, accumulator; if (arguments.length === 2) { seed = arguments[0]; hasSeed = true; accumulator = arguments[1]; } else { accumulator = arguments[0]; } return hasSeed ? this.scan(seed, accumulator).startWith(seed).finalValue() : this.scan(accumulator).finalValue(); }; /** * Applies an accumulator function over an observable sequence, returning the result of the aggregation as a single element in the result sequence. The specified seed value is used as the initial accumulator value. * For aggregation behavior with incremental intermediate results, see Observable.scan. * @example * 1 - res = source.reduce(function (acc, x) { return acc + x; }); * 2 - res = source.reduce(function (acc, x) { return acc + x; }, 0); * @param {Function} accumulator An accumulator function to be invoked on each element. * @param {Any} [seed] The initial accumulator value. * @returns {Observable} An observable sequence containing a single element with the final accumulator value. */ observableProto.reduce = function (accumulator) { var seed, hasSeed; if (arguments.length === 2) { hasSeed = true; seed = arguments[1]; } return hasSeed ? this.scan(seed, accumulator).startWith(seed).finalValue() : this.scan(accumulator).finalValue(); }; /** * Determines whether any element of an observable sequence satisfies a condition if present, else if any items are in the sequence. * @example * var result = source.any(); * var result = source.any(function (x) { return x > 3; }); * @param {Function} [predicate] A function to test each element for a condition. * @returns {Observable} An observable sequence containing a single element determining whether any elements in the source sequence pass the test in the specified predicate if given, else if any items are in the sequence. */ observableProto.some = observableProto.any = function (predicate, thisArg) { var source = this; return predicate ? source.where(predicate, thisArg).any() : new AnonymousObservable(function (observer) { return source.subscribe(function () { observer.onNext(true); observer.onCompleted(); }, observer.onError.bind(observer), function () { observer.onNext(false); observer.onCompleted(); }); }); }; /** * Determines whether an observable sequence is empty. * * @memberOf Observable# * @returns {Observable} An observable sequence containing a single element determining whether the source sequence is empty. */ observableProto.isEmpty = function () { return this.any().select(function (b) { return !b; }); }; /** * Determines whether all elements of an observable sequence satisfy a condition. * * 1 - res = source.all(function (value) { return value.length > 3; }); * @memberOf Observable# * @param {Function} [predicate] A function to test each element for a condition. * @param {Any} [thisArg] Object to use as this when executing callback. * @returns {Observable} An observable sequence containing a single element determining whether all elements in the source sequence pass the test in the specified predicate. */ observableProto.every = observableProto.all = function (predicate, thisArg) { return this.where(function (v) { return !predicate(v); }, thisArg).any().select(function (b) { return !b; }); }; /** * Determines whether an observable sequence contains a specified element with an optional equality comparer. * @example * 1 - res = source.contains(42); * 2 - res = source.contains({ value: 42 }, function (x, y) { return x.value === y.value; }); * @param value The value to locate in the source sequence. * @param {Function} [comparer] An equality comparer to compare elements. * @returns {Observable} An observable sequence containing a single element determining whether the source sequence contains an element that has the specified value. */ observableProto.contains = function (value, comparer) { comparer || (comparer = defaultComparer); return this.where(function (v) { return comparer(v, value); }).any(); }; /** * Returns an observable sequence containing a value that represents how many elements in the specified observable sequence satisfy a condition if provided, else the count of items. * @example * res = source.count(); * res = source.count(function (x) { return x > 3; }); * @param {Function} [predicate]A function to test each element for a condition. * @param {Any} [thisArg] Object to use as this when executing callback. * @returns {Observable} An observable sequence containing a single element with a number that represents how many elements in the input sequence satisfy the condition in the predicate function if provided, else the count of items in the sequence. */ observableProto.count = function (predicate, thisArg) { return predicate ? this.where(predicate, thisArg).count() : this.aggregate(0, function (count) { return count + 1; }); }; /** * Computes the sum of a sequence of values that are obtained by invoking an optional transform function on each element of the input sequence, else if not specified computes the sum on each item in the sequence. * @example * var res = source.sum(); * var res = source.sum(function (x) { return x.value; }); * @param {Function} [selector] A transform function to apply to each element. * @param {Any} [thisArg] Object to use as this when executing callback. * @returns {Observable} An observable sequence containing a single element with the sum of the values in the source sequence. */ observableProto.sum = function (keySelector, thisArg) { return keySelector ? this.select(keySelector, thisArg).sum() : this.aggregate(0, function (prev, curr) { return prev + curr; }); }; /** * Returns the elements in an observable sequence with the minimum key value according to the specified comparer. * @example * var res = source.minBy(function (x) { return x.value; }); * var res = source.minBy(function (x) { return x.value; }, function (x, y) { return x - y; }); * @param {Function} keySelector Key selector function. * @param {Function} [comparer] Comparer used to compare key values. * @returns {Observable} An observable sequence containing a list of zero or more elements that have a minimum key value. */ observableProto.minBy = function (keySelector, comparer) { comparer || (comparer = defaultSubComparer); return extremaBy(this, keySelector, function (x, y) { return comparer(x, y) * -1; }); }; /** * Returns the minimum element in an observable sequence according to the optional comparer else a default greater than less than check. * @example * var res = source.min(); * var res = source.min(function (x, y) { return x.value - y.value; }); * @param {Function} [comparer] Comparer used to compare elements. * @returns {Observable} An observable sequence containing a single element with the minimum element in the source sequence. */ observableProto.min = function (comparer) { return this.minBy(identity, comparer).select(function (x) { return firstOnly(x); }); }; /** * Returns the elements in an observable sequence with the maximum key value according to the specified comparer. * @example * var res = source.maxBy(function (x) { return x.value; }); * var res = source.maxBy(function (x) { return x.value; }, function (x, y) { return x - y;; }); * @param {Function} keySelector Key selector function. * @param {Function} [comparer] Comparer used to compare key values. * @returns {Observable} An observable sequence containing a list of zero or more elements that have a maximum key value. */ observableProto.maxBy = function (keySelector, comparer) { comparer || (comparer = defaultSubComparer); return extremaBy(this, keySelector, comparer); }; /** * Returns the maximum value in an observable sequence according to the specified comparer. * @example * var res = source.max(); * var res = source.max(function (x, y) { return x.value - y.value; }); * @param {Function} [comparer] Comparer used to compare elements. * @returns {Observable} An observable sequence containing a single element with the maximum element in the source sequence. */ observableProto.max = function (comparer) { return this.maxBy(identity, comparer).select(function (x) { return firstOnly(x); }); }; /** * Computes the average of an observable sequence of values that are in the sequence or obtained by invoking a transform function on each element of the input sequence if present. * @example * var res = res = source.average(); * var res = res = source.average(function (x) { return x.value; }); * @param {Function} [selector] A transform function to apply to each element. * @param {Any} [thisArg] Object to use as this when executing callback. * @returns {Observable} An observable sequence containing a single element with the average of the sequence of values. */ observableProto.average = function (keySelector, thisArg) { return keySelector ? this.select(keySelector, thisArg).average() : this.scan({ sum: 0, count: 0 }, function (prev, cur) { return { sum: prev.sum + cur, count: prev.count + 1 }; }).finalValue().select(function (s) { if (s.count === 0) { throw new Error('The input sequence was empty'); } return s.sum / s.count; }); }; function sequenceEqualArray(first, second, comparer) { return new AnonymousObservable(function (observer) { var count = 0, len = second.length; return first.subscribe(function (value) { var equal = false; try { if (count < len) { equal = comparer(value, second[count++]); } } catch (e) { observer.onError(e); return; } if (!equal) { observer.onNext(false); observer.onCompleted(); } }, observer.onError.bind(observer), function () { observer.onNext(count === len); observer.onCompleted(); }); }); } /** * Determines whether two sequences are equal by comparing the elements pairwise using a specified equality comparer. * * @example * var res = res = source.sequenceEqual([1,2,3]); * var res = res = source.sequenceEqual([{ value: 42 }], function (x, y) { return x.value === y.value; }); * 3 - res = source.sequenceEqual(Rx.Observable.returnValue(42)); * 4 - res = source.sequenceEqual(Rx.Observable.returnValue({ value: 42 }), function (x, y) { return x.value === y.value; }); * @param {Observable} second Second observable sequence or array to compare. * @param {Function} [comparer] Comparer used to compare elements of both sequences. * @returns {Observable} An observable sequence that contains a single element which indicates whether both sequences are of equal length and their corresponding elements are equal according to the specified equality comparer. */ observableProto.sequenceEqual = function (second, comparer) { var first = this; comparer || (comparer = defaultComparer); if (Array.isArray(second)) { return sequenceEqualArray(first, second, comparer); } return new AnonymousObservable(function (observer) { var donel = false, doner = false, ql = [], qr = []; var subscription1 = first.subscribe(function (x) { var equal, v; if (qr.length > 0) { v = qr.shift(); try { equal = comparer(v, x); } catch (e) { observer.onError(e); return; } if (!equal) { observer.onNext(false); observer.onCompleted(); } } else if (doner) { observer.onNext(false); observer.onCompleted(); } else { ql.push(x); } }, observer.onError.bind(observer), function () { donel = true; if (ql.length === 0) { if (qr.length > 0) { observer.onNext(false); observer.onCompleted(); } else if (doner) { observer.onNext(true); observer.onCompleted(); } } }); isPromise(second) && (second = observableFromPromise(second)); var subscription2 = second.subscribe(function (x) { var equal, v; if (ql.length > 0) { v = ql.shift(); try { equal = comparer(v, x); } catch (exception) { observer.onError(exception); return; } if (!equal) { observer.onNext(false); observer.onCompleted(); } } else if (donel) { observer.onNext(false); observer.onCompleted(); } else { qr.push(x); } }, observer.onError.bind(observer), function () { doner = true; if (qr.length === 0) { if (ql.length > 0) { observer.onNext(false); observer.onCompleted(); } else if (donel) { observer.onNext(true); observer.onCompleted(); } } }); return new CompositeDisposable(subscription1, subscription2); }); }; function elementAtOrDefault(source, index, hasDefault, defaultValue) { if (index < 0) { throw new Error(argumentOutOfRange); } return new AnonymousObservable(function (observer) { var i = index; return source.subscribe(function (x) { if (i === 0) { observer.onNext(x); observer.onCompleted(); } i--; }, observer.onError.bind(observer), function () { if (!hasDefault) { observer.onError(new Error(argumentOutOfRange)); } else { observer.onNext(defaultValue); observer.onCompleted(); } }); }); } /** * Returns the element at a specified index in a sequence. * @example * var res = source.elementAt(5); * @param {Number} index The zero-based index of the element to retrieve. * @returns {Observable} An observable sequence that produces the element at the specified position in the source sequence. */ observableProto.elementAt = function (index) { return elementAtOrDefault(this, index, false); }; /** * Returns the element at a specified index in a sequence or a default value if the index is out of range. * @example * var res = source.elementAtOrDefault(5); * var res = source.elementAtOrDefault(5, 0); * @param {Number} index The zero-based index of the element to retrieve. * @param [defaultValue] The default value if the index is outside the bounds of the source sequence. * @returns {Observable} An observable sequence that produces the element at the specified position in the source sequence, or a default value if the index is outside the bounds of the source sequence. */ observableProto.elementAtOrDefault = function (index, defaultValue) { return elementAtOrDefault(this, index, true, defaultValue); }; function singleOrDefaultAsync(source, hasDefault, defaultValue) { return new AnonymousObservable(function (observer) { var value = defaultValue, seenValue = false; return source.subscribe(function (x) { if (seenValue) { observer.onError(new Error('Sequence contains more than one element')); } else { value = x; seenValue = true; } }, observer.onError.bind(observer), function () { if (!seenValue && !hasDefault) { observer.onError(new Error(sequenceContainsNoElements)); } else { observer.onNext(value); observer.onCompleted(); } }); }); } /** * Returns the only element of an observable sequence that satisfies the condition in the optional predicate, and reports an exception if there is not exactly one element in the observable sequence. * @example * var res = res = source.single(); * var res = res = source.single(function (x) { return x === 42; }); * @param {Function} [predicate] A predicate function to evaluate for elements in the source sequence. * @param {Any} [thisArg] Object to use as `this` when executing the predicate. * @returns {Observable} Sequence containing the single element in the observable sequence that satisfies the condition in the predicate. */ observableProto.single = function (predicate, thisArg) { return predicate ? this.where(predicate, thisArg).single() : singleOrDefaultAsync(this, false); }; /** * Returns the only element of an observable sequence that matches the predicate, or a default value if no such element exists; this method reports an exception if there is more than one element in the observable sequence. * @example * var res = res = source.singleOrDefault(); * var res = res = source.singleOrDefault(function (x) { return x === 42; }); * res = source.singleOrDefault(function (x) { return x === 42; }, 0); * res = source.singleOrDefault(null, 0); * @memberOf Observable# * @param {Function} predicate A predicate function to evaluate for elements in the source sequence. * @param [defaultValue] The default value if the index is outside the bounds of the source sequence. * @param {Any} [thisArg] Object to use as `this` when executing the predicate. * @returns {Observable} Sequence containing the single element in the observable sequence that satisfies the condition in the predicate, or a default value if no such element exists. */ observableProto.singleOrDefault = function (predicate, defaultValue, thisArg) { return predicate? this.where(predicate, thisArg).singleOrDefault(null, defaultValue) : singleOrDefaultAsync(this, true, defaultValue) }; function firstOrDefaultAsync(source, hasDefault, defaultValue) { return new AnonymousObservable(function (observer) { return source.subscribe(function (x) { observer.onNext(x); observer.onCompleted(); }, observer.onError.bind(observer), function () { if (!hasDefault) { observer.onError(new Error(sequenceContainsNoElements)); } else { observer.onNext(defaultValue); observer.onCompleted(); } }); }); } /** * Returns the first element of an observable sequence that satisfies the condition in the predicate if present else the first item in the sequence. * @example * var res = res = source.first(); * var res = res = source.first(function (x) { return x > 3; }); * @param {Function} [predicate] A predicate function to evaluate for elements in the source sequence. * @param {Any} [thisArg] Object to use as `this` when executing the predicate. * @returns {Observable} Sequence containing the first element in the observable sequence that satisfies the condition in the predicate if provided, else the first item in the sequence. */ observableProto.first = function (predicate, thisArg) { return predicate ? this.where(predicate, thisArg).first() : firstOrDefaultAsync(this, false); }; /** * Returns the first element of an observable sequence that satisfies the condition in the predicate, or a default value if no such element exists. * @example * var res = res = source.firstOrDefault(); * var res = res = source.firstOrDefault(function (x) { return x > 3; }); * var res = source.firstOrDefault(function (x) { return x > 3; }, 0); * var res = source.firstOrDefault(null, 0); * @param {Function} [predicate] A predicate function to evaluate for elements in the source sequence. * @param {Any} [defaultValue] The default value if no such element exists. If not specified, defaults to null. * @param {Any} [thisArg] Object to use as `this` when executing the predicate. * @returns {Observable} Sequence containing the first element in the observable sequence that satisfies the condition in the predicate, or a default value if no such element exists. */ observableProto.firstOrDefault = function (predicate, defaultValue, thisArg) { return predicate ? this.where(predicate).firstOrDefault(null, defaultValue) : firstOrDefaultAsync(this, true, defaultValue); }; function lastOrDefaultAsync(source, hasDefault, defaultValue) { return new AnonymousObservable(function (observer) { var value = defaultValue, seenValue = false; return source.subscribe(function (x) { value = x; seenValue = true; }, observer.onError.bind(observer), function () { if (!seenValue && !hasDefault) { observer.onError(new Error(sequenceContainsNoElements)); } else { observer.onNext(value); observer.onCompleted(); } }); }); } /** * Returns the last element of an observable sequence that satisfies the condition in the predicate if specified, else the last element. * @example * var res = source.last(); * var res = source.last(function (x) { return x > 3; }); * @param {Function} [predicate] A predicate function to evaluate for elements in the source sequence. * @param {Any} [thisArg] Object to use as `this` when executing the predicate. * @returns {Observable} Sequence containing the last element in the observable sequence that satisfies the condition in the predicate. */ observableProto.last = function (predicate, thisArg) { return predicate ? this.where(predicate, thisArg).last() : lastOrDefaultAsync(this, false); }; /** * Returns the last element of an observable sequence that satisfies the condition in the predicate, or a default value if no such element exists. * @example * var res = source.lastOrDefault(); * var res = source.lastOrDefault(function (x) { return x > 3; }); * var res = source.lastOrDefault(function (x) { return x > 3; }, 0); * var res = source.lastOrDefault(null, 0); * @param {Function} [predicate] A predicate function to evaluate for elements in the source sequence. * @param [defaultValue] The default value if no such element exists. If not specified, defaults to null. * @param {Any} [thisArg] Object to use as `this` when executing the predicate. * @returns {Observable} Sequence containing the last element in the observable sequence that satisfies the condition in the predicate, or a default value if no such element exists. */ observableProto.lastOrDefault = function (predicate, defaultValue, thisArg) { return predicate ? this.where(predicate, thisArg).lastOrDefault(null, defaultValue) : lastOrDefaultAsync(this, true, defaultValue); }; function findValue (source, predicate, thisArg, yieldIndex) { return new AnonymousObservable(function (observer) { var i = 0; return source.subscribe(function (x) { var shouldRun; try { shouldRun = predicate.call(thisArg, x, i, source); } catch(e) { observer.onError(e); return; } if (shouldRun) { observer.onNext(yieldIndex ? i : x); observer.onCompleted(); } else { i++; } }, observer.onError.bind(observer), function () { observer.onNext(yieldIndex ? -1 : undefined); observer.onCompleted(); }); }); } /** * Searches for an element that matches the conditions defined by the specified predicate, and returns the first occurrence within the entire Observable sequence. * @param {Function} predicate The predicate that defines the conditions of the element to search for. * @param {Any} [thisArg] Object to use as `this` when executing the predicate. * @returns {Observable} An Observable sequence with the first element that matches the conditions defined by the specified predicate, if found; otherwise, undefined. */ observableProto.find = function (predicate, thisArg) { return findValue(this, predicate, thisArg, false); }; /** * Searches for an element that matches the conditions defined by the specified predicate, and returns * an Observable sequence with the zero-based index of the first occurrence within the entire Observable sequence. * @param {Function} predicate The predicate that defines the conditions of the element to search for. * @param {Any} [thisArg] Object to use as `this` when executing the predicate. * @returns {Observable} An Observable sequence with the zero-based index of the first occurrence of an element that matches the conditions defined by match, if found; otherwise, –1. */ observableProto.findIndex = function (predicate, thisArg) { return findValue(this, predicate, thisArg, true); }; /** * Invokes the specified function asynchronously on the specified scheduler, surfacing the result through an observable sequence. * * @example * var res = Rx.Observable.start(function () { console.log('hello'); }); * var res = Rx.Observable.start(function () { console.log('hello'); }, Rx.Scheduler.timeout); * var res = Rx.Observable.start(function () { this.log('hello'); }, Rx.Scheduler.timeout, console); * * @param {Function} func Function to run asynchronously. * @param {Scheduler} [scheduler] Scheduler to run the function on. If not specified, defaults to Scheduler.timeout. * @param [context] The context for the func parameter to be executed. If not specified, defaults to undefined. * @returns {Observable} An observable sequence exposing the function's result value, or an exception. * * Remarks * * The function is called immediately, not during the subscription of the resulting sequence. * * Multiple subscriptions to the resulting sequence can observe the function's result. */ Observable.start = function (func, scheduler, context) { return observableToAsync(func, scheduler, context)(); }; /** * Converts the function into an asynchronous function. Each invocation of the resulting asynchronous function causes an invocation of the original synchronous function on the specified scheduler. * * @example * var res = Rx.Observable.toAsync(function (x, y) { return x + y; })(4, 3); * var res = Rx.Observable.toAsync(function (x, y) { return x + y; }, Rx.Scheduler.timeout)(4, 3); * var res = Rx.Observable.toAsync(function (x) { this.log(x); }, Rx.Scheduler.timeout, console)('hello'); * * @param {Function} function Function to convert to an asynchronous function. * @param {Scheduler} [scheduler] Scheduler to run the function on. If not specified, defaults to Scheduler.timeout. * @param {Mixed} [context] The context for the func parameter to be executed. If not specified, defaults to undefined. * @returns {Function} Asynchronous function. */ var observableToAsync = Observable.toAsync = function (func, scheduler, context) { scheduler || (scheduler = timeoutScheduler); return function () { var args = arguments, subject = new AsyncSubject(); scheduler.schedule(function () { var result; try { result = func.apply(context, args); } catch (e) { subject.onError(e); return; } subject.onNext(result); subject.onCompleted(); }); return subject.asObservable(); }; }; /** * Converts a callback function to an observable sequence. * * @param {Function} function Function with a callback as the last parameter to convert to an Observable sequence. * @param {Scheduler} [scheduler] Scheduler to run the function on. If not specified, defaults to Scheduler.timeout. * @param {Mixed} [context] The context for the func parameter to be executed. If not specified, defaults to undefined. * @param {Function} [selector] A selector which takes the arguments from the callback to produce a single item to yield on next. * @returns {Function} A function, when executed with the required parameters minus the callback, produces an Observable sequence with a single value of the arguments to the callback as an array. */ Observable.fromCallback = function (func, scheduler, context, selector) { scheduler || (scheduler = immediateScheduler); return function () { var args = slice.call(arguments, 0); return new AnonymousObservable(function (observer) { return scheduler.schedule(function () { function handler(e) { var results = e; if (selector) { try { results = selector(arguments); } catch (err) { observer.onError(err); return; } } else { if (results.length === 1) { results = results[0]; } } observer.onNext(results); observer.onCompleted(); } args.push(handler); func.apply(context, args); }); }); }; }; /** * Converts a Node.js callback style function to an observable sequence. This must be in function (err, ...) format. * @param {Function} func The function to call * @param {Scheduler} [scheduler] Scheduler to run the function on. If not specified, defaults to Scheduler.timeout. * @param {Mixed} [context] The context for the func parameter to be executed. If not specified, defaults to undefined. * @param {Function} [selector] A selector which takes the arguments from the callback minus the error to produce a single item to yield on next. * @returns {Function} An async function which when applied, returns an observable sequence with the callback arguments as an array. */ Observable.fromNodeCallback = function (func, scheduler, context, selector) { scheduler || (scheduler = immediateScheduler); return function () { var args = slice.call(arguments, 0); return new AnonymousObservable(function (observer) { return scheduler.schedule(function () { function handler(err) { if (err) { observer.onError(err); return; } var results = slice.call(arguments, 1); if (selector) { try { results = selector(results); } catch (e) { observer.onError(e); return; } } else { if (results.length === 1) { results = results[0]; } } observer.onNext(results); observer.onCompleted(); } args.push(handler); func.apply(context, args); }); }); }; }; function fixEvent(event) { var stopPropagation = function () { this.cancelBubble = true; }; var preventDefault = function () { this.bubbledKeyCode = this.keyCode; if (this.ctrlKey) { try { this.keyCode = 0; } catch (e) { } } this.defaultPrevented = true; this.returnValue = false; this.modified = true; }; event || (event = root.event); if (!event.target) { event.target = event.target || event.srcElement; if (event.type == 'mouseover') { event.relatedTarget = event.fromElement; } if (event.type == 'mouseout') { event.relatedTarget = event.toElement; } // Adding stopPropogation and preventDefault to IE if (!event.stopPropagation){ event.stopPropagation = stopPropagation; event.preventDefault = preventDefault; } // Normalize key events switch(event.type){ case 'keypress': var c = ('charCode' in event ? event.charCode : event.keyCode); if (c == 10) { c = 0; event.keyCode = 13; } else if (c == 13 || c == 27) { c = 0; } else if (c == 3) { c = 99; } event.charCode = c; event.keyChar = event.charCode ? String.fromCharCode(event.charCode) : ''; break; } } return event; } function createListener (element, name, handler) { // Node.js specific if (element.addListener) { element.addListener(name, handler); return disposableCreate(function () { element.removeListener(name, handler); }); } // Standards compliant if (element.addEventListener) { element.addEventListener(name, handler, false); return disposableCreate(function () { element.removeEventListener(name, handler, false); }); } if (element.attachEvent) { // IE Specific var innerHandler = function (event) { handler(fixEvent(event)); }; element.attachEvent('on' + name, innerHandler); return disposableCreate(function () { element.detachEvent('on' + name, innerHandler); }); } // Level 1 DOM Events element['on' + name] = handler; return disposableCreate(function () { element['on' + name] = null; }); } function createEventListener (el, eventName, handler) { var disposables = new CompositeDisposable(); // Asume NodeList if (typeof el.item === 'function' && typeof el.length === 'number') { for (var i = 0, len = el.length; i < len; i++) { disposables.add(createEventListener(el.item(i), eventName, handler)); } } else if (el) { disposables.add(createListener(el, eventName, handler)); } return disposables; } // Check for Angular/jQuery/Zepto support var jq = !!root.angular && !!angular.element ? angular.element : (!!root.jQuery ? root.jQuery : ( !!root.Zepto ? root.Zepto : null)); // Check for ember var ember = !!root.Ember && typeof root.Ember.addListener === 'function'; /** * Creates an observable sequence by adding an event listener to the matching DOMElement or each item in the NodeList. * * @example * var source = Rx.Observable.fromEvent(element, 'mouseup'); * * @param {Object} element The DOMElement or NodeList to attach a listener. * @param {String} eventName The event name to attach the observable sequence. * @param {Function} [selector] A selector which takes the arguments from the event handler to produce a single item to yield on next. * @returns {Observable} An observable sequence of events from the specified element and the specified event. */ Observable.fromEvent = function (element, eventName, selector) { if (ember) { return fromEventPattern( function (h) { Ember.addListener(element, eventName, h); }, function (h) { Ember.removeListener(element, eventName, h); }, selector); } if (jq) { var $elem = jq(element); return fromEventPattern( function (h) { $elem.on(eventName, h); }, function (h) { $elem.off(eventName, h); }, selector); } return new AnonymousObservable(function (observer) { return createEventListener( element, eventName, function handler (e) { var results = e; if (selector) { try { results = selector(arguments); } catch (err) { observer.onError(err); return } } observer.onNext(results); }); }).publish().refCount(); }; /** * Creates an observable sequence from an event emitter via an addHandler/removeHandler pair. * @param {Function} addHandler The function to add a handler to the emitter. * @param {Function} [removeHandler] The optional function to remove a handler from an emitter. * @param {Function} [selector] A selector which takes the arguments from the event handler to produce a single item to yield on next. * @returns {Observable} An observable sequence which wraps an event from an event emitter */ var fromEventPattern = Observable.fromEventPattern = function (addHandler, removeHandler, selector) { return new AnonymousObservable(function (observer) { function innerHandler (e) { var result = e; if (selector) { try { result = selector(arguments); } catch (err) { observer.onError(err); return; } } observer.onNext(result); } var returnValue = addHandler(innerHandler); return disposableCreate(function () { if (removeHandler) { removeHandler(innerHandler, returnValue); } }); }).publish().refCount(); }; /** * Invokes the asynchronous function, surfacing the result through an observable sequence. * @param {Function} functionAsync Asynchronous function which returns a Promise to run. * @returns {Observable} An observable sequence exposing the function's result value, or an exception. */ Observable.startAsync = function (functionAsync) { var promise; try { promise = functionAsync(); } catch (e) { return observableThrow(e); } return observableFromPromise(promise); } var PausableObservable = (function (_super) { inherits(PausableObservable, _super); function subscribe(observer) { var conn = this.source.publish(), subscription = conn.subscribe(observer), connection = disposableEmpty; var pausable = this.subject.distinctUntilChanged().subscribe(function (b) { if (b) { connection = conn.connect(); } else { connection.dispose(); connection = disposableEmpty; } }); return new CompositeDisposable(subscription, connection, pausable); } function PausableObservable(source, subject) { this.source = source; this.subject = subject || new Subject(); this.isPaused = true; _super.call(this, subscribe); } PausableObservable.prototype.pause = function () { if (this.isPaused === true){ return; } this.isPaused = true; this.subject.onNext(false); }; PausableObservable.prototype.resume = function () { if (this.isPaused === false){ return; } this.isPaused = false; this.subject.onNext(true); }; return PausableObservable; }(Observable)); /** * Pauses the underlying observable sequence based upon the observable sequence which yields true/false. * @example * var pauser = new Rx.Subject(); * var source = Rx.Observable.interval(100).pausable(pauser); * @param {Observable} pauser The observable sequence used to pause the underlying sequence. * @returns {Observable} The observable sequence which is paused based upon the pauser. */ observableProto.pausable = function (pauser) { return new PausableObservable(this, pauser); }; function combineLatestSource(source, subject, resultSelector) { return new AnonymousObservable(function (observer) { var n = 2, hasValue = [false, false], hasValueAll = false, isDone = false, values = new Array(n); function next(x, i) { values[i] = x var res; hasValue[i] = true; if (hasValueAll || (hasValueAll = hasValue.every(identity))) { try { res = resultSelector.apply(null, values); } catch (ex) { observer.onError(ex); return; } observer.onNext(res); } else if (isDone) { observer.onCompleted(); } } return new CompositeDisposable( source.subscribe( function (x) { next(x, 0); }, observer.onError.bind(observer), function () { isDone = true; observer.onCompleted(); }), subject.subscribe( function (x) { next(x, 1); }, observer.onError.bind(observer)) ); }); } var PausableBufferedObservable = (function (_super) { inherits(PausableBufferedObservable, _super); function subscribe(observer) { var q = [], previous = true; var subscription = combineLatestSource( this.source, this.subject.distinctUntilChanged(), function (data, shouldFire) { return { data: data, shouldFire: shouldFire }; }) .subscribe( function (results) { if (results.shouldFire && previous) { observer.onNext(results.data); } if (results.shouldFire && !previous) { while (q.length > 0) { observer.onNext(q.shift()); } previous = true; } else if (!results.shouldFire && !previous) { q.push(results.data); } else if (!results.shouldFire && previous) { previous = false; } }, function (err) { // Empty buffer before sending error while (q.length > 0) { observer.onNext(q.shift()); } observer.onError(err); }, function () { // Empty buffer before sending completion while (q.length > 0) { observer.onNext(q.shift()); } observer.onCompleted(); } ); this.subject.onNext(false); return subscription; } function PausableBufferedObservable(source, subject) { this.source = source; this.subject = subject || new Subject(); this.isPaused = true; _super.call(this, subscribe); } PausableBufferedObservable.prototype.pause = function () { if (this.isPaused === true){ return; } this.isPaused = true; this.subject.onNext(false); }; PausableBufferedObservable.prototype.resume = function () { if (this.isPaused === false){ return; } this.isPaused = false; this.subject.onNext(true); }; return PausableBufferedObservable; }(Observable)); /** * Pauses the underlying observable sequence based upon the observable sequence which yields true/false, * and yields the values that were buffered while paused. * @example * var pauser = new Rx.Subject(); * var source = Rx.Observable.interval(100).pausableBuffered(pauser); * @param {Observable} pauser The observable sequence used to pause the underlying sequence. * @returns {Observable} The observable sequence which is paused based upon the pauser. */ observableProto.pausableBuffered = function (subject) { return new PausableBufferedObservable(this, subject); }; /** * Attaches a controller to the observable sequence with the ability to queue. * @example * var source = Rx.Observable.interval(100).controlled(); * source.request(3); // Reads 3 values * @param {Observable} pauser The observable sequence used to pause the underlying sequence. * @returns {Observable} The observable sequence which is paused based upon the pauser. */ observableProto.controlled = function (enableQueue) { if (enableQueue == null) { enableQueue = true; } return new ControlledObservable(this, enableQueue); }; var ControlledObservable = (function (_super) { inherits(ControlledObservable, _super); function subscribe (observer) { return this.source.subscribe(observer); } function ControlledObservable (source, enableQueue) { _super.call(this, subscribe); this.subject = new ControlledSubject(enableQueue); this.source = source.multicast(this.subject).refCount(); } ControlledObservable.prototype.request = function (numberOfItems) { if (numberOfItems == null) { numberOfItems = -1; } return this.subject.request(numberOfItems); }; return ControlledObservable; }(Observable)); var ControlledSubject = Rx.ControlledSubject = (function (_super) { function subscribe (observer) { return this.subject.subscribe(observer); } inherits(ControlledSubject, _super); function ControlledSubject(enableQueue) { if (enableQueue == null) { enableQueue = true; } _super.call(this, subscribe); this.subject = new Subject(); this.enableQueue = enableQueue; this.queue = enableQueue ? [] : null; this.requestedCount = 0; this.requestedDisposable = disposableEmpty; this.error = null; this.hasFailed = false; this.hasCompleted = false; this.controlledDisposable = disposableEmpty; } addProperties(ControlledSubject.prototype, Observer, { onCompleted: function () { checkDisposed.call(this); this.hasCompleted = true; if (!this.enableQueue || this.queue.length === 0) { this.subject.onCompleted(); } }, onError: function (error) { checkDisposed.call(this); this.hasFailed = true; this.error = error; if (!this.enableQueue || this.queue.length === 0) { this.subject.onError(error); } }, onNext: function (value) { checkDisposed.call(this); var hasRequested = false; if (this.requestedCount === 0) { if (this.enableQueue) { this.queue.push(value); } } else { if (this.requestedCount !== -1) { if (this.requestedCount-- === 0) { this.disposeCurrentRequest(); } } hasRequested = true; } if (hasRequested) { this.subject.onNext(value); } }, _processRequest: function (numberOfItems) { if (this.enableQueue) { //console.log('queue length', this.queue.length); while (this.queue.length >= numberOfItems && numberOfItems > 0) { //console.log('number of items', numberOfItems); this.subject.onNext(this.queue.shift()); numberOfItems--; } if (this.queue.length !== 0) { return { numberOfItems: numberOfItems, returnValue: true }; } else { return { numberOfItems: numberOfItems, returnValue: false }; } } if (this.hasFailed) { this.subject.onError(this.error); this.controlledDisposable.dispose(); this.controlledDisposable = disposableEmpty; } else if (this.hasCompleted) { this.subject.onCompleted(); this.controlledDisposable.dispose(); this.controlledDisposable = disposableEmpty; } return { numberOfItems: numberOfItems, returnValue: false }; }, request: function (number) { checkDisposed.call(this); this.disposeCurrentRequest(); var self = this, r = this._processRequest(number); number = r.numberOfItems; if (!r.returnValue) { this.requestedCount = number; this.requestedDisposable = disposableCreate(function () { self.requestedCount = 0; }); return this.requestedDisposable } else { return disposableEmpty; } }, disposeCurrentRequest: function () { this.requestedDisposable.dispose(); this.requestedDisposable = disposableEmpty; }, dispose: function () { this.isDisposed = true; this.error = null; this.subject.dispose(); this.requestedDisposable.dispose(); } }); return ControlledSubject; }(Observable)); /** * Multicasts the source sequence notifications through an instantiated subject into all uses of the sequence within a selector function. Each * subscription to the resulting sequence causes a separate multicast invocation, exposing the sequence resulting from the selector function's * invocation. For specializations with fixed subject types, see Publish, PublishLast, and Replay. * * @example * 1 - res = source.multicast(observable); * 2 - res = source.multicast(function () { return new Subject(); }, function (x) { return x; }); * * @param {Function|Subject} subjectOrSubjectSelector * Factory function to create an intermediate subject through which the source sequence's elements will be multicast to the selector function. * Or: * Subject to push source elements into. * * @param {Function} [selector] Optional selector function which can use the multicasted source sequence subject to the policies enforced by the created subject. Specified only if <paramref name="subjectOrSubjectSelector" is a factory function. * @returns {Observable} An observable sequence that contains the elements of a sequence produced by multicasting the source sequence within a selector function. */ observableProto.multicast = function (subjectOrSubjectSelector, selector) { var source = this; return typeof subjectOrSubjectSelector === 'function' ? new AnonymousObservable(function (observer) { var connectable = source.multicast(subjectOrSubjectSelector()); return new CompositeDisposable(selector(connectable).subscribe(observer), connectable.connect()); }) : new ConnectableObservable(source, subjectOrSubjectSelector); }; /** * Returns an observable sequence that is the result of invoking the selector on a connectable observable sequence that shares a single subscription to the underlying sequence. * This operator is a specialization of Multicast using a regular Subject. * * @example * var resres = source.publish(); * var res = source.publish(function (x) { return x; }); * * @param {Function} [selector] Selector function which can use the multicasted source sequence as many times as needed, without causing multiple subscriptions to the source sequence. Subscribers to the given source will receive all notifications of the source from the time of the subscription on. * @returns {Observable} An observable sequence that contains the elements of a sequence produced by multicasting the source sequence within a selector function. */ observableProto.publish = function (selector) { return !selector ? this.multicast(new Subject()) : this.multicast(function () { return new Subject(); }, selector); }; /** * Returns an observable sequence that shares a single subscription to the underlying sequence. * This operator is a specialization of publish which creates a subscription when the number of observers goes from zero to one, then shares that subscription with all subsequent observers until the number of observers returns to zero, at which point the subscription is disposed. * * @example * var res = source.share(); * * @returns {Observable} An observable sequence that contains the elements of a sequence produced by multicasting the source sequence. */ observableProto.share = function () { return this.publish(null).refCount(); }; /** * Returns an observable sequence that is the result of invoking the selector on a connectable observable sequence that shares a single subscription to the underlying sequence containing only the last notification. * This operator is a specialization of Multicast using a AsyncSubject. * * @example * var res = source.publishLast(); * var res = source.publishLast(function (x) { return x; }); * * @param selector [Optional] Selector function which can use the multicasted source sequence as many times as needed, without causing multiple subscriptions to the source sequence. Subscribers to the given source will only receive the last notification of the source. * @returns {Observable} An observable sequence that contains the elements of a sequence produced by multicasting the source sequence within a selector function. */ observableProto.publishLast = function (selector) { return !selector ? this.multicast(new AsyncSubject()) : this.multicast(function () { return new AsyncSubject(); }, selector); }; /** * Returns an observable sequence that is the result of invoking the selector on a connectable observable sequence that shares a single subscription to the underlying sequence and starts with initialValue. * This operator is a specialization of Multicast using a BehaviorSubject. * * @example * var res = source.publishValue(42); * var res = source.publishValue(function (x) { return x.select(function (y) { return y * y; }) }, 42); * * @param {Function} [selector] Optional selector function which can use the multicasted source sequence as many times as needed, without causing multiple subscriptions to the source sequence. Subscribers to the given source will receive immediately receive the initial value, followed by all notifications of the source from the time of the subscription on. * @param {Mixed} initialValue Initial value received by observers upon subscription. * @returns {Observable} An observable sequence that contains the elements of a sequence produced by multicasting the source sequence within a selector function. */ observableProto.publishValue = function (initialValueOrSelector, initialValue) { return arguments.length === 2 ? this.multicast(function () { return new BehaviorSubject(initialValue); }, initialValueOrSelector) : this.multicast(new BehaviorSubject(initialValueOrSelector)); }; /** * Returns an observable sequence that shares a single subscription to the underlying sequence and starts with an initialValue. * This operator is a specialization of publishValue which creates a subscription when the number of observers goes from zero to one, then shares that subscription with all subsequent observers until the number of observers returns to zero, at which point the subscription is disposed. * * @example * var res = source.shareValue(42); * * @param {Mixed} initialValue Initial value received by observers upon subscription. * @returns {Observable} An observable sequence that contains the elements of a sequence produced by multicasting the source sequence. */ observableProto.shareValue = function (initialValue) { return this.publishValue(initialValue). refCount(); }; /** * Returns an observable sequence that is the result of invoking the selector on a connectable observable sequence that shares a single subscription to the underlying sequence replaying notifications subject to a maximum time length for the replay buffer. * This operator is a specialization of Multicast using a ReplaySubject. * * @example * var res = source.replay(null, 3); * var res = source.replay(null, 3, 500); * var res = source.replay(null, 3, 500, scheduler); * var res = source.replay(function (x) { return x.take(6).repeat(); }, 3, 500, scheduler); * * @param selector [Optional] Selector function which can use the multicasted source sequence as many times as needed, without causing multiple subscriptions to the source sequence. Subscribers to the given source will receive all the notifications of the source subject to the specified replay buffer trimming policy. * @param bufferSize [Optional] Maximum element count of the replay buffer. * @param window [Optional] Maximum time length of the replay buffer. * @param scheduler [Optional] Scheduler where connected observers within the selector function will be invoked on. * @returns {Observable} An observable sequence that contains the elements of a sequence produced by multicasting the source sequence within a selector function. */ observableProto.replay = function (selector, bufferSize, window, scheduler) { return !selector ? this.multicast(new ReplaySubject(bufferSize, window, scheduler)) : this.multicast(function () { return new ReplaySubject(bufferSize, window, scheduler); }, selector); }; /** * Returns an observable sequence that shares a single subscription to the underlying sequence replaying notifications subject to a maximum time length for the replay buffer. * This operator is a specialization of replay which creates a subscription when the number of observers goes from zero to one, then shares that subscription with all subsequent observers until the number of observers returns to zero, at which point the subscription is disposed. * * @example * var res = source.replayWhileObserved(3); * var res = source.replayWhileObserved(3, 500); * var res = source.replayWhileObserved(3, 500, scheduler); * * @param bufferSize [Optional] Maximum element count of the replay buffer. * @param window [Optional] Maximum time length of the replay buffer. * @param scheduler [Optional] Scheduler where connected observers within the selector function will be invoked on. * @returns {Observable} An observable sequence that contains the elements of a sequence produced by multicasting the source sequence. */ observableProto.replayWhileObserved = function (bufferSize, window, scheduler) { return this.replay(null, bufferSize, window, scheduler).refCount(); }; /** @private */ var InnerSubscription = function (subject, observer) { this.subject = subject; this.observer = observer; }; /** * @private * @memberOf InnerSubscription */ 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 a value that changes over time. * Observers can subscribe to the subject to receive the last (or initial) value and all subsequent notifications. */ var BehaviorSubject = Rx.BehaviorSubject = (function (_super) { function subscribe(observer) { checkDisposed.call(this); if (!this.isStopped) { this.observers.push(observer); observer.onNext(this.value); return new InnerSubscription(this, observer); } var ex = this.exception; if (ex) { observer.onError(ex); } else { observer.onCompleted(); } return disposableEmpty; } inherits(BehaviorSubject, _super); /** * @constructor * Initializes a new instance of the BehaviorSubject class which creates a subject that caches its last value and starts with the specified value. * @param {Mixed} value Initial value sent to observers when no other value has been received by the subject yet. */ function BehaviorSubject(value) { _super.call(this, subscribe); this.value = value, this.observers = [], this.isDisposed = false, this.isStopped = false, this.exception = null; } addProperties(BehaviorSubject.prototype, Observer, { /** * 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.call(this); if (!this.isStopped) { var os = this.observers.slice(0); this.isStopped = true; for (var i = 0, len = os.length; i < len; i++) { os[i].onCompleted(); } this.observers = []; } }, /** * Notifies all subscribed observers about the exception. * @param {Mixed} error The exception to send to all observers. */ onError: function (error) { checkDisposed.call(this); if (!this.isStopped) { var os = this.observers.slice(0); this.isStopped = true; this.exception = error; for (var i = 0, len = os.length; i < len; i++) { os[i].onError(error); } this.observers = []; } }, /** * 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.call(this); if (!this.isStopped) { this.value = value; var os = this.observers.slice(0); for (var i = 0, len = os.length; i < len; i++) { os[i].onNext(value); } } }, /** * Unsubscribe all observers and release resources. */ dispose: function () { this.isDisposed = true; this.observers = null; this.value = null; this.exception = null; } }); return BehaviorSubject; }(Observable)); /** * Represents an object that is both an observable sequence as well as an observer. * Each notification is broadcasted to all subscribed and future observers, subject to buffer trimming policies. */ var ReplaySubject = Rx.ReplaySubject = (function (_super) { function RemovableDisposable (subject, observer) { this.subject = subject; this.observer = observer; }; RemovableDisposable.prototype.dispose = function () { this.observer.dispose(); if (!this.subject.isDisposed) { var idx = this.subject.observers.indexOf(this.observer); this.subject.observers.splice(idx, 1); } }; function subscribe(observer) { var so = new ScheduledObserver(this.scheduler, observer), subscription = new RemovableDisposable(this, so); checkDisposed.call(this); this._trim(this.scheduler.now()); this.observers.push(so); var n = this.q.length; for (var i = 0, len = this.q.length; i < len; i++) { so.onNext(this.q[i].value); } if (this.hasError) { n++; so.onError(this.error); } else if (this.isStopped) { n++; so.onCompleted(); } so.ensureActive(n); return subscription; } inherits(ReplaySubject, _super); /** * Initializes a new instance of the ReplaySubject class with the specified buffer size, window size and scheduler. * @param {Number} [bufferSize] Maximum element count of the replay buffer. * @param {Number} [windowSize] Maximum time length of the replay buffer. * @param {Scheduler} [scheduler] Scheduler the observers are invoked on. */ function ReplaySubject(bufferSize, windowSize, scheduler) { this.bufferSize = bufferSize == null ? Number.MAX_VALUE : bufferSize; this.windowSize = windowSize == null ? Number.MAX_VALUE : windowSize; this.scheduler = scheduler || currentThreadScheduler; this.q = []; this.observers = []; this.isStopped = false; this.isDisposed = false; this.hasError = false; this.error = null; _super.call(this, subscribe); } addProperties(ReplaySubject.prototype, Observer, { /** * 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; }, /* @private */ _trim: function (now) { while (this.q.length > this.bufferSize) { this.q.shift(); } while (this.q.length > 0 && (now - this.q[0].interval) > this.windowSize) { this.q.shift(); } }, /** * 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) { var observer; checkDisposed.call(this); if (!this.isStopped) { var now = this.scheduler.now(); this.q.push({ interval: now, value: value }); this._trim(now); var o = this.observers.slice(0); for (var i = 0, len = o.length; i < len; i++) { observer = o[i]; observer.onNext(value); observer.ensureActive(); } } }, /** * Notifies all subscribed observers about the exception. * @param {Mixed} error The exception to send to all observers. */ onError: function (error) { var observer; checkDisposed.call(this); if (!this.isStopped) { this.isStopped = true; this.error = error; this.hasError = true; var now = this.scheduler.now(); this._trim(now); var o = this.observers.slice(0); for (var i = 0, len = o.length; i < len; i++) { observer = o[i]; observer.onError(error); observer.ensureActive(); } this.observers = []; } }, /** * Notifies all subscribed observers about the end of the sequence. */ onCompleted: function () { var observer; checkDisposed.call(this); if (!this.isStopped) { this.isStopped = true; var now = this.scheduler.now(); this._trim(now); var o = this.observers.slice(0); for (var i = 0, len = o.length; i < len; i++) { observer = o[i]; observer.onCompleted(); observer.ensureActive(); } this.observers = []; } }, /** * Unsubscribe all observers and release resources. */ dispose: function () { this.isDisposed = true; this.observers = null; } }); return ReplaySubject; }(Observable)); /** @private */ var ConnectableObservable = Rx.ConnectableObservable = (function (_super) { inherits(ConnectableObservable, _super); /** * @constructor * @private */ function ConnectableObservable(source, subject) { var state = { subject: subject, source: source.asObservable(), hasSubscription: false, subscription: null }; this.connect = function () { if (!state.hasSubscription) { state.hasSubscription = true; state.subscription = new CompositeDisposable(state.source.subscribe(state.subject), disposableCreate(function () { state.hasSubscription = false; })); } return state.subscription; }; function subscribe(observer) { return state.subject.subscribe(observer); } _super.call(this, subscribe); } /** * @private * @memberOf ConnectableObservable */ ConnectableObservable.prototype.connect = function () { return this.connect(); }; /** * @private * @memberOf ConnectableObservable */ ConnectableObservable.prototype.refCount = function () { var connectableSubscription = null, count = 0, source = this; return new AnonymousObservable(function (observer) { var shouldConnect, subscription; count++; shouldConnect = count === 1; subscription = source.subscribe(observer); if (shouldConnect) { connectableSubscription = source.connect(); } return disposableCreate(function () { subscription.dispose(); count--; if (count === 0) { connectableSubscription.dispose(); } }); }); }; return ConnectableObservable; }(Observable)); // Real Dictionary var primes = [1, 3, 7, 13, 31, 61, 127, 251, 509, 1021, 2039, 4093, 8191, 16381, 32749, 65521, 131071, 262139, 524287, 1048573, 2097143, 4194301, 8388593, 16777213, 33554393, 67108859, 134217689, 268435399, 536870909, 1073741789, 2147483647]; var noSuchkey = "no such key"; var duplicatekey = "duplicate key"; function isPrime(candidate) { if (candidate & 1 === 0) { return candidate === 2; } var num1 = Math.sqrt(candidate), num2 = 3; while (num2 <= num1) { if (candidate % num2 === 0) { return false; } num2 += 2; } return true; } function getPrime(min) { var index, num, candidate; for (index = 0; index < primes.length; ++index) { num = primes[index]; if (num >= min) { return num; } } candidate = min | 1; while (candidate < primes[primes.length - 1]) { if (isPrime(candidate)) { return candidate; } candidate += 2; } return min; } function stringHashFn(str) { var hash = 757602046; if (!str.length) { return hash; } for (var i = 0, len = str.length; i < len; i++) { var character = str.charCodeAt(i); hash = ((hash<<5)-hash)+character; hash = hash & hash; } return hash; } function numberHashFn(key) { var c2 = 0x27d4eb2d; key = (key ^ 61) ^ (key >>> 16); key = key + (key << 3); key = key ^ (key >>> 4); key = key * c2; key = key ^ (key >>> 15); return key; } var getHashCode = (function () { var uniqueIdCounter = 0; return function (obj) { if (obj == null) { throw new Error(noSuchkey); } // Check for built-ins before tacking on our own for any object if (typeof obj === 'string') { return stringHashFn(obj); } if (typeof obj === 'number') { return numberHashFn(obj); } if (typeof obj === 'boolean') { return obj === true ? 1 : 0; } if (obj instanceof Date) { return obj.getTime(); } if (obj.getHashCode) { return obj.getHashCode(); } var id = 17 * uniqueIdCounter++; obj.getHashCode = function () { return id; }; return id; }; } ()); function newEntry() { return { key: null, value: null, next: 0, hashCode: 0 }; } // Dictionary implementation var Dictionary = function (capacity, comparer) { if (capacity < 0) { throw new Error('out of range') } if (capacity > 0) { this._initialize(capacity); } this.comparer = comparer || defaultComparer; this.freeCount = 0; this.size = 0; this.freeList = -1; }; Dictionary.prototype._initialize = function (capacity) { var prime = getPrime(capacity), i; this.buckets = new Array(prime); this.entries = new Array(prime); for (i = 0; i < prime; i++) { this.buckets[i] = -1; this.entries[i] = newEntry(); } this.freeList = -1; }; Dictionary.prototype.count = function () { return this.size; }; Dictionary.prototype.add = function (key, value) { return this._insert(key, value, true); }; Dictionary.prototype._insert = function (key, value, add) { if (!this.buckets) { this._initialize(0); } var index3; var num = getHashCode(key) & 2147483647; var index1 = num % this.buckets.length; for (var index2 = this.buckets[index1]; index2 >= 0; index2 = this.entries[index2].next) { if (this.entries[index2].hashCode === num && this.comparer(this.entries[index2].key, key)) { if (add) { throw new Error(duplicatekey); } this.entries[index2].value = value; return; } } if (this.freeCount > 0) { index3 = this.freeList; this.freeList = this.entries[index3].next; --this.freeCount; } else { if (this.size === this.entries.length) { this._resize(); index1 = num % this.buckets.length; } index3 = this.size; ++this.size; } this.entries[index3].hashCode = num; this.entries[index3].next = this.buckets[index1]; this.entries[index3].key = key; this.entries[index3].value = value; this.buckets[index1] = index3; }; Dictionary.prototype._resize = function () { var prime = getPrime(this.size * 2), numArray = new Array(prime); for (index = 0; index < numArray.length; ++index) { numArray[index] = -1; } var entryArray = new Array(prime); for (index = 0; index < this.size; ++index) { entryArray[index] = this.entries[index]; } for (var index = this.size; index < prime; ++index) { entryArray[index] = newEntry(); } for (var index1 = 0; index1 < this.size; ++index1) { var index2 = entryArray[index1].hashCode % prime; entryArray[index1].next = numArray[index2]; numArray[index2] = index1; } this.buckets = numArray; this.entries = entryArray; }; Dictionary.prototype.remove = function (key) { if (this.buckets) { var num = getHashCode(key) & 2147483647; var index1 = num % this.buckets.length; var index2 = -1; for (var index3 = this.buckets[index1]; index3 >= 0; index3 = this.entries[index3].next) { if (this.entries[index3].hashCode === num && this.comparer(this.entries[index3].key, key)) { if (index2 < 0) { this.buckets[index1] = this.entries[index3].next; } else { this.entries[index2].next = this.entries[index3].next; } this.entries[index3].hashCode = -1; this.entries[index3].next = this.freeList; this.entries[index3].key = null; this.entries[index3].value = null; this.freeList = index3; ++this.freeCount; return true; } else { index2 = index3; } } } return false; }; Dictionary.prototype.clear = function () { var index, len; if (this.size <= 0) { return; } for (index = 0, len = this.buckets.length; index < len; ++index) { this.buckets[index] = -1; } for (index = 0; index < this.size; ++index) { this.entries[index] = newEntry(); } this.freeList = -1; this.size = 0; }; Dictionary.prototype._findEntry = function (key) { if (this.buckets) { var num = getHashCode(key) & 2147483647; for (var index = this.buckets[num % this.buckets.length]; index >= 0; index = this.entries[index].next) { if (this.entries[index].hashCode === num && this.comparer(this.entries[index].key, key)) { return index; } } } return -1; }; Dictionary.prototype.count = function () { return this.size - this.freeCount; }; Dictionary.prototype.tryGetValue = function (key) { var entry = this._findEntry(key); if (entry >= 0) { return this.entries[entry].value; } return undefined; }; Dictionary.prototype.getValues = function () { var index = 0, results = []; if (this.entries) { for (var index1 = 0; index1 < this.size; index1++) { if (this.entries[index1].hashCode >= 0) { results[index++] = this.entries[index1].value; } } } return results; }; Dictionary.prototype.get = function (key) { var entry = this._findEntry(key); if (entry >= 0) { return this.entries[entry].value; } throw new Error(noSuchkey); }; Dictionary.prototype.set = function (key, value) { this._insert(key, value, false); }; Dictionary.prototype.containskey = function (key) { return this._findEntry(key) >= 0; }; /** * Correlates the elements of two sequences based on overlapping durations. * * @param {Observable} right The right observable sequence to join elements for. * @param {Function} leftDurationSelector A function to select the duration (expressed as an observable sequence) of each element of the left observable sequence, used to determine overlap. * @param {Function} rightDurationSelector A function to select the duration (expressed as an observable sequence) of each element of the right observable sequence, used to determine overlap. * @param {Function} resultSelector A function invoked to compute a result element for any two overlapping elements of the left and right observable sequences. The parameters passed to the function correspond with the elements from the left and right source sequences for which overlap occurs. * @returns {Observable} An observable sequence that contains result elements computed from source elements that have an overlapping duration. */ observableProto.join = function (right, leftDurationSelector, rightDurationSelector, resultSelector) { var left = this; return new AnonymousObservable(function (observer) { var group = new CompositeDisposable(), leftDone = false, leftId = 0, leftMap = new Dictionary(), rightDone = false, rightId = 0, rightMap = new Dictionary(); group.add(left.subscribe(function (value) { var duration, expire, id = leftId++, md = new SingleAssignmentDisposable(), result, values; leftMap.add(id, value); group.add(md); expire = function () { if (leftMap.remove(id) && leftMap.count() === 0 && leftDone) { observer.onCompleted(); } return group.remove(md); }; try { duration = leftDurationSelector(value); } catch (e) { observer.onError(e); return; } md.setDisposable(duration.take(1).subscribe(noop, observer.onError.bind(observer), function () { expire(); })); values = rightMap.getValues(); for (var i = 0; i < values.length; i++) { try { result = resultSelector(value, values[i]); } catch (exception) { observer.onError(exception); return; } observer.onNext(result); } }, observer.onError.bind(observer), function () { leftDone = true; if (rightDone || leftMap.count() === 0) { observer.onCompleted(); } })); group.add(right.subscribe(function (value) { var duration, expire, id = rightId++, md = new SingleAssignmentDisposable(), result, values; rightMap.add(id, value); group.add(md); expire = function () { if (rightMap.remove(id) && rightMap.count() === 0 && rightDone) { observer.onCompleted(); } return group.remove(md); }; try { duration = rightDurationSelector(value); } catch (exception) { observer.onError(exception); return; } md.setDisposable(duration.take(1).subscribe(noop, observer.onError.bind(observer), function () { expire(); })); values = leftMap.getValues(); for (var i = 0; i < values.length; i++) { try { result = resultSelector(values[i], value); } catch (exception) { observer.onError(exception); return; } observer.onNext(result); } }, observer.onError.bind(observer), function () { rightDone = true; if (leftDone || rightMap.count() === 0) { observer.onCompleted(); } })); return group; }); }; /** * Correlates the elements of two sequences based on overlapping durations, and groups the results. * * @param {Observable} right The right observable sequence to join elements for. * @param {Function} leftDurationSelector A function to select the duration (expressed as an observable sequence) of each element of the left observable sequence, used to determine overlap. * @param {Function} rightDurationSelector A function to select the duration (expressed as an observable sequence) of each element of the right observable sequence, used to determine overlap. * @param {Function} resultSelector A function invoked to compute a result element for any element of the left sequence with overlapping elements from the right observable sequence. The first parameter passed to the function is an element of the left sequence. The second parameter passed to the function is an observable sequence with elements from the right sequence that overlap with the left sequence's element. * @returns {Observable} An observable sequence that contains result elements computed from source elements that have an overlapping duration. */ observableProto.groupJoin = function (right, leftDurationSelector, rightDurationSelector, resultSelector) { var left = this; return new AnonymousObservable(function (observer) { var nothing = function () {}; var group = new CompositeDisposable(); var r = new RefCountDisposable(group); var leftMap = new Dictionary(); var rightMap = new Dictionary(); var leftID = 0; var rightID = 0; group.add(left.subscribe( function (value) { var s = new Subject(); var id = leftID++; leftMap.add(id, s); var i, len, leftValues, rightValues; var result; try { result = resultSelector(value, addRef(s, r)); } catch (e) { leftValues = leftMap.getValues(); for (i = 0, len = leftValues.length; i < len; i++) { leftValues[i].onError(e); } observer.onError(e); return; } observer.onNext(result); rightValues = rightMap.getValues(); for (i = 0, len = rightValues.length; i < len; i++) { s.onNext(rightValues[i]); } var md = new SingleAssignmentDisposable(); group.add(md); var expire = function () { if (leftMap.remove(id)) { s.onCompleted(); } group.remove(md); }; var duration; try { duration = leftDurationSelector(value); } catch (e) { leftValues = leftMap.getValues(); for (i = 0, len = leftMap.length; i < len; i++) { leftValues[i].onError(e); } observer.onError(e); return; } md.setDisposable(duration.take(1).subscribe( nothing, function (e) { leftValues = leftMap.getValues(); for (i = 0, len = leftValues.length; i < len; i++) { leftValues[i].onError(e); } observer.onError(e); }, expire) ); }, function (e) { var leftValues = leftMap.getValues(); for (var i = 0, len = leftValues.length; i < len; i++) { leftValues[i].onError(e); } observer.onError(e); }, observer.onCompleted.bind(observer))); group.add(right.subscribe( function (value) { var leftValues, i, len; var id = rightID++; rightMap.add(id, value); var md = new SingleAssignmentDisposable(); group.add(md); var expire = function () { rightMap.remove(id); group.remove(md); }; var duration; try { duration = rightDurationSelector(value); } catch (e) { leftValues = leftMap.getValues(); for (i = 0, len = leftMap.length; i < len; i++) { leftValues[i].onError(e); } observer.onError(e); return; } md.setDisposable(duration.take(1).subscribe( nothing, function (e) { leftValues = leftMap.getValues(); for (i = 0, len = leftMap.length; i < len; i++) { leftValues[i].onError(e); } observer.onError(e); }, expire) ); leftValues = leftMap.getValues(); for (i = 0, len = leftValues.length; i < len; i++) { leftValues[i].onNext(value); } }, function (e) { var leftValues = leftMap.getValues(); for (var i = 0, len = leftValues.length; i < len; i++) { leftValues[i].onError(e); } observer.onError(e); })); return r; }); }; /** * Projects each element of an observable sequence into zero or more buffers. * * @param {Mixed} bufferOpeningsOrClosingSelector Observable sequence whose elements denote the creation of new windows, or, a function invoked to define the boundaries of the produced windows (a new window is started when the previous one is closed, resulting in non-overlapping windows). * @param {Function} [bufferClosingSelector] A function invoked to define the closing of each produced window. If a closing selector function is specified for the first parameter, this parameter is ignored. * @returns {Observable} An observable sequence of windows. */ observableProto.buffer = function (bufferOpeningsOrClosingSelector, bufferClosingSelector) { return this.window.apply(this, arguments).selectMany(function (x) { return x.toArray(); }); }; /** * Projects each element of an observable sequence into zero or more windows. * * @param {Mixed} windowOpeningsOrClosingSelector Observable sequence whose elements denote the creation of new windows, or, a function invoked to define the boundaries of the produced windows (a new window is started when the previous one is closed, resulting in non-overlapping windows). * @param {Function} [windowClosingSelector] A function invoked to define the closing of each produced window. If a closing selector function is specified for the first parameter, this parameter is ignored. * @returns {Observable} An observable sequence of windows. */ observableProto.window = function (windowOpeningsOrClosingSelector, windowClosingSelector) { if (arguments.length === 1 && typeof arguments[0] !== 'function') { return observableWindowWithBounaries.call(this, windowOpeningsOrClosingSelector); } return typeof windowOpeningsOrClosingSelector === 'function' ? observableWindowWithClosingSelector.call(this, windowOpeningsOrClosingSelector) : observableWindowWithOpenings.call(this, windowOpeningsOrClosingSelector, windowClosingSelector); }; function observableWindowWithOpenings(windowOpenings, windowClosingSelector) { return windowOpenings.groupJoin(this, windowClosingSelector, function () { return observableEmpty(); }, function (_, window) { return window; }); } function observableWindowWithBounaries(windowBoundaries) { var source = this; return new AnonymousObservable(function (observer) { var window = new Subject(), d = new CompositeDisposable(), r = new RefCountDisposable(d); observer.onNext(addRef(window, r)); d.add(source.subscribe(function (x) { window.onNext(x); }, function (err) { window.onError(err); observer.onError(err); }, function () { window.onCompleted(); observer.onCompleted(); })); d.add(windowBoundaries.subscribe(function (w) { window.onCompleted(); window = new Subject(); observer.onNext(addRef(window, r)); }, function (err) { window.onError(err); observer.onError(err); }, function () { window.onCompleted(); observer.onCompleted(); })); return r; }); } function observableWindowWithClosingSelector(windowClosingSelector) { var source = this; return new AnonymousObservable(function (observer) { var createWindowClose, m = new SerialDisposable(), d = new CompositeDisposable(m), r = new RefCountDisposable(d), window = new Subject(); observer.onNext(addRef(window, r)); d.add(source.subscribe(function (x) { window.onNext(x); }, function (ex) { window.onError(ex); observer.onError(ex); }, function () { window.onCompleted(); observer.onCompleted(); })); createWindowClose = function () { var m1, windowClose; try { windowClose = windowClosingSelector(); } catch (exception) { observer.onError(exception); return; } m1 = new SingleAssignmentDisposable(); m.setDisposable(m1); m1.setDisposable(windowClose.take(1).subscribe(noop, function (ex) { window.onError(ex); observer.onError(ex); }, function () { window.onCompleted(); window = new Subject(); observer.onNext(addRef(window, r)); createWindowClose(); })); }; createWindowClose(); return r; }); } /** * Returns a new observable that triggers on the second and subsequent triggerings of the input observable. * The Nth triggering of the input observable passes the arguments from the N-1th and Nth triggering as a pair. * The argument passed to the N-1th triggering is held in hidden internal state until the Nth triggering occurs. * @returns {Observable} An observable that triggers on successive pairs of observations from the input observable as an array. */ observableProto.pairwise = function () { var source = this; return new AnonymousObservable(function (observer) { var previous, hasPrevious = false; return source.subscribe( function (x) { if (hasPrevious) { observer.onNext([previous, x]); } else { hasPrevious = true; } previous = x; }, observer.onError.bind(observer), observer.onCompleted.bind(observer)); }); }; /** * Returns two observables which partition the observations of the source by the given function. * The first will trigger observations for those values for which the predicate returns true. * The second will trigger observations for those values where the predicate returns false. * The predicate is executed once for each subscribed observer. * Both also propagate all error observations arising from the source and each completes * when the source completes. * @param {Function} predicate * The function to determine which output Observable will trigger a particular observation. * @returns {Array} * An array of observables. The first triggers when the predicate returns true, * and the second triggers when the predicate returns false. */ observableProto.partition = function(predicate, thisArg) { var published = this.publish().refCount(); return [ published.filter(predicate, thisArg), published.filter(function (x, i, o) { return !predicate.call(thisArg, x, i, o); }) ]; }; function enumerableWhile(condition, source) { return new Enumerable(function () { return new Enumerator(function () { return condition() ? { done: false, value: source } : { done: true, value: undefined }; }); }); } /** * Returns an observable sequence that is the result of invoking the selector on the source sequence, without sharing subscriptions. * This operator allows for a fluent style of writing queries that use the same sequence multiple times. * * @param {Function} selector Selector function which can use the source sequence as many times as needed, without sharing subscriptions to the source sequence. * @returns {Observable} An observable sequence that contains the elements of a sequence produced by multicasting the source sequence within a selector function. */ observableProto.letBind = observableProto['let'] = function (func) { return func(this); }; /** * Determines whether an observable collection contains values. There is an alias for this method called 'ifThen' for browsers <IE9 * * @example * 1 - res = Rx.Observable.if(condition, obs1); * 2 - res = Rx.Observable.if(condition, obs1, obs2); * 3 - res = Rx.Observable.if(condition, obs1, scheduler); * @param {Function} condition The condition which determines if the thenSource or elseSource will be run. * @param {Observable} thenSource The observable sequence or Promise that will be run if the condition function returns true. * @param {Observable} [elseSource] The observable sequence or Promise that will be run if the condition function returns false. If this is not provided, it defaults to Rx.Observabe.Empty with the specified scheduler. * @returns {Observable} An observable sequence which is either the thenSource or elseSource. */ Observable['if'] = Observable.ifThen = function (condition, thenSource, elseSourceOrScheduler) { return observableDefer(function () { elseSourceOrScheduler || (elseSourceOrScheduler = observableEmpty()); isPromise(thenSource) && (thenSource = observableFromPromise(thenSource)); isPromise(elseSourceOrScheduler) && (elseSourceOrScheduler = observableFromPromise(elseSourceOrScheduler)); // Assume a scheduler for empty only typeof elseSourceOrScheduler.now === 'function' && (elseSourceOrScheduler = observableEmpty(elseSourceOrScheduler)); return condition() ? thenSource : elseSourceOrScheduler; }); }; /** * Concatenates the observable sequences obtained by running the specified result selector for each element in source. * There is an alias for this method called 'forIn' for browsers <IE9 * @param {Array} sources An array of values to turn into an observable sequence. * @param {Function} resultSelector A function to apply to each item in the sources array to turn it into an observable sequence. * @returns {Observable} An observable sequence from the concatenated observable sequences. */ Observable['for'] = Observable.forIn = function (sources, resultSelector) { return enumerableFor(sources, resultSelector).concat(); }; /** * Repeats source as long as condition holds emulating a while loop. * There is an alias for this method called 'whileDo' for browsers <IE9 * * @param {Function} condition The condition which determines if the source will be repeated. * @param {Observable} source The observable sequence that will be run if the condition function returns true. * @returns {Observable} An observable sequence which is repeated as long as the condition holds. */ var observableWhileDo = Observable['while'] = Observable.whileDo = function (condition, source) { isPromise(source) && (source = observableFromPromise(source)); return enumerableWhile(condition, source).concat(); }; /** * Repeats source as long as condition holds emulating a do while loop. * * @param {Function} condition The condition which determines if the source will be repeated. * @param {Observable} source The observable sequence that will be run if the condition function returns true. * @returns {Observable} An observable sequence which is repeated as long as the condition holds. */ observableProto.doWhile = function (condition) { return observableConcat([this, observableWhileDo(condition, this)]); }; /** * Uses selector to determine which source in sources to use. * There is an alias 'switchCase' for browsers <IE9. * * @example * 1 - res = Rx.Observable.case(selector, { '1': obs1, '2': obs2 }); * 1 - res = Rx.Observable.case(selector, { '1': obs1, '2': obs2 }, obs0); * 1 - res = Rx.Observable.case(selector, { '1': obs1, '2': obs2 }, scheduler); * * @param {Function} selector The function which extracts the value for to test in a case statement. * @param {Array} sources A object which has keys which correspond to the case statement labels. * @param {Observable} [elseSource] The observable sequence or Promise that will be run if the sources are not matched. If this is not provided, it defaults to Rx.Observabe.empty with the specified scheduler. * * @returns {Observable} An observable sequence which is determined by a case statement. */ Observable['case'] = Observable.switchCase = function (selector, sources, defaultSourceOrScheduler) { return observableDefer(function () { defaultSourceOrScheduler || (defaultSourceOrScheduler = observableEmpty()); typeof defaultSourceOrScheduler.now === 'function' && (defaultSourceOrScheduler = observableEmpty(defaultSourceOrScheduler)); var result = sources[selector()]; isPromise(result) && (result = observableFromPromise(result)); return result || defaultSourceOrScheduler; }); }; /** * Expands an observable sequence by recursively invoking selector. * * @param {Function} selector Selector function to invoke for each produced element, resulting in another sequence to which the selector will be invoked recursively again. * @param {Scheduler} [scheduler] Scheduler on which to perform the expansion. If not provided, this defaults to the current thread scheduler. * @returns {Observable} An observable sequence containing all the elements produced by the recursive expansion. */ observableProto.expand = function (selector, scheduler) { scheduler || (scheduler = immediateScheduler); var source = this; return new AnonymousObservable(function (observer) { var q = [], m = new SerialDisposable(), d = new CompositeDisposable(m), activeCount = 0, isAcquired = false; var ensureActive = function () { var isOwner = false; if (q.length > 0) { isOwner = !isAcquired; isAcquired = true; } if (isOwner) { m.setDisposable(scheduler.scheduleRecursive(function (self) { var work; if (q.length > 0) { work = q.shift(); } else { isAcquired = false; return; } var m1 = new SingleAssignmentDisposable(); d.add(m1); m1.setDisposable(work.subscribe(function (x) { observer.onNext(x); var result = null; try { result = selector(x); } catch (e) { observer.onError(e); } q.push(result); activeCount++; ensureActive(); }, observer.onError.bind(observer), function () { d.remove(m1); activeCount--; if (activeCount === 0) { observer.onCompleted(); } })); self(); })); } }; q.push(source); activeCount++; ensureActive(); return d; }); }; /** * Runs all observable sequences in parallel and collect their last elements. * * @example * 1 - res = Rx.Observable.forkJoin([obs1, obs2]); * 1 - res = Rx.Observable.forkJoin(obs1, obs2, ...); * @returns {Observable} An observable sequence with an array collecting the last elements of all the input sequences. */ Observable.forkJoin = function () { var allSources = argsOrArray(arguments, 0); return new AnonymousObservable(function (subscriber) { var count = allSources.length; if (count === 0) { subscriber.onCompleted(); return disposableEmpty; } var group = new CompositeDisposable(), finished = false, hasResults = new Array(count), hasCompleted = new Array(count), results = new Array(count); for (var idx = 0; idx < count; idx++) { (function (i) { var source = allSources[i]; isPromise(source) && (source = observableFromPromise(source)); group.add( source.subscribe( function (value) { if (!finished) { hasResults[i] = true; results[i] = value; } }, function (e) { finished = true; subscriber.onError(e); group.dispose(); }, function () { if (!finished) { if (!hasResults[i]) { subscriber.onCompleted(); return; } hasCompleted[i] = true; for (var ix = 0; ix < count; ix++) { if (!hasCompleted[ix]) { return; } } finished = true; subscriber.onNext(results); subscriber.onCompleted(); } })); })(idx); } return group; }); }; /** * Runs two observable sequences in parallel and combines their last elemenets. * * @param {Observable} second Second observable sequence. * @param {Function} resultSelector Result selector function to invoke with the last elements of both sequences. * @returns {Observable} An observable sequence with the result of calling the selector function with the last elements of both input sequences. */ observableProto.forkJoin = function (second, resultSelector) { var first = this; return new AnonymousObservable(function (observer) { var leftStopped = false, rightStopped = false, hasLeft = false, hasRight = false, lastLeft, lastRight, leftSubscription = new SingleAssignmentDisposable(), rightSubscription = new SingleAssignmentDisposable(); isPromise(second) && (second = observableFromPromise(second)); leftSubscription.setDisposable( first.subscribe(function (left) { hasLeft = true; lastLeft = left; }, function (err) { rightSubscription.dispose(); observer.onError(err); }, function () { leftStopped = true; if (rightStopped) { if (!hasLeft) { observer.onCompleted(); } else if (!hasRight) { observer.onCompleted(); } else { var result; try { result = resultSelector(lastLeft, lastRight); } catch (e) { observer.onError(e); return; } observer.onNext(result); observer.onCompleted(); } } }) ); rightSubscription.setDisposable( second.subscribe(function (right) { hasRight = true; lastRight = right; }, function (err) { leftSubscription.dispose(); observer.onError(err); }, function () { rightStopped = true; if (leftStopped) { if (!hasLeft) { observer.onCompleted(); } else if (!hasRight) { observer.onCompleted(); } else { var result; try { result = resultSelector(lastLeft, lastRight); } catch (e) { observer.onError(e); return; } observer.onNext(result); observer.onCompleted(); } } }) ); return new CompositeDisposable(leftSubscription, rightSubscription); }); }; /** * Comonadic bind operator. * @param {Function} selector A transform function to apply to each element. * @param {Object} scheduler Scheduler used to execute the operation. If not specified, defaults to the ImmediateScheduler. * @returns {Observable} An observable sequence which results from the comonadic bind operation. */ observableProto.manySelect = function (selector, scheduler) { scheduler || (scheduler = immediateScheduler); var source = this; return observableDefer(function () { var chain; return source .select( function (x) { var curr = new ChainObservable(x); if (chain) { chain.onNext(x); } chain = curr; return curr; }) .doAction( noop, function (e) { if (chain) { chain.onError(e); } }, function () { if (chain) { chain.onCompleted(); } }) .observeOn(scheduler) .select(function (x, i, o) { return selector(x, i, o); }); }); }; var ChainObservable = (function (_super) { function subscribe (observer) { var self = this, g = new CompositeDisposable(); g.add(currentThreadScheduler.schedule(function () { observer.onNext(self.head); g.add(self.tail.mergeObservable().subscribe(observer)); })); return g; } inherits(ChainObservable, _super); function ChainObservable(head) { _super.call(this, subscribe); this.head = head; this.tail = new AsyncSubject(); } addProperties(ChainObservable.prototype, Observer, { onCompleted: function () { this.onNext(Observable.empty()); }, onError: function (e) { this.onNext(Observable.throwException(e)); }, onNext: function (v) { this.tail.onNext(v); this.tail.onCompleted(); } }); return ChainObservable; }(Observable)); /** @private */ var Map = (function () { /** * @constructor * @private */ function Map() { this.keys = []; this.values = []; } /** * @private * @memberOf Map# */ Map.prototype['delete'] = function (key) { var i = this.keys.indexOf(key); if (i !== -1) { this.keys.splice(i, 1); this.values.splice(i, 1); } return i !== -1; }; /** * @private * @memberOf Map# */ Map.prototype.get = function (key, fallback) { var i = this.keys.indexOf(key); return i !== -1 ? this.values[i] : fallback; }; /** * @private * @memberOf Map# */ Map.prototype.set = function (key, value) { var i = this.keys.indexOf(key); if (i !== -1) { this.values[i] = value; } this.values[this.keys.push(key) - 1] = value; }; /** * @private * @memberOf Map# */ Map.prototype.size = function () { return this.keys.length; }; /** * @private * @memberOf Map# */ Map.prototype.has = function (key) { return this.keys.indexOf(key) !== -1; }; /** * @private * @memberOf Map# */ Map.prototype.getKeys = function () { return this.keys.slice(0); }; /** * @private * @memberOf Map# */ Map.prototype.getValues = function () { return this.values.slice(0); }; return Map; }()); /** * @constructor * Represents a join pattern over observable sequences. */ function Pattern(patterns) { this.patterns = patterns; } /** * Creates a pattern that matches the current plan matches and when the specified observable sequences has an available value. * * @param other Observable sequence to match in addition to the current pattern. * @return Pattern object that matches when all observable sequences in the pattern have an available value. */ Pattern.prototype.and = function (other) { var patterns = this.patterns.slice(0); patterns.push(other); return new Pattern(patterns); }; /** * Matches when all observable sequences in the pattern (specified using a chain of and operators) have an available value and projects the values. * * @param selector Selector that will be invoked with available values from the source sequences, in the same order of the sequences in the pattern. * @return Plan that produces the projected values, to be fed (with other plans) to the when operator. */ Pattern.prototype.then = function (selector) { return new Plan(this, selector); }; function Plan(expression, selector) { this.expression = expression; this.selector = selector; } Plan.prototype.activate = function (externalSubscriptions, observer, deactivate) { var self = this; var joinObservers = []; for (var i = 0, len = this.expression.patterns.length; i < len; i++) { joinObservers.push(planCreateObserver(externalSubscriptions, this.expression.patterns[i], observer.onError.bind(observer))); } var activePlan = new ActivePlan(joinObservers, function () { var result; try { result = self.selector.apply(self, arguments); } catch (exception) { observer.onError(exception); return; } observer.onNext(result); }, function () { for (var j = 0, jlen = joinObservers.length; j < jlen; j++) { joinObservers[j].removeActivePlan(activePlan); } deactivate(activePlan); }); for (i = 0, len = joinObservers.length; i < len; i++) { joinObservers[i].addActivePlan(activePlan); } return activePlan; }; function planCreateObserver(externalSubscriptions, observable, onError) { var entry = externalSubscriptions.get(observable); if (!entry) { var observer = new JoinObserver(observable, onError); externalSubscriptions.set(observable, observer); return observer; } return entry; } // Active Plan function ActivePlan(joinObserverArray, onNext, onCompleted) { var i, joinObserver; this.joinObserverArray = joinObserverArray; this.onNext = onNext; this.onCompleted = onCompleted; this.joinObservers = new Map(); for (i = 0; i < this.joinObserverArray.length; i++) { joinObserver = this.joinObserverArray[i]; this.joinObservers.set(joinObserver, joinObserver); } } ActivePlan.prototype.dequeue = function () { var values = this.joinObservers.getValues(); for (var i = 0, len = values.length; i < len; i++) { values[i].queue.shift(); } }; ActivePlan.prototype.match = function () { var firstValues, i, len, isCompleted, values, hasValues = true; for (i = 0, len = this.joinObserverArray.length; i < len; i++) { if (this.joinObserverArray[i].queue.length === 0) { hasValues = false; break; } } if (hasValues) { firstValues = []; isCompleted = false; for (i = 0, len = this.joinObserverArray.length; i < len; i++) { firstValues.push(this.joinObserverArray[i].queue[0]); if (this.joinObserverArray[i].queue[0].kind === 'C') { isCompleted = true; } } if (isCompleted) { this.onCompleted(); } else { this.dequeue(); values = []; for (i = 0; i < firstValues.length; i++) { values.push(firstValues[i].value); } this.onNext.apply(this, values); } } }; /** @private */ var JoinObserver = (function (_super) { inherits(JoinObserver, _super); /** * @constructor * @private */ function JoinObserver(source, onError) { _super.call(this); this.source = source; this.onError = onError; this.queue = []; this.activePlans = []; this.subscription = new SingleAssignmentDisposable(); this.isDisposed = false; } var JoinObserverPrototype = JoinObserver.prototype; /** * @memberOf JoinObserver# * @private */ JoinObserverPrototype.next = function (notification) { if (!this.isDisposed) { if (notification.kind === 'E') { this.onError(notification.exception); return; } this.queue.push(notification); var activePlans = this.activePlans.slice(0); for (var i = 0, len = activePlans.length; i < len; i++) { activePlans[i].match(); } } }; /** * @memberOf JoinObserver# * @private */ JoinObserverPrototype.error = noop; /** * @memberOf JoinObserver# * @private */ JoinObserverPrototype.completed = noop; /** * @memberOf JoinObserver# * @private */ JoinObserverPrototype.addActivePlan = function (activePlan) { this.activePlans.push(activePlan); }; /** * @memberOf JoinObserver# * @private */ JoinObserverPrototype.subscribe = function () { this.subscription.setDisposable(this.source.materialize().subscribe(this)); }; /** * @memberOf JoinObserver# * @private */ JoinObserverPrototype.removeActivePlan = function (activePlan) { var idx = this.activePlans.indexOf(activePlan); this.activePlans.splice(idx, 1); if (this.activePlans.length === 0) { this.dispose(); } }; /** * @memberOf JoinObserver# * @private */ JoinObserverPrototype.dispose = function () { _super.prototype.dispose.call(this); if (!this.isDisposed) { this.isDisposed = true; this.subscription.dispose(); } }; return JoinObserver; } (AbstractObserver)); /** * Creates a pattern that matches when both observable sequences have an available value. * * @param right Observable sequence to match with the current sequence. * @return {Pattern} Pattern object that matches when both observable sequences have an available value. */ observableProto.and = function (right) { return new Pattern([this, right]); }; /** * Matches when the observable sequence has an available value and projects the value. * * @param selector Selector that will be invoked for values in the source sequence. * @returns {Plan} Plan that produces the projected values, to be fed (with other plans) to the when operator. */ observableProto.then = function (selector) { return new Pattern([this]).then(selector); }; /** * Joins together the results from several patterns. * * @param plans A series of plans (specified as an Array of as a series of arguments) created by use of the Then operator on patterns. * @returns {Observable} Observable sequence with the results form matching several patterns. */ Observable.when = function () { var plans = argsOrArray(arguments, 0); return new AnonymousObservable(function (observer) { var activePlans = [], externalSubscriptions = new Map(), group, i, len, joinObserver, joinValues, outObserver; outObserver = observerCreate(observer.onNext.bind(observer), function (exception) { var values = externalSubscriptions.getValues(); for (var j = 0, jlen = values.length; j < jlen; j++) { values[j].onError(exception); } observer.onError(exception); }, observer.onCompleted.bind(observer)); try { for (i = 0, len = plans.length; i < len; i++) { activePlans.push(plans[i].activate(externalSubscriptions, outObserver, function (activePlan) { var idx = activePlans.indexOf(activePlan); activePlans.splice(idx, 1); if (activePlans.length === 0) { outObserver.onCompleted(); } })); } } catch (e) { observableThrow(e).subscribe(observer); } group = new CompositeDisposable(); joinValues = externalSubscriptions.getValues(); for (i = 0, len = joinValues.length; i < len; i++) { joinObserver = joinValues[i]; joinObserver.subscribe(); group.add(joinObserver); } return group; }); }; function observableTimerDate(dueTime, scheduler) { return new AnonymousObservable(function (observer) { return scheduler.scheduleWithAbsolute(dueTime, function () { observer.onNext(0); observer.onCompleted(); }); }); } function observableTimerDateAndPeriod(dueTime, period, scheduler) { var p = normalizeTime(period); return new AnonymousObservable(function (observer) { var count = 0, d = dueTime; return scheduler.scheduleRecursiveWithAbsolute(d, function (self) { var now; if (p > 0) { now = scheduler.now(); d = d + p; if (d <= now) { d = now + p; } } observer.onNext(count++); self(d); }); }); } function observableTimerTimeSpan(dueTime, scheduler) { var d = normalizeTime(dueTime); return new AnonymousObservable(function (observer) { return scheduler.scheduleWithRelative(d, function () { observer.onNext(0); observer.onCompleted(); }); }); } function observableTimerTimeSpanAndPeriod(dueTime, period, scheduler) { if (dueTime === period) { return new AnonymousObservable(function (observer) { return scheduler.schedulePeriodicWithState(0, period, function (count) { observer.onNext(count); return count + 1; }); }); } return observableDefer(function () { return observableTimerDateAndPeriod(scheduler.now() + dueTime, period, scheduler); }); } /** * Returns an observable sequence that produces a value after each period. * * @example * 1 - res = Rx.Observable.interval(1000); * 2 - res = Rx.Observable.interval(1000, Rx.Scheduler.timeout); * * @param {Number} period Period for producing the values in the resulting sequence (specified as an integer denoting milliseconds). * @param {Scheduler} [scheduler] Scheduler to run the timer on. If not specified, Rx.Scheduler.timeout is used. * @returns {Observable} An observable sequence that produces a value after each period. */ var observableinterval = Observable.interval = function (period, scheduler) { scheduler || (scheduler = timeoutScheduler); return observableTimerTimeSpanAndPeriod(period, period, scheduler); }; /** * Returns an observable sequence that produces a value after dueTime has elapsed and then after each period. * * @example * 1 - res = Rx.Observable.timer(new Date()); * 2 - res = Rx.Observable.timer(new Date(), 1000); * 3 - res = Rx.Observable.timer(new Date(), Rx.Scheduler.timeout); * 4 - res = Rx.Observable.timer(new Date(), 1000, Rx.Scheduler.timeout); * * 5 - res = Rx.Observable.timer(5000); * 6 - res = Rx.Observable.timer(5000, 1000); * 7 - res = Rx.Observable.timer(5000, Rx.Scheduler.timeout); * 8 - res = Rx.Observable.timer(5000, 1000, Rx.Scheduler.timeout); * * @param {Number} dueTime Absolute (specified as a Date object) or relative time (specified as an integer denoting milliseconds) at which to produce the first value. * @param {Mixed} [periodOrScheduler] Period to produce subsequent values (specified as an integer denoting milliseconds), or the scheduler to run the timer on. If not specified, the resulting timer is not recurring. * @param {Scheduler} [scheduler] Scheduler to run the timer on. If not specified, the timeout scheduler is used. * @returns {Observable} An observable sequence that produces a value after due time has elapsed and then each period. */ var observableTimer = Observable.timer = function (dueTime, periodOrScheduler, scheduler) { var period; scheduler || (scheduler = timeoutScheduler); if (periodOrScheduler !== undefined && typeof periodOrScheduler === 'number') { period = periodOrScheduler; } else if (periodOrScheduler !== undefined && typeof periodOrScheduler === 'object') { scheduler = periodOrScheduler; } if (dueTime instanceof Date && period === undefined) { return observableTimerDate(dueTime.getTime(), scheduler); } if (dueTime instanceof Date && period !== undefined) { period = periodOrScheduler; return observableTimerDateAndPeriod(dueTime.getTime(), period, scheduler); } if (period === undefined) { return observableTimerTimeSpan(dueTime, scheduler); } return observableTimerTimeSpanAndPeriod(dueTime, period, scheduler); }; function observableDelayTimeSpan(dueTime, scheduler) { var source = this; return new AnonymousObservable(function (observer) { var active = false, cancelable = new SerialDisposable(), exception = null, q = [], running = false, subscription; subscription = source.materialize().timestamp(scheduler).subscribe(function (notification) { var d, shouldRun; if (notification.value.kind === 'E') { q = []; q.push(notification); exception = notification.value.exception; shouldRun = !running; } else { q.push({ value: notification.value, timestamp: notification.timestamp + dueTime }); shouldRun = !active; active = true; } if (shouldRun) { if (exception !== null) { observer.onError(exception); } else { d = new SingleAssignmentDisposable(); cancelable.setDisposable(d); d.setDisposable(scheduler.scheduleRecursiveWithRelative(dueTime, function (self) { var e, recurseDueTime, result, shouldRecurse; if (exception !== null) { return; } running = true; do { result = null; if (q.length > 0 && q[0].timestamp - scheduler.now() <= 0) { result = q.shift().value; } if (result !== null) { result.accept(observer); } } while (result !== null); shouldRecurse = false; recurseDueTime = 0; if (q.length > 0) { shouldRecurse = true; recurseDueTime = Math.max(0, q[0].timestamp - scheduler.now()); } else { active = false; } e = exception; running = false; if (e !== null) { observer.onError(e); } else if (shouldRecurse) { self(recurseDueTime); } })); } } }); return new CompositeDisposable(subscription, cancelable); }); } function observableDelayDate(dueTime, scheduler) { var self = this; return observableDefer(function () { var timeSpan = dueTime - scheduler.now(); return observableDelayTimeSpan.call(self, timeSpan, scheduler); }); } /** * Time shifts the observable sequence by dueTime. The relative time intervals between the values are preserved. * * @example * 1 - res = Rx.Observable.delay(new Date()); * 2 - res = Rx.Observable.delay(new Date(), Rx.Scheduler.timeout); * * 3 - res = Rx.Observable.delay(5000); * 4 - res = Rx.Observable.delay(5000, 1000, Rx.Scheduler.timeout); * @memberOf Observable# * @param {Number} dueTime Absolute (specified as a Date object) or relative time (specified as an integer denoting milliseconds) by which to shift the observable sequence. * @param {Scheduler} [scheduler] Scheduler to run the delay timers on. If not specified, the timeout scheduler is used. * @returns {Observable} Time-shifted sequence. */ observableProto.delay = function (dueTime, scheduler) { scheduler || (scheduler = timeoutScheduler); return dueTime instanceof Date ? observableDelayDate.call(this, dueTime.getTime(), scheduler) : observableDelayTimeSpan.call(this, dueTime, scheduler); }; /** * Ignores values from an observable sequence which are followed by another value before dueTime. * * @example * 1 - res = source.throttle(5000); // 5 seconds * 2 - res = source.throttle(5000, scheduler); * * @param {Number} dueTime Duration of the throttle period for each value (specified as an integer denoting milliseconds). * @param {Scheduler} [scheduler] Scheduler to run the throttle timers on. If not specified, the timeout scheduler is used. * @returns {Observable} The throttled sequence. */ observableProto.throttle = function (dueTime, scheduler) { scheduler || (scheduler = timeoutScheduler); var source = this; return this.throttleWithSelector(function () { return observableTimer(dueTime, scheduler); }) }; /** * Projects each element of an observable sequence into zero or more windows which are produced based on timing information. * * @example * 1 - res = xs.windowWithTime(1000, scheduler); // non-overlapping segments of 1 second * 2 - res = xs.windowWithTime(1000, 500 , scheduler); // segments of 1 second with time shift 0.5 seconds * * @param {Number} timeSpan Length of each window (specified as an integer denoting milliseconds). * @param {Mixed} [timeShiftOrScheduler] Interval between creation of consecutive windows (specified as an integer denoting milliseconds), or an optional scheduler parameter. If not specified, the time shift corresponds to the timeSpan parameter, resulting in non-overlapping adjacent windows. * @param {Scheduler} [scheduler] Scheduler to run windowing timers on. If not specified, the timeout scheduler is used. * @returns {Observable} An observable sequence of windows. */ observableProto.windowWithTime = function (timeSpan, timeShiftOrScheduler, scheduler) { var source = this, timeShift; if (timeShiftOrScheduler === undefined) { timeShift = timeSpan; } if (scheduler === undefined) { scheduler = timeoutScheduler; } if (typeof timeShiftOrScheduler === 'number') { timeShift = timeShiftOrScheduler; } else if (typeof timeShiftOrScheduler === 'object') { timeShift = timeSpan; scheduler = timeShiftOrScheduler; } return new AnonymousObservable(function (observer) { var groupDisposable, nextShift = timeShift, nextSpan = timeSpan, q = [], refCountDisposable, timerD = new SerialDisposable(), totalTime = 0; groupDisposable = new CompositeDisposable(timerD), refCountDisposable = new RefCountDisposable(groupDisposable); function createTimer () { var m = new SingleAssignmentDisposable(), isSpan = false, isShift = false; timerD.setDisposable(m); if (nextSpan === nextShift) { isSpan = true; isShift = true; } else if (nextSpan < nextShift) { isSpan = true; } else { isShift = true; } var newTotalTime = isSpan ? nextSpan : nextShift, ts = newTotalTime - totalTime; totalTime = newTotalTime; if (isSpan) { nextSpan += timeShift; } if (isShift) { nextShift += timeShift; } m.setDisposable(scheduler.scheduleWithRelative(ts, function () { var s; if (isShift) { s = new Subject(); q.push(s); observer.onNext(addRef(s, refCountDisposable)); } if (isSpan) { s = q.shift(); s.onCompleted(); } createTimer(); })); }; q.push(new Subject()); observer.onNext(addRef(q[0], refCountDisposable)); createTimer(); groupDisposable.add(source.subscribe(function (x) { var i, s; for (i = 0; i < q.length; i++) { s = q[i]; s.onNext(x); } }, function (e) { var i, s; for (i = 0; i < q.length; i++) { s = q[i]; s.onError(e); } observer.onError(e); }, function () { var i, s; for (i = 0; i < q.length; i++) { s = q[i]; s.onCompleted(); } observer.onCompleted(); })); return refCountDisposable; }); }; /** * Projects each element of an observable sequence into a window that is completed when either it's full or a given amount of time has elapsed. * @example * 1 - res = source.windowWithTimeOrCount(5000, 50); // 5s or 50 items * 2 - res = source.windowWithTimeOrCount(5000, 50, scheduler); //5s or 50 items * * @memberOf Observable# * @param {Number} timeSpan Maximum time length of a window. * @param {Number} count Maximum element count of a window. * @param {Scheduler} [scheduler] Scheduler to run windowing timers on. If not specified, the timeout scheduler is used. * @returns {Observable} An observable sequence of windows. */ observableProto.windowWithTimeOrCount = function (timeSpan, count, scheduler) { var source = this; scheduler || (scheduler = timeoutScheduler); return new AnonymousObservable(function (observer) { var createTimer, groupDisposable, n = 0, refCountDisposable, s, timerD = new SerialDisposable(), windowId = 0; groupDisposable = new CompositeDisposable(timerD); refCountDisposable = new RefCountDisposable(groupDisposable); createTimer = function (id) { var m = new SingleAssignmentDisposable(); timerD.setDisposable(m); m.setDisposable(scheduler.scheduleWithRelative(timeSpan, function () { var newId; if (id !== windowId) { return; } n = 0; newId = ++windowId; s.onCompleted(); s = new Subject(); observer.onNext(addRef(s, refCountDisposable)); createTimer(newId); })); }; s = new Subject(); observer.onNext(addRef(s, refCountDisposable)); createTimer(0); groupDisposable.add(source.subscribe(function (x) { var newId = 0, newWindow = false; s.onNext(x); n++; if (n === count) { newWindow = true; n = 0; newId = ++windowId; s.onCompleted(); s = new Subject(); observer.onNext(addRef(s, refCountDisposable)); } if (newWindow) { createTimer(newId); } }, function (e) { s.onError(e); observer.onError(e); }, function () { s.onCompleted(); observer.onCompleted(); })); return refCountDisposable; }); }; /** * Projects each element of an observable sequence into zero or more buffers which are produced based on timing information. * * @example * 1 - res = xs.bufferWithTime(1000, scheduler); // non-overlapping segments of 1 second * 2 - res = xs.bufferWithTime(1000, 500, scheduler; // segments of 1 second with time shift 0.5 seconds * * @param {Number} timeSpan Length of each buffer (specified as an integer denoting milliseconds). * @param {Mixed} [timeShiftOrScheduler] Interval between creation of consecutive buffers (specified as an integer denoting milliseconds), or an optional scheduler parameter. If not specified, the time shift corresponds to the timeSpan parameter, resulting in non-overlapping adjacent buffers. * @param {Scheduler} [scheduler] Scheduler to run buffer timers on. If not specified, the timeout scheduler is used. * @returns {Observable} An observable sequence of buffers. */ observableProto.bufferWithTime = function (timeSpan, timeShiftOrScheduler, scheduler) { return this.windowWithTime.apply(this, arguments).selectMany(function (x) { return x.toArray(); }); }; /** * Projects each element of an observable sequence into a buffer that is completed when either it's full or a given amount of time has elapsed. * * @example * 1 - res = source.bufferWithTimeOrCount(5000, 50); // 5s or 50 items in an array * 2 - res = source.bufferWithTimeOrCount(5000, 50, scheduler); // 5s or 50 items in an array * * @param {Number} timeSpan Maximum time length of a buffer. * @param {Number} count Maximum element count of a buffer. * @param {Scheduler} [scheduler] Scheduler to run bufferin timers on. If not specified, the timeout scheduler is used. * @returns {Observable} An observable sequence of buffers. */ observableProto.bufferWithTimeOrCount = function (timeSpan, count, scheduler) { return this.windowWithTimeOrCount(timeSpan, count, scheduler).selectMany(function (x) { return x.toArray(); }); }; /** * Records the time interval between consecutive values in an observable sequence. * * @example * 1 - res = source.timeInterval(); * 2 - res = source.timeInterval(Rx.Scheduler.timeout); * * @param [scheduler] Scheduler used to compute time intervals. If not specified, the timeout scheduler is used. * @returns {Observable} An observable sequence with time interval information on values. */ observableProto.timeInterval = function (scheduler) { var source = this; scheduler || (scheduler = timeoutScheduler); return observableDefer(function () { var last = scheduler.now(); return source.select(function (x) { var now = scheduler.now(), span = now - last; last = now; return { value: x, interval: span }; }); }); }; /** * Records the timestamp for each value in an observable sequence. * * @example * 1 - res = source.timestamp(); // produces { value: x, timestamp: ts } * 2 - res = source.timestamp(Rx.Scheduler.timeout); * * @param {Scheduler} [scheduler] Scheduler used to compute timestamps. If not specified, the timeout scheduler is used. * @returns {Observable} An observable sequence with timestamp information on values. */ observableProto.timestamp = function (scheduler) { scheduler || (scheduler = timeoutScheduler); return this.select(function (x) { return { value: x, timestamp: scheduler.now() }; }); }; function sampleObservable(source, sampler) { return new AnonymousObservable(function (observer) { var atEnd, value, hasValue; function sampleSubscribe() { if (hasValue) { hasValue = false; observer.onNext(value); } if (atEnd) { observer.onCompleted(); } } return new CompositeDisposable( source.subscribe(function (newValue) { hasValue = true; value = newValue; }, observer.onError.bind(observer), function () { atEnd = true; }), sampler.subscribe(sampleSubscribe, observer.onError.bind(observer), sampleSubscribe) ); }); } /** * Samples the observable sequence at each interval. * * @example * 1 - res = source.sample(sampleObservable); // Sampler tick sequence * 2 - res = source.sample(5000); // 5 seconds * 2 - res = source.sample(5000, Rx.Scheduler.timeout); // 5 seconds * * @param {Mixed} intervalOrSampler Interval at which to sample (specified as an integer denoting milliseconds) or Sampler Observable. * @param {Scheduler} [scheduler] Scheduler to run the sampling timer on. If not specified, the timeout scheduler is used. * @returns {Observable} Sampled observable sequence. */ observableProto.sample = function (intervalOrSampler, scheduler) { scheduler || (scheduler = timeoutScheduler); if (typeof intervalOrSampler === 'number') { return sampleObservable(this, observableinterval(intervalOrSampler, scheduler)); } return sampleObservable(this, intervalOrSampler); }; /** * Returns the source observable sequence or the other observable sequence if dueTime elapses. * * @example * 1 - res = source.timeout(new Date()); // As a date * 2 - res = source.timeout(5000); // 5 seconds * 3 - res = source.timeout(new Date(), Rx.Observable.returnValue(42)); // As a date and timeout observable * 4 - res = source.timeout(5000, Rx.Observable.returnValue(42)); // 5 seconds and timeout observable * 5 - res = source.timeout(new Date(), Rx.Observable.returnValue(42), Rx.Scheduler.timeout); // As a date and timeout observable * 6 - res = source.timeout(5000, Rx.Observable.returnValue(42), Rx.Scheduler.timeout); // 5 seconds and timeout observable * * @param {Number} dueTime Absolute (specified as a Date object) or relative time (specified as an integer denoting milliseconds) when a timeout occurs. * @param {Observable} [other] Sequence to return in case of a timeout. If not specified, a timeout error throwing sequence will be used. * @param {Scheduler} [scheduler] Scheduler to run the timeout timers on. If not specified, the timeout scheduler is used. * @returns {Observable} The source sequence switching to the other sequence in case of a timeout. */ observableProto.timeout = function (dueTime, other, scheduler) { other || (other = observableThrow(new Error('Timeout'))); scheduler || (scheduler = timeoutScheduler); var source = this, schedulerMethod = dueTime instanceof Date ? 'scheduleWithAbsolute' : 'scheduleWithRelative'; return new AnonymousObservable(function (observer) { var id = 0, original = new SingleAssignmentDisposable(), subscription = new SerialDisposable(), switched = false, timer = new SerialDisposable(); subscription.setDisposable(original); var createTimer = function () { var myId = id; timer.setDisposable(scheduler[schedulerMethod](dueTime, function () { if (id === myId) { isPromise(other) && (other = observableFromPromise(other)); subscription.setDisposable(other.subscribe(observer)); } })); }; createTimer(); original.setDisposable(source.subscribe(function (x) { if (!switched) { id++; observer.onNext(x); createTimer(); } }, function (e) { if (!switched) { id++; observer.onError(e); } }, function () { if (!switched) { id++; observer.onCompleted(); } })); return new CompositeDisposable(subscription, timer); }); }; /** * Generates an observable sequence by iterating a state from an initial state until the condition fails. * * @example * res = source.generateWithAbsoluteTime(0, * function (x) { return return true; }, * function (x) { return x + 1; }, * function (x) { return x; }, * function (x) { return new Date(); } * }); * * @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 {Function} timeSelector Time selector function to control the speed of values being produced each iteration, returning Date values. * @param {Scheduler} [scheduler] Scheduler on which to run the generator loop. If not specified, the timeout scheduler is used. * @returns {Observable} The generated sequence. */ Observable.generateWithAbsoluteTime = function (initialState, condition, iterate, resultSelector, timeSelector, scheduler) { scheduler || (scheduler = timeoutScheduler); return new AnonymousObservable(function (observer) { var first = true, hasResult = false, result, state = initialState, time; return scheduler.scheduleRecursiveWithAbsolute(scheduler.now(), function (self) { if (hasResult) { observer.onNext(result); } try { if (first) { first = false; } else { state = iterate(state); } hasResult = condition(state); if (hasResult) { result = resultSelector(state); time = timeSelector(state); } } catch (e) { observer.onError(e); return; } if (hasResult) { self(time); } else { observer.onCompleted(); } }); }); }; /** * Generates an observable sequence by iterating a state from an initial state until the condition fails. * * @example * res = source.generateWithRelativeTime(0, * function (x) { return return true; }, * function (x) { return x + 1; }, * function (x) { return x; }, * function (x) { return 500; } * ); * * @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 {Function} timeSelector Time selector function to control the speed of values being produced each iteration, returning integer values denoting milliseconds. * @param {Scheduler} [scheduler] Scheduler on which to run the generator loop. If not specified, the timeout scheduler is used. * @returns {Observable} The generated sequence. */ Observable.generateWithRelativeTime = function (initialState, condition, iterate, resultSelector, timeSelector, scheduler) { scheduler || (scheduler = timeoutScheduler); return new AnonymousObservable(function (observer) { var first = true, hasResult = false, result, state = initialState, time; return scheduler.scheduleRecursiveWithRelative(0, function (self) { if (hasResult) { observer.onNext(result); } try { if (first) { first = false; } else { state = iterate(state); } hasResult = condition(state); if (hasResult) { result = resultSelector(state); time = timeSelector(state); } } catch (e) { observer.onError(e); return; } if (hasResult) { self(time); } else { observer.onCompleted(); } }); }); }; /** * Time shifts the observable sequence by delaying the subscription. * * @example * 1 - res = source.delaySubscription(5000); // 5s * 2 - res = source.delaySubscription(5000, Rx.Scheduler.timeout); // 5 seconds * * @param {Number} dueTime Absolute or relative time to perform the subscription at. * @param {Scheduler} [scheduler] Scheduler to run the subscription delay timer on. If not specified, the timeout scheduler is used. * @returns {Observable} Time-shifted sequence. */ observableProto.delaySubscription = function (dueTime, scheduler) { scheduler || (scheduler = timeoutScheduler); return this.delayWithSelector(observableTimer(dueTime, scheduler), function () { return observableEmpty(); }); }; /** * Time shifts the observable sequence based on a subscription delay and a delay selector function for each element. * * @example * 1 - res = source.delayWithSelector(function (x) { return Rx.Scheduler.timer(5000); }); // with selector only * 1 - res = source.delayWithSelector(Rx.Observable.timer(2000), function (x) { return Rx.Observable.timer(x); }); // with delay and selector * * @param {Observable} [subscriptionDelay] Sequence indicating the delay for the subscription to the source. * @param {Function} delayDurationSelector Selector function to retrieve a sequence indicating the delay for each given element. * @returns {Observable} Time-shifted sequence. */ observableProto.delayWithSelector = function (subscriptionDelay, delayDurationSelector) { var source = this, subDelay, selector; if (typeof subscriptionDelay === 'function') { selector = subscriptionDelay; } else { subDelay = subscriptionDelay; selector = delayDurationSelector; } return new AnonymousObservable(function (observer) { var delays = new CompositeDisposable(), atEnd = false, done = function () { if (atEnd && delays.length === 0) { observer.onCompleted(); } }, subscription = new SerialDisposable(), start = function () { subscription.setDisposable(source.subscribe(function (x) { var delay; try { delay = selector(x); } catch (error) { observer.onError(error); return; } var d = new SingleAssignmentDisposable(); delays.add(d); d.setDisposable(delay.subscribe(function () { observer.onNext(x); delays.remove(d); done(); }, observer.onError.bind(observer), function () { observer.onNext(x); delays.remove(d); done(); })); }, observer.onError.bind(observer), function () { atEnd = true; subscription.dispose(); done(); })); }; if (!subDelay) { start(); } else { subscription.setDisposable(subDelay.subscribe(function () { start(); }, observer.onError.bind(observer), function () { start(); })); } return new CompositeDisposable(subscription, delays); }); }; /** * Returns the source observable sequence, switching to the other observable sequence if a timeout is signaled. * * @example * 1 - res = source.timeoutWithSelector(Rx.Observable.timer(500)); * 2 - res = source.timeoutWithSelector(Rx.Observable.timer(500), function (x) { return Rx.Observable.timer(200); }); * 3 - res = source.timeoutWithSelector(Rx.Observable.timer(500), function (x) { return Rx.Observable.timer(200); }, Rx.Observable.returnValue(42)); * * @param {Observable} [firstTimeout] Observable sequence that represents the timeout for the first element. If not provided, this defaults to Observable.never(). * @param {Function} [timeoutDurationSelector] Selector to retrieve an observable sequence that represents the timeout between the current element and the next element. * @param {Observable} [other] Sequence to return in case of a timeout. If not provided, this is set to Observable.throwException(). * @returns {Observable} The source sequence switching to the other sequence in case of a timeout. */ observableProto.timeoutWithSelector = function (firstTimeout, timeoutdurationSelector, other) { if (arguments.length === 1) { timeoutdurationSelector = firstTimeout; var firstTimeout = observableNever(); } other || (other = observableThrow(new Error('Timeout'))); var source = this; return new AnonymousObservable(function (observer) { var subscription = new SerialDisposable(), timer = new SerialDisposable(), original = new SingleAssignmentDisposable(); subscription.setDisposable(original); var id = 0, switched = false, setTimer = function (timeout) { var myId = id, timerWins = function () { return id === myId; }; var d = new SingleAssignmentDisposable(); timer.setDisposable(d); d.setDisposable(timeout.subscribe(function () { if (timerWins()) { subscription.setDisposable(other.subscribe(observer)); } d.dispose(); }, function (e) { if (timerWins()) { observer.onError(e); } }, function () { if (timerWins()) { subscription.setDisposable(other.subscribe(observer)); } })); }; setTimer(firstTimeout); var observerWins = function () { var res = !switched; if (res) { id++; } return res; }; original.setDisposable(source.subscribe(function (x) { if (observerWins()) { observer.onNext(x); var timeout; try { timeout = timeoutdurationSelector(x); } catch (e) { observer.onError(e); return; } setTimer(timeout); } }, function (e) { if (observerWins()) { observer.onError(e); } }, function () { if (observerWins()) { observer.onCompleted(); } })); return new CompositeDisposable(subscription, timer); }); }; /** * Ignores values from an observable sequence which are followed by another value within a computed throttle duration. * * @example * 1 - res = source.delayWithSelector(function (x) { return Rx.Scheduler.timer(x + x); }); * * @param {Function} throttleDurationSelector Selector function to retrieve a sequence indicating the throttle duration for each given element. * @returns {Observable} The throttled sequence. */ observableProto.throttleWithSelector = function (throttleDurationSelector) { var source = this; return new AnonymousObservable(function (observer) { var value, hasValue = false, cancelable = new SerialDisposable(), id = 0, subscription = source.subscribe(function (x) { var throttle; try { throttle = throttleDurationSelector(x); } catch (e) { observer.onError(e); return; } hasValue = true; value = x; id++; var currentid = id, d = new SingleAssignmentDisposable(); cancelable.setDisposable(d); d.setDisposable(throttle.subscribe(function () { if (hasValue && id === currentid) { observer.onNext(value); } hasValue = false; d.dispose(); }, observer.onError.bind(observer), function () { if (hasValue && id === currentid) { observer.onNext(value); } hasValue = false; d.dispose(); })); }, function (e) { cancelable.dispose(); observer.onError(e); hasValue = false; id++; }, function () { cancelable.dispose(); if (hasValue) { observer.onNext(value); } observer.onCompleted(); hasValue = false; id++; }); return new CompositeDisposable(subscription, cancelable); }); }; /** * Skips elements for the specified duration from the end of the observable source sequence, using the specified scheduler to run timers. * * 1 - res = source.skipLastWithTime(5000); * 2 - res = source.skipLastWithTime(5000, scheduler); * * @description * This operator accumulates a queue with a length enough to store elements received during the initial duration window. * As more elements are received, elements older than the specified duration are taken from the queue and produced on the * result sequence. This causes elements to be delayed with duration. * @param {Number} duration Duration for skipping elements from the end of the sequence. * @param {Scheduler} [scheduler] Scheduler to run the timer on. If not specified, defaults to Rx.Scheduler.timeout * @returns {Observable} An observable sequence with the elements skipped during the specified duration from the end of the source sequence. */ observableProto.skipLastWithTime = function (duration, scheduler) { scheduler || (scheduler = timeoutScheduler); var source = this; return new AnonymousObservable(function (observer) { var q = []; return source.subscribe(function (x) { var now = scheduler.now(); q.push({ interval: now, value: x }); while (q.length > 0 && now - q[0].interval >= duration) { observer.onNext(q.shift().value); } }, observer.onError.bind(observer), function () { var now = scheduler.now(); while (q.length > 0 && now - q[0].interval >= duration) { observer.onNext(q.shift().value); } observer.onCompleted(); }); }); }; /** * Returns elements within the specified duration from the end of the observable source sequence, using the specified schedulers to run timers and to drain the collected elements. * * @example * 1 - res = source.takeLastWithTime(5000, [optional timer scheduler], [optional loop scheduler]); * @description * This operator accumulates a queue with a length enough to store elements received during the initial duration window. * As more elements are received, elements older than the specified duration are taken from the queue and produced on the * result sequence. This causes elements to be delayed with duration. * @param {Number} duration Duration for taking elements from the end of the sequence. * @param {Scheduler} [timerScheduler] Scheduler to run the timer on. If not specified, defaults to Rx.Scheduler.timeout. * @param {Scheduler} [loopScheduler] Scheduler to drain the collected elements. If not specified, defaults to Rx.Scheduler.immediate. * @returns {Observable} An observable sequence with the elements taken during the specified duration from the end of the source sequence. */ observableProto.takeLastWithTime = function (duration, timerScheduler, loopScheduler) { return this.takeLastBufferWithTime(duration, timerScheduler).selectMany(function (xs) { return observableFromArray(xs, loopScheduler); }); }; /** * Returns an array with the elements within the specified duration from the end of the observable source sequence, using the specified scheduler to run timers. * * @example * 1 - res = source.takeLastBufferWithTime(5000, [optional scheduler]); * @description * This operator accumulates a queue with a length enough to store elements received during the initial duration window. * As more elements are received, elements older than the specified duration are taken from the queue and produced on the * result sequence. This causes elements to be delayed with duration. * @param {Number} duration Duration for taking elements from the end of the sequence. * @param {Scheduler} scheduler Scheduler to run the timer on. If not specified, defaults to Rx.Scheduler.timeout. * @returns {Observable} An observable sequence containing a single array with the elements taken during the specified duration from the end of the source sequence. */ observableProto.takeLastBufferWithTime = function (duration, scheduler) { var source = this; scheduler || (scheduler = timeoutScheduler); return new AnonymousObservable(function (observer) { var q = []; return source.subscribe(function (x) { var now = scheduler.now(); q.push({ interval: now, value: x }); while (q.length > 0 && now - q[0].interval >= duration) { q.shift(); } }, observer.onError.bind(observer), function () { var now = scheduler.now(), res = []; while (q.length > 0) { var next = q.shift(); if (now - next.interval <= duration) { res.push(next.value); } } observer.onNext(res); observer.onCompleted(); }); }); }; /** * Takes elements for the specified duration from the start of the observable source sequence, using the specified scheduler to run timers. * * @example * 1 - res = source.takeWithTime(5000, [optional scheduler]); * @description * This operator accumulates a queue with a length enough to store elements received during the initial duration window. * As more elements are received, elements older than the specified duration are taken from the queue and produced on the * result sequence. This causes elements to be delayed with duration. * @param {Number} duration Duration for taking elements from the start of the sequence. * @param {Scheduler} scheduler Scheduler to run the timer on. If not specified, defaults to Rx.Scheduler.timeout. * @returns {Observable} An observable sequence with the elements taken during the specified duration from the start of the source sequence. */ observableProto.takeWithTime = function (duration, scheduler) { var source = this; scheduler || (scheduler = timeoutScheduler); return new AnonymousObservable(function (observer) { var t = scheduler.scheduleWithRelative(duration, function () { observer.onCompleted(); }); return new CompositeDisposable(t, source.subscribe(observer)); }); }; /** * Skips elements for the specified duration from the start of the observable source sequence, using the specified scheduler to run timers. * * @example * 1 - res = source.skipWithTime(5000, [optional scheduler]); * * @description * Specifying a zero value for duration doesn't guarantee no elements will be dropped from the start of the source sequence. * This is a side-effect of the asynchrony introduced by the scheduler, where the action that causes callbacks from the source sequence to be forwarded * may not execute immediately, despite the zero due time. * * Errors produced by the source sequence are always forwarded to the result sequence, even if the error occurs before the duration. * @param {Number} duration Duration for skipping elements from the start of the sequence. * @param {Scheduler} scheduler Scheduler to run the timer on. If not specified, defaults to Rx.Scheduler.timeout. * @returns {Observable} An observable sequence with the elements skipped during the specified duration from the start of the source sequence. */ observableProto.skipWithTime = function (duration, scheduler) { var source = this; scheduler || (scheduler = timeoutScheduler); return new AnonymousObservable(function (observer) { var open = false, t = scheduler.scheduleWithRelative(duration, function () { open = true; }), d = source.subscribe(function (x) { if (open) { observer.onNext(x); } }, observer.onError.bind(observer), observer.onCompleted.bind(observer)); return new CompositeDisposable(t, d); }); }; /** * Skips elements from the observable source sequence until the specified start time, using the specified scheduler to run timers. * Errors produced by the source sequence are always forwarded to the result sequence, even if the error occurs before the start time. * * @examples * 1 - res = source.skipUntilWithTime(new Date(), [optional scheduler]); * 2 - res = source.skipUntilWithTime(5000, [optional scheduler]); * @param startTime Time to start taking elements from the source sequence. If this value is less than or equal to Date(), no elements will be skipped. * @param scheduler Scheduler to run the timer on. If not specified, defaults to Rx.Scheduler.timeout. * @returns {Observable} An observable sequence with the elements skipped until the specified start time. */ observableProto.skipUntilWithTime = function (startTime, scheduler) { scheduler || (scheduler = timeoutScheduler); var source = this, schedulerMethod = startTime instanceof Date ? 'scheduleWithAbsolute' : 'scheduleWithRelative'; return new AnonymousObservable(function (observer) { var open = false; return new CompositeDisposable( scheduler[schedulerMethod](startTime, function () { open = true; }), source.subscribe( function (x) { open && observer.onNext(x); }, observer.onError.bind(observer), observer.onCompleted.bind(observer))); }); }; /** * Takes elements for the specified duration until the specified end time, using the specified scheduler to run timers. * * @example * 1 - res = source.takeUntilWithTime(new Date(), [optional scheduler]); * 2 - res = source.takeUntilWithTime(5000, [optional scheduler]); * @param {Number | Date} endTime Time to stop taking elements from the source sequence. If this value is less than or equal to new Date(), the result stream will complete immediately. * @param {Scheduler} scheduler Scheduler to run the timer on. * @returns {Observable} An observable sequence with the elements taken until the specified end time. */ observableProto.takeUntilWithTime = function (endTime, scheduler) { scheduler || (scheduler = timeoutScheduler); var source = this, schedulerMethod = endTime instanceof Date ? 'scheduleWithAbsolute' : 'scheduleWithRelative'; return new AnonymousObservable(function (observer) { return new CompositeDisposable(scheduler[schedulerMethod](endTime, function () { observer.onCompleted(); }), source.subscribe(observer)); }); }; /** Provides a set of extension methods for virtual time scheduling. */ Rx.VirtualTimeScheduler = (function (_super) { function notImplemented() { throw new Error('Not implemented'); } function localNow() { return this.toDateTimeOffset(this.clock); } function scheduleNow(state, action) { return this.scheduleAbsoluteWithState(state, this.clock, action); } function scheduleRelative(state, dueTime, action) { return this.scheduleRelativeWithState(state, this.toRelative(dueTime), action); } function scheduleAbsolute(state, dueTime, action) { return this.scheduleRelativeWithState(state, this.toRelative(dueTime - this.now()), action); } function invokeAction(scheduler, action) { action(); return disposableEmpty; } inherits(VirtualTimeScheduler, _super); /** * Creates a new virtual time scheduler with the specified initial clock value and absolute time comparer. * * @constructor * @param {Number} initialClock Initial value for the clock. * @param {Function} comparer Comparer to determine causality of events based on absolute time. */ function VirtualTimeScheduler(initialClock, comparer) { this.clock = initialClock; this.comparer = comparer; this.isEnabled = false; this.queue = new PriorityQueue(1024); _super.call(this, localNow, scheduleNow, scheduleRelative, scheduleAbsolute); } var VirtualTimeSchedulerPrototype = VirtualTimeScheduler.prototype; /** * Adds a relative time value to an absolute time value. * @param {Number} absolute Absolute virtual time value. * @param {Number} relative Relative virtual time value to add. * @return {Number} Resulting absolute virtual time sum value. */ VirtualTimeSchedulerPrototype.add = notImplemented; /** * Converts an absolute time to a number * @param {Any} The absolute time. * @returns {Number} The absolute time in ms */ VirtualTimeSchedulerPrototype.toDateTimeOffset = notImplemented; /** * Converts the TimeSpan value to a relative virtual time value. * @param {Number} timeSpan TimeSpan value to convert. * @return {Number} Corresponding relative virtual time value. */ VirtualTimeSchedulerPrototype.toRelative = notImplemented; /** * Schedules a periodic piece of work by dynamically discovering the scheduler's capabilities. The periodic task will be emulated using recursive scheduling. * @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). */ VirtualTimeSchedulerPrototype.schedulePeriodicWithState = function (state, period, action) { var s = new SchedulePeriodicRecursive(this, state, period, action); return s.start(); }; /** * Schedules an action to be executed after dueTime. * @param {Mixed} state State passed to the action to be executed. * @param {Number} dueTime Relative time after which to execute the action. * @param {Function} action Action to be executed. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */ VirtualTimeSchedulerPrototype.scheduleRelativeWithState = function (state, dueTime, action) { var runAt = this.add(this.clock, dueTime); return this.scheduleAbsoluteWithState(state, runAt, action); }; /** * Schedules an action to be executed at dueTime. * @param {Number} dueTime Relative time after which to execute the action. * @param {Function} action Action to be executed. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */ VirtualTimeSchedulerPrototype.scheduleRelative = function (dueTime, action) { return this.scheduleRelativeWithState(action, dueTime, invokeAction); }; /** * Starts the virtual time scheduler. */ VirtualTimeSchedulerPrototype.start = function () { var next; if (!this.isEnabled) { this.isEnabled = true; do { next = this.getNext(); if (next !== null) { if (this.comparer(next.dueTime, this.clock) > 0) { this.clock = next.dueTime; } next.invoke(); } else { this.isEnabled = false; } } while (this.isEnabled); } }; /** * Stops the virtual time scheduler. */ VirtualTimeSchedulerPrototype.stop = function () { this.isEnabled = false; }; /** * Advances the scheduler's clock to the specified time, running all work till that point. * @param {Number} time Absolute time to advance the scheduler's clock to. */ VirtualTimeSchedulerPrototype.advanceTo = function (time) { var next; var dueToClock = this.comparer(this.clock, time); if (this.comparer(this.clock, time) > 0) { throw new Error(argumentOutOfRange); } if (dueToClock === 0) { return; } if (!this.isEnabled) { this.isEnabled = true; do { next = this.getNext(); if (next !== null && this.comparer(next.dueTime, time) <= 0) { if (this.comparer(next.dueTime, this.clock) > 0) { this.clock = next.dueTime; } next.invoke(); } else { this.isEnabled = false; } } while (this.isEnabled); this.clock = time; } }; /** * Advances the scheduler's clock by the specified relative time, running all work scheduled for that timespan. * @param {Number} time Relative time to advance the scheduler's clock by. */ VirtualTimeSchedulerPrototype.advanceBy = function (time) { var dt = this.add(this.clock, time); var dueToClock = this.comparer(this.clock, dt); if (dueToClock > 0) { throw new Error(argumentOutOfRange); } if (dueToClock === 0) { return; } this.advanceTo(dt); }; /** * Advances the scheduler's clock by the specified relative time. * @param {Number} time Relative time to advance the scheduler's clock by. */ VirtualTimeSchedulerPrototype.sleep = function (time) { var dt = this.add(this.clock, time); if (this.comparer(this.clock, dt) >= 0) { throw new Error(argumentOutOfRange); } this.clock = dt; }; /** * Gets the next scheduled item to be executed. * @returns {ScheduledItem} The next scheduled item. */ VirtualTimeSchedulerPrototype.getNext = function () { var next; while (this.queue.length > 0) { next = this.queue.peek(); if (next.isCancelled()) { this.queue.dequeue(); } else { return next; } } return null; }; /** * Schedules an action to be executed at dueTime. * @param {Scheduler} scheduler Scheduler to execute the action on. * @param {Number} dueTime Absolute time at which to execute the action. * @param {Function} action Action to be executed. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */ VirtualTimeSchedulerPrototype.scheduleAbsolute = function (dueTime, action) { return this.scheduleAbsoluteWithState(action, dueTime, invokeAction); }; /** * Schedules an action to be executed at dueTime. * @param {Mixed} state State passed to the action to be executed. * @param {Number} dueTime Absolute time at which to execute the action. * @param {Function} action Action to be executed. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */ VirtualTimeSchedulerPrototype.scheduleAbsoluteWithState = function (state, dueTime, action) { var self = this, run = function (scheduler, state1) { self.queue.remove(si); return action(scheduler, state1); }, si = new ScheduledItem(self, state, run, dueTime, self.comparer); self.queue.enqueue(si); return si.disposable; }; return VirtualTimeScheduler; }(Scheduler)); /** Provides a virtual time scheduler that uses Date for absolute time and number for relative time. */ Rx.HistoricalScheduler = (function (_super) { inherits(HistoricalScheduler, _super); /** * Creates a new historical scheduler with the specified initial clock value. * * @constructor * @param {Number} initialClock Initial value for the clock. * @param {Function} comparer Comparer to determine causality of events based on absolute time. */ function HistoricalScheduler(initialClock, comparer) { var clock = initialClock == null ? 0 : initialClock; var cmp = comparer || defaultSubComparer; _super.call(this, clock, cmp); } var HistoricalSchedulerProto = HistoricalScheduler.prototype; /** * Adds a relative time value to an absolute time value. * @param {Number} absolute Absolute virtual time value. * @param {Number} relative Relative virtual time value to add. * @return {Number} Resulting absolute virtual time sum value. */ HistoricalSchedulerProto.add = function (absolute, relative) { return absolute + relative; }; /** * @private */ HistoricalSchedulerProto.toDateTimeOffset = function (absolute) { return new Date(absolute).getTime(); }; /** * Converts the TimeSpan value to a relative virtual time value. * * @memberOf HistoricalScheduler * @param {Number} timeSpan TimeSpan value to convert. * @return {Number} Corresponding relative virtual time value. */ HistoricalSchedulerProto.toRelative = function (timeSpan) { return timeSpan; }; return HistoricalScheduler; }(Rx.VirtualTimeScheduler)); 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) { if (typeof subscriber === 'undefined') { subscriber = disposableEmpty; } else if (typeof subscriber === 'function') { subscriber = disposableCreate(subscriber); } return subscriber; } function AnonymousObservable(subscribe) { if (!(this instanceof AnonymousObservable)) { return new AnonymousObservable(subscribe); } function s(observer) { var autoDetachObserver = new AutoDetachObserver(observer); if (currentThreadScheduler.scheduleRequired()) { currentThreadScheduler.schedule(function () { try { autoDetachObserver.setDisposable(fixSubscriber(subscribe(autoDetachObserver))); } catch (e) { if (!autoDetachObserver.fail(e)) { throw e; } } }); } else { try { autoDetachObserver.setDisposable(fixSubscriber(subscribe(autoDetachObserver))); } catch (e) { if (!autoDetachObserver.fail(e)) { throw e; } } } return autoDetachObserver; } __super__.call(this, s); } return AnonymousObservable; }(Observable)); /** @private */ 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 noError = false; try { this.observer.onNext(value); noError = true; } catch (e) { throw e; } finally { if (!noError) { this.dispose(); } } }; AutoDetachObserverPrototype.error = function (exn) { try { this.observer.onError(exn); } catch (e) { throw e; } finally { this.dispose(); } }; AutoDetachObserverPrototype.completed = function () { try { this.observer.onCompleted(); } catch (e) { throw e; } finally { this.dispose(); } }; AutoDetachObserverPrototype.setDisposable = function (value) { this.m.setDisposable(value); }; AutoDetachObserverPrototype.getDisposable = function (value) { return this.m.getDisposable(); }; /* @private */ AutoDetachObserverPrototype.disposable = function (value) { return arguments.length ? this.getDisposable() : setDisposable(value); }; AutoDetachObserverPrototype.dispose = function () { _super.prototype.dispose.call(this); this.m.dispose(); }; return AutoDetachObserver; }(AbstractObserver)); /** @private */ var GroupedObservable = (function (_super) { inherits(GroupedObservable, _super); function subscribe(observer) { return this.underlyingObservable.subscribe(observer); } /** * @constructor * @private */ function GroupedObservable(key, underlyingObservable, mergedDisposable) { _super.call(this, subscribe); this.key = key; this.underlyingObservable = !mergedDisposable ? underlyingObservable : new AnonymousObservable(function (observer) { return new CompositeDisposable(mergedDisposable.getDisposable(), underlyingObservable.subscribe(observer)); }); } return GroupedObservable; }(Observable)); /** * 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.call(this); if (!this.isStopped) { this.observers.push(observer); return new InnerSubscription(this, observer); } if (this.exception) { observer.onError(this.exception); return disposableEmpty; } observer.onCompleted(); return disposableEmpty; } inherits(Subject, _super); /** * Creates a subject. * @constructor */ function Subject() { _super.call(this, subscribe); this.isDisposed = false, this.isStopped = false, this.observers = []; } addProperties(Subject.prototype, Observer, { /** * 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.call(this); if (!this.isStopped) { var os = this.observers.slice(0); this.isStopped = true; for (var i = 0, len = os.length; i < len; i++) { os[i].onCompleted(); } this.observers = []; } }, /** * Notifies all subscribed observers about the exception. * @param {Mixed} error The exception to send to all observers. */ onError: function (exception) { checkDisposed.call(this); if (!this.isStopped) { var os = this.observers.slice(0); this.isStopped = true; this.exception = exception; for (var i = 0, len = os.length; i < len; i++) { os[i].onError(exception); } this.observers = []; } }, /** * 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.call(this); if (!this.isStopped) { var os = this.observers.slice(0); for (var i = 0, 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.call(this); if (!this.isStopped) { this.observers.push(observer); return new InnerSubscription(this, observer); } var ex = this.exception, hv = this.hasValue, v = this.value; if (ex) { observer.onError(ex); } else if (hv) { observer.onNext(v); 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.value = null; this.hasValue = false; this.observers = []; this.exception = null; } 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.call(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 o, i, len; checkDisposed.call(this); if (!this.isStopped) { this.isStopped = true; var os = this.observers.slice(0), v = this.value, hv = this.hasValue; if (hv) { for (i = 0, len = os.length; i < len; i++) { o = os[i]; o.onNext(v); o.onCompleted(); } } else { for (i = 0, len = os.length; i < len; i++) { os[i].onCompleted(); } } this.observers = []; } }, /** * Notifies all subscribed observers about the exception. * @param {Mixed} error The exception to send to all observers. */ onError: function (exception) { checkDisposed.call(this); if (!this.isStopped) { var os = this.observers.slice(0); this.isStopped = true; this.exception = exception; for (var i = 0, len = os.length; i < len; i++) { os[i].onError(exception); } this.observers = []; } }, /** * 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.call(this); if (!this.isStopped) { 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)); /** @private */ var AnonymousSubject = (function (_super) { inherits(AnonymousSubject, _super); function subscribe(observer) { return this.observable.subscribe(observer); } /** * @private * @constructor */ function AnonymousSubject(observer, observable) { _super.call(this, subscribe); this.observer = observer; this.observable = observable; } addProperties(AnonymousSubject.prototype, Observer, { /** * @private * @memberOf AnonymousSubject# */ onCompleted: function () { this.observer.onCompleted(); }, /** * @private * @memberOf AnonymousSubject# */ onError: function (exception) { this.observer.onError(exception); }, /** * @private * @memberOf AnonymousSubject# */ 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; } }.call(this));
src/routes.js
mintlin/foreman
"use strict"; import React from 'react'; import { Route, IndexRoute } from 'react-router'; import App from './components/app'; import HomePage from './components/homePage'; import PlanPage from './components/planPage'; import Category from './components/category'; export default ( <Route path="/" component={App}> <IndexRoute component={HomePage} /> <Route path="/plan" component={PlanPage} /> <Route path="/category" component={Category} /> <Route path="/category/:id" component={Category} /> </Route> );
client/src/app/components/employer/Employer.js
lefnire/jobs
import React from 'react'; import { RaisedButton, Card, CardText, CardTitle, CardHeader, FlatButton, } from 'material-ui'; import Job from '../jobs/Job'; import _ from 'lodash'; import {_fetch, me, getTags, constants, filterOptions, _ga, IS_SMALL, PRICE} from '../../helpers'; const {TAG_TYPES} = constants; import load from 'load-script'; import Formsy from 'formsy-react'; import { FormsyText, FormsyCheckbox } from 'formsy-material-ui/lib'; import Select from 'react-select'; import StripeCheckout from 'react-stripe-checkout'; import Error from '../Error'; import { Modal, Button } from 'react-bootstrap'; let stripeRef, _open, timer; class ShareModal extends React.Component { constructor(){ super(); this.state = {open: false}; } open = (created, tags) => { window.addthis_share = { url: `https://jobpigapp.com/#/job/${created.id}`, //?uid=${created.user_id}`, title: tags[0] ? `Seeking ${tags[0].label} experts on Jobpig, a matchmaking Jobboard!` : `I'm posting a job on Jobpig, a candidate matchmaking tool!`, description: "Jobpig is a matchmaking job board. Whether looking for work or candidates, let Jobpig's algorithm find your perfect match!" }; this.setState({open: true}); this._setupAddthis(); }; close = () => { this._teardownAddthis(); this.setState({open: false}); }; _setupAddthis = () => { // Hacky callback for post-social-share. Started using AddThis callbacks (http://www.addthis.com/academy/addthis-javascript-events/), // but there's no solution for "after shared" or even "share window closed"; only "share window opened" (addthis.menu.share). // My solution uses http://stackoverflow.com/a/6341534/362790 & http://stackoverflow.com/a/31752385/362790 // Also, this breaks when addthis loaded from index.html script tag let shareWindow, service; _open = window.open; window.open = (url,name,params) => { clearInterval(timer); shareWindow = _open(url,name,params); // you can store names also timer = setInterval(() => { if (!(shareWindow && shareWindow.closed)) return; _fetch('user/share/post', {method: "POST"}).then(this.props.onShare); _ga.event('engagement', 'share', service); clearInterval(timer); }, 750); }; // Go to www.addthis.com/dashboard to customize your tools load('https://s7.addthis.com/js/300/addthis_widget.js#pubid=lefnire', (err, script) => { if (err) throw err; addthis.addEventListener('addthis.menu.share', evt => service = evt.data.service); }); }; _teardownAddthis = () => { clearInterval(timer); if (_open) window.open = _open; }; render() { let {open} = this.state; return ( <Modal show={open} onHide={this.close} bsSize="large" animation={!IS_SMALL}> <Modal.Header> <Modal.Title>Share socially and this post is free!</Modal.Title> <p>Click on a sharing button below. If you prefer to pay (${PRICE} for a 30 day post), click the "Pay with Card" button.</p> </Modal.Header> <Modal.Body className="share-modal"> <div> <div className="addthis_sharing_toolbox"></div> <Button bsSize="lg" bsStyle="primary" onClick={() => stripeRef.onClick()}>Pay with Card</Button> </div> </Modal.Body> </Modal> ); } } export default class Employer extends React.Component { constructor(){ super(); this.state = { jobs: [], open: false, canSubmit: false }; } componentWillMount() { global.jobpig.createJob = this; this.refresh(); } renderJobs = () => { return ( <div> {this.state.jobs.map((job, i) => ( <Job job={job} key={job.id} isEmployer={true} style={{marginBottom: 15}}/> ))} </div> ); }; renderPerks = () => { let {free_jobs} = this.state; return ( <Card style={{marginBottom: 15}}> <CardText> <RaisedButton label="Post Job" primary={true} onTouchTap={()=> global.jobpig.createJob.open()} /> </CardText> <CardText> <ul className="empty-text"> <li>View / contact candidates who match your listing, sorted by score</li> <li>Higher listing display priority for searchers</li> <li>Listing analytics</li> {free_jobs === -1 ? ( <li>${PRICE} for 30 days</li> ) : ( <li> <span style={{textDecoration: 'line-through'}}>(${PRICE} for 30 days)</span>&nbsp; { free_jobs? <b>{free_jobs} Free Post{free_jobs>1? 's': ''}!</b> : <span><b>Free post with social share</b></span> } </li> )} </ul> </CardText> </Card> ); }; renderSample = () => { let fakeJob = { title: 'Your Job Title', //description: `Post your job here. Users will find you if their preferences match your job's attributes; and vice versa. $50 for 30days, and your post will be promoted to matching users!`, //description: `Seeking Full-time JavaScript and Ruby on Rails developer to join our awesome San Francisco office!`, views: 25, likes: 10, dislikes: 5, tags: [ {text: "Your Company", type: TAG_TYPES.COMPANY}, {text: "San Francisco, CA", type: TAG_TYPES.LOCATION}, {text: "Full-time", type: TAG_TYPES.COMMITMENT}, {text: "Ruby on Rails"}, {text: "JavaScript"}, {text: "PostgreSQL"} ].map((t,key) => _.assign({key, type: TAG_TYPES.SKILL}, t)), users: [{ id: 1, fullname: 'Tyler Renelle', score: 10, tags: [{key: 'PostgreSQL'},{key: 'JavaScript'},{key: 'Full-time'}], pic: 'http://www.gravatar.com/avatar/ff2dd194f7faa850a0410f93735280b8', bio: `Full Stack JavaScript developer, 10 years in web & mobile. Focused on Node, React / React Native, and Angular / Ionic. Creator of HabitRPG, a startup begun on Kickstarter which now has 800k+ users. Built an enterprise PDF-creation service employed by 1.5k sites, and websites for clients such as Adidas, BigFix, and UCSF. Currently obsessed with machine learning - bonafide singularitarian here.` }] }; return ( <Job job={fakeJob} style={{opacity:0.5}} isEmployer={true} /> ); }; render() { let {jobs, open} = this.state; if (open) return this.renderForm(); return ( <div className="padded"> {this.renderPerks()} {_.isEmpty(jobs) && this.renderSample()} {this.renderJobs()} </div> ); } refresh = (force) => { Promise.all([ _fetch('jobs/mine', {method: "GET"}), me(force) ]).then(vals => { this.setState({ jobs: vals[0], free_jobs: vals[1].free_jobs, }); }); }; // --------------- Create Job renderForm() { return ( <div> <ShareModal ref="share" onShare={this.onShare} /> <Modal.Body> <StripeCheckout ref={c => {if (c) stripeRef = c}} token={this.onToken} stripeKey="<nconf:stripe:public>" amount={PRICE * 100}> <span>{/* StripeCheckout wants to render its own button unless we give it an element; but we don't want to render a button */}</span> </StripeCheckout> <Error error={this.state.error} /> <Formsy.Form ref="form" onValid={() => this.setState({canSubmit: true})} onInvalid={() => this.setState({canSubmit: false})} onValidSubmit={this.submit} > <FormsyText name='title' required hintText="Job title (required)" fullWidth={true} /> <FormsyText name='company' required hintText="Company (required)" fullWidth={true} /> <FormsyText name='url' hintText="External job URL (optional)" fullWidth={true} validations="isUrl" validationError="Enter a valid URL" /> <Select.Async placeholder="Skills (required)" multi={true} value={this.state.tags} loadOptions={() => getTags().then(options => ({options})) } onChange={this.changeTags} noResultsText="Start typing" filterOptions={filterOptions(true)} /> <p>Skills are how your job gets found. Enter as many of the most important skills required for this position as you can.</p> <FormsyCheckbox name='remote' label="Remote" /> <Select.Async placeholder="Location" value={this.state.location} loadOptions={() => getTags(TAG_TYPES.LOCATION).then(options => ({options})) } onChange={this.changeLocation} noResultsText="Start typing" filterOptions={filterOptions(true)} /> <FormsyText name='description' required hintText="Job description (required)" multiLine={true} rows={3} fullWidth={true} /> </Formsy.Form> </Modal.Body> <Modal.Footer style={{border: 'none'}}> <FlatButton label="Cancel" secondary={true} onTouchTap={this.close}/> <RaisedButton label="Submit" primary={true} disabled={false && !this.state.canSubmit} onTouchTap={() => this.refs.form.submit()} /> </Modal.Footer> </div> ) } changeLocation = location => { if (location.create) location.label = location.label.replace(/^Add /, ''); this.setState({location}); }; changeTags = tags => { let entered = _.last(tags); if (entered && entered.create) entered.label = entered.label.replace(/^Add /, ''); this.setState({tags}); }; open = () => { _ga.pageview('modal:create-job'); this.setState({open: true}); }; close = () => { _ga.pageview(); this.setState({open: false}); }; submit = body => { let {location, tags, free_jobs} = this.state; body.location = location && location.label; body.tags = tags && _.map(tags, 'label'); this.body = body; // save it away in case we need to come back after modal _fetch('jobs', {method:"POST", body: this.body}) .then(created => { // they had free jobs if (created.pending === false) return this.onPosted(); this.job_id = created.id; // They don't have free job; but can get one with a social share if (free_jobs === 0) { return this.refs.share.open(created, tags); } // Neither above stripeRef.onClick(); }) .catch(error => this.setState({error})); }; onToken = token => { // POST server/payments {token: token} _fetch('payments', {method: "POST", body:{token, job_id: this.job_id}}) .then(() => this.onPosted()).catch(error => this.setState({error})); }; onShare = () => { _fetch('jobs', {method: "POST", body: {job_id: this.job_id}}).then(this.onPosted); }; onPosted = () => { this.refresh(true); this.job_id = null; _ga.event('revenue','purchase'); this.refs.share.close(); // must come before this.close() _.defer(() => { this.close(); global.jobpig.alerts.alert('Payment success, posting job now.'); }); }; }
element-react-test/src/components/AlertTip.js
fengnovo/fengnovo-react-test
import React from 'react' import { Button, Notification } from 'element-react' class AlertTip extends React.Component { constructor(...args){ super(...args) } onClick() { MessageBox.msgbox({ title: '消息', message: '这是一段内容, 这是一段内容, 这是一段内容, 这是一段内容, 这是一段内容, 这是一段内容, 这是一段内容', showCancelButton: true }).then(action => { Message({ type: 'info', message: 'action: ' + action }); }) } render() { return <Button type="text" onClick={this.onClick.bind(this)}>点击打开 Message Box</Button> } } export default AlertTip
docs/src/app/components/pages/components/DropDownMenu/ExampleOpenImmediate.js
tan-jerene/material-ui
import React from 'react'; import DropDownMenu from 'material-ui/DropDownMenu'; import MenuItem from 'material-ui/MenuItem'; export default class DropDownMenuOpenImmediateExample extends React.Component { constructor(props) { super(props); this.state = {value: 2}; } handleChange = (event, index, value) => this.setState({value}); render() { return ( <DropDownMenu value={this.state.value} onChange={this.handleChange} openImmediately={true}> <MenuItem value={1} primaryText="Never" /> <MenuItem value={2} primaryText="Every Night" /> <MenuItem value={3} primaryText="Weeknights" /> <MenuItem value={4} primaryText="Weekends" /> <MenuItem value={5} primaryText="Weekly" /> </DropDownMenu> ); } }
Example/index.ios.js
FuYaoDe/react-native-app-intro
/** * Sample React Native App * https://github.com/facebook/react-native * @flow */ import React, { Component } from 'react'; import { AppRegistry, StyleSheet, Text, View, Alert, Image } from 'react-native'; import AppIntro from 'react-native-app-intro'; // import AppIntro from './AppIntro'; const styles = StyleSheet.create({ slide: { flex: 1, justifyContent: 'center', alignItems: 'center', backgroundColor: '#9DD6EB', padding: 15, }, header: { flex: 0.5, justifyContent: 'center', alignItems: 'center', }, pic: { width: 75 * 2, height: 63 * 2, }, text: { color: '#fff', fontSize: 30, fontWeight: 'bold', }, info: { flex: 0.5, alignItems: 'center', padding: 40 }, title: { color: '#fff', fontSize: 30, paddingBottom: 20, }, description: { color: '#fff', fontSize: 20, }, }); class Example extends Component { onSkipBtnHandle = (index) => { Alert.alert('Skip'); console.log(index); } doneBtnHandle = () => { Alert.alert('Done'); } nextBtnHandle = (index) => { Alert.alert('Next'); console.log(index); } onSlideChangeHandle = (index, total) => { console.log(index, total); } render() { return ( <AppIntro onNextBtnClick={this.nextBtnHandle} onDoneBtnClick={this.doneBtnHandle} onSkipBtnClick={this.onSkipBtnHandle} onSlideChange={this.onSlideChangeHandle} > <View style={[styles.slide,{ backgroundColor: '#fa931d' }]}> <View style={styles.header}> <View> <Image style={{ width: 75 * 2.5, height: 63 * 2.5 }} source={require('./img/1/c1.png')} /> </View> <View style={{ position: 'absolute', top: 80, left: -20, }} level={20} > <Image style={{ width: 46 * 2.5, height: 28 * 2.5 }} source={require('./img/1/c2.png')} /> </View> <View style={{ position: 'absolute', top: 23, left: -25, }} level={20} > <Image style={{ width: 109 * 2.5, height: 68 * 2.5 }} source={require('./img/1/c5.png')} /> </View> <View style={{ position: 'absolute', top: 65, left: -15, }} level={5} > <Image style={{ width: 23 * 2.5, height: 17 * 2.5 }} source={require('./img/1/c3.png')} /> </View> </View> <View style={styles.info}> <View level={10}><Text style={styles.title}>AppIntro</Text></View> <View level={15}><Text style={styles.description}>Pretty Simple Useful in your app tour!</Text></View> </View> </View> <View style={[styles.slide, { backgroundColor: '#a4b602' }]}> <View style={styles.header}> <View> <Image style={{ width: 75 * 2.5, height: 63 * 2.5 }} source={require('./img/2/1.png')} /> </View> <View style={{ position: 'absolute', top: 30, left: -10, }} level={20} > <Image style={{ width: 101 * 2.5, height: 71 * 2.5 }} source={require('./img/2/2.png')} /> </View> <View style={{ position: 'absolute', top: 10, left: 0, }} level={-20} > <Image style={{ width: 85 * 2.5, height: 73 * 2.5 }} source={require('./img/2/3.png')} /> </View> </View> <View style={styles.info}> <View level={10}><Text style={styles.title}>Title!</Text></View> <View level={15}><Text style={styles.description}>description!</Text></View> </View> </View> <View style={[styles.slide, { backgroundColor: '#406E9F' }]}> <View style={styles.header}> <View style={{ position: 'absolute', top: 20, left: -30, }} > <Image style={{ width: 138 * 2.5, height: 83 * 2.5 }} source={require('./img/3/3.png')} /> </View> <View style={{ position: 'absolute', top: 25, left: -10, }} level={-15} > <Image style={{ width: 103 * 2.5, height: 42 * 2.5 }} source={require('./img/3/4.png')} /> </View> <View level={10}> <Image style={{ width: 95 * 2.5, height: 55 * 2.5 }} source={require('./img/3/1.png')} /> </View> <View style={{ position: 'absolute', top: 65, left: 70, }} level={25} > <Image style={{ width: 47 * 2.5, height: 43 * 2.5 }} source={require('./img/3/2.png')} /> </View> </View> <View style={styles.info}> <View level={10}><Text style={styles.title}>Title!</Text></View> <View level={15}><Text style={styles.description}>description!</Text></View> </View> </View> <View style={[styles.slide, { backgroundColor: '#DB4302' }]}> <View style={styles.header}> <View style={{ position: 'absolute', top: 25, left: -35, }} level={15} > <Image style={{ width: 96 * 2.5, height: 69 * 2.5 }} source={require('./img/4/4.png')} /> </View> <View> <Image style={{ width: 50 * 2.5, height: 63 * 2.5 }} source={require('./img/4/1.png')} /> </View> <View style={{ position: 'absolute', top: 20, left: 0, }} level={20} > <Image style={{ width: 46 * 2.5, height: 98 * 2.5 }} source={require('./img/4/3.png')} /> </View> </View> <View style={styles.info}> <View level={10}><Text style={styles.title}>Title!</Text></View> <View level={15}><Text style={styles.description}>description!</Text></View> </View> </View> </AppIntro> ); } } AppRegistry.registerComponent('Example', () => Example);
src/svg-icons/action/update.js
spiermar/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ActionUpdate = (props) => ( <SvgIcon {...props}> <path d="M21 10.12h-6.78l2.74-2.82c-2.73-2.7-7.15-2.8-9.88-.1-2.73 2.71-2.73 7.08 0 9.79 2.73 2.71 7.15 2.71 9.88 0C18.32 15.65 19 14.08 19 12.1h2c0 1.98-.88 4.55-2.64 6.29-3.51 3.48-9.21 3.48-12.72 0-3.5-3.47-3.53-9.11-.02-12.58 3.51-3.47 9.14-3.47 12.65 0L21 3v7.12zM12.5 8v4.25l3.5 2.08-.72 1.21L11 13V8h1.5z"/> </SvgIcon> ); ActionUpdate = pure(ActionUpdate); ActionUpdate.displayName = 'ActionUpdate'; ActionUpdate.muiName = 'SvgIcon'; export default ActionUpdate;
src/tests/compose.js
kadirahq/react-komposer
/* eslint react/prefer-stateless-function: 0, react/prop-types: 0 */ import React from 'react'; import { shallow, mount } from 'enzyme'; import { expect } from 'chai'; import compose from '../compose'; const { describe, it } = global; class Comp extends React.Component { render() { return (<p>{this.props.name}</p>); } } describe('compose', () => { describe('basic features', () => { it('should pass props to the Child', () => { const Container = compose((props, onData) => { onData(null, {}); })(Comp); const el = shallow(<Container name="arunoda" />); expect(el.html()).to.match(/arunoda/); }); it('should pass data to the Child', () => { const Container = compose((props, onData) => { onData(null, { name: 'arunoda' }); })(Comp); const el = shallow(<Container />); expect(el.html()).to.match(/arunoda/); }); it('should pass both data and props to the Child', () => { const Container = compose((props, onData) => { onData(null, { name: 'arunoda' }); })(({ name, age }) => (<p>{name}={age}</p>)); const el = shallow(<Container age={20} />); expect(el.html()).to.match(/arunoda=20/); }); it('should run with the env', (done) => { const env = { name: 'arunoda' }; const options = { env }; const Container = compose((props, onData, context) => { expect(context.name).to.be.equal('arunoda'); done(); }, options)(Comp); shallow(<Container />); }); it('should show the given loading handler when there is no data', () => { const options = { loadingHandler: () => (<p>loading</p>), }; const Container = compose((props, onData) => { onData(); }, options)(Comp); const el = shallow(<Container />); expect(el.html()).to.match(/loading/); }); it('should show the given error handler when there is an error', () => { const options = { errorHandler: e => (<p>{e.message}</p>), }; const Container = compose((props, onData) => { onData(new Error('Aiyo')); }, options)(Comp); const el = shallow(<Container />); expect(el.html()).to.match(/Aiyo/); }); it('should set the child ref', () => { const Container = compose((props, onData) => { onData(null, { name: 'arunoda' }); })(Comp); const el = mount(<Container name="arunoda" />); expect(el.instance().child.props.name).to.be.equal('arunoda'); }); }); describe('dataLoader features', () => { it('should allow to pass data multiple times', () => { let onData; const Container = compose((props, _onData) => { onData = _onData; })(Comp); const el = mount(<Container />); // First run onData(null, { name: 'arunoda' }); expect(el.instance().state.data.name).to.be.equal('arunoda'); // Second run onData(null, { name: 'kamal' }); expect(el.instance().state.data.name).to.be.equal('kamal'); }); it('should unsubscribe when unmounted', (done) => { const Container = compose((props, onData) => { onData(null, {}); return done; })(Comp); const el = mount(<Container name="arunoda" />); el.instance().componentWillUnmount(); }); it('should unsubscribe when subscribing again', (done) => { let onData; const Container = compose((props, _onData) => { onData = _onData; onData(null, {}); return done; })(Comp); const el = mount(<Container name="arunoda" />); el.instance()._subscribe({ aa: 10 }); }); it('should throw an error when sending data when unmounted', () => { let onData; const Container = compose((props, _onData) => { onData = _onData; onData(null, {}); })(Comp); const el = mount(<Container name="arunoda" />); el.instance().componentWillUnmount(); const run = () => onData(null, { aa: 10 }); expect(run).to.throw(/Tyring set data after/); }); }); describe('performance', () => { describe('with propsToWatch === []', () => { describe('dataLoader', () => { it('should run for the first time - kkrgr', () => { const options = { propsToWatch: [], }; const Container = compose((props, onData) => { onData(null, { name: 'arunoda' }); }, options)(Comp); const el = shallow(<Container />); expect(el.html()).to.match(/arunoda/); }); it('should not run again', () => { const options = { propsToWatch: [], }; let callCount = 0; const Container = compose(() => { callCount += 1; }, options)(Comp); const el = mount(<Container />); el.instance()._subscribe({ aa: 10 }); expect(callCount).to.be.equal(1); }); }); }); describe('with propsToWatch == [some props]', () => { describe('dataLoader', () => { it('should not run if the watching props are the same', () => { const options = { propsToWatch: ['name'], }; let callCount = 0; const Container = compose(() => { callCount += 1; }, options)(Comp); const el = mount(<Container name="arunoda" />); el.instance()._subscribe({ name: 'arunoda', age: 20 }); expect(callCount).to.be.equal(1); }); it('should not run if the watching props changed', () => { const options = { propsToWatch: ['name'], }; let callCount = 0; const Container = compose(() => { callCount += 1; }, options)(Comp); const el = mount(<Container name="arunoda" />); el.instance()._subscribe({ name: 'kamal', age: 20 }); expect(callCount).to.be.equal(2); }); it('should do a shallow comparison', () => { const options = { propsToWatch: ['data'], }; const data = {}; let callCount = 0; const Container = compose(() => { callCount += 1; }, options)(Comp); const el = mount(<Container data={data} />); // let's change the stuff inside the data data.foo = 100; el.instance()._subscribe({ data }); expect(callCount).to.be.equal(1); }); it('should watch multiple props', () => { const options = { propsToWatch: ['name', 'age'], }; let callCount = 0; const Container = compose(() => { callCount += 1; }, options)(Comp); const el = mount(<Container name="arunoda" age={20} />); // first run with same props el.instance()._subscribe({ name: 'arunoda', age: 20, kkr: 20 }); expect(callCount).to.be.equal(1); // second run with changed props el.instance()._subscribe({ name: 'arunoda', age: 30 }); expect(callCount).to.be.equal(2); }); }); }); describe('with shouldSubscribe', () => { describe('dataLoader', () => { it('should run for the first time even shouldSubscribe give false', () => { const options = { shouldSubscribe: () => false, }; const Container = compose((props, onData) => { onData(null, { name: 'arunoda' }); }, options)(Comp); const el = shallow(<Container />); expect(el.html()).to.match(/arunoda/); }); it('should ignore propsToWatch', () => { const options = { shouldSubscribe: () => true, propsToWatch: [], }; let callCount = 0; const Container = compose(() => { callCount += 1; }, options)(Comp); const el = mount(<Container />); el.instance()._subscribe({ aa: 10 }); expect(callCount).to.be.equal(2); }); }); }); describe('pure', () => { describe('default', () => { it('should run not be pure', () => { const Container = compose(() => null)(Comp); const i = shallow(<Container />).instance(); expect(i.shouldComponentUpdate()).to.be.equal(true); }); }); describe('with shouldUpdate', () => { it('should run should update', () => { const nextProps = { aa: 20 }; const options = { shouldUpdate(cp, np) { expect(cp).to.deep.equal({ aa: 10 }); expect(np).to.deep.equal(nextProps); return false; }, }; const Container = compose(() => null, options)(Comp); const i = shallow(<Container aa={10} />).instance(); expect(i.shouldComponentUpdate(nextProps)).to.be.equal(false); }); }); describe('with props', () => { it('should be true if props are different', () => { const Container = compose(() => null, { pure: true })(Comp); const i = shallow(<Container p1="10" />).instance(); expect(i.shouldComponentUpdate({ p1: '11' }, {})).to.be.equal(true); i.props = { p1: '11' }; expect(i.shouldComponentUpdate({ p1: '11', p2: 10 }, {})) .to.be.equal(true); }); it('should be false if props are the same', () => { const Container = compose(() => null, { pure: true })(Comp); const i = shallow(<Container p1="10" />).instance(); expect(i.shouldComponentUpdate({ p1: '10' }, {}, {})).to.be.equal(false); }); }); describe('with error', () => { it('should be true if errors are different', () => { const Container = compose(() => null, { pure: true })(Comp); const i = shallow(<Container />).instance(); const error = new Error('hello'); expect(i.shouldComponentUpdate(i.props, { error })).to.be.equal(true); i.state = { error }; const newError = new Error('hello'); expect(i.shouldComponentUpdate(i.props, { error: newError })) .to.be.equal(true); }); it('should be false if errors are the same', () => { const Container = compose(() => null, { pure: true })(Comp); const i = shallow(<Container />).instance(); const error = new Error('hello'); expect(i.shouldComponentUpdate(i.props, { error })).to.be.equal(true); i.state = { error }; expect(i.shouldComponentUpdate(i.props, { error }, {})) .to.be.equal(false); }); }); describe('with data', () => { it('should be true if data are different', () => { const Container = compose(() => null, { pure: true })(Comp); const i = shallow(<Container />).instance(); const data = { aa: 10 }; expect(i.shouldComponentUpdate(i.props, { data })).to.be.equal(true); i.state = { data }; const sameData = { aa: 10 }; expect(i.shouldComponentUpdate(i.props, { data: sameData }, {})) .to.be.equal(false); }); it('should be false if data are the same', () => { const Container = compose(() => null, { pure: true })(Comp); const i = shallow(<Container />).instance(); const data = { aa: 10 }; expect(i.shouldComponentUpdate(i.props, { data })).to.be.equal(true); i.state = { data }; const sameData = { aa: 10 }; expect(i.shouldComponentUpdate(i.props, { data: sameData }, {})) .to.be.equal(false); }); }); }); }); });
examples/async/index.js
morgante/redux
import 'babel-core/polyfill'; import React from 'react'; import { Provider } from 'react-redux'; import App from './containers/App'; import configureStore from './store/configureStore'; const store = configureStore(); React.render( <Provider store={store}> {() => <App />} </Provider>, document.getElementById('root') );
node_modules/react-icons/md/account-balance.js
bengimbel/Solstice-React-Contacts-Project
import React from 'react' import Icon from 'react-icon-base' const MdAccountBalance = props => ( <Icon viewBox="0 0 40 40" {...props}> <g><path d="m19.1 1.6l15.9 8.4v3.4h-31.6v-3.4z m7.5 15h5v11.8h-5v-11.8z m-23.2 20v-5h31.6v5h-31.6z m13.2-20h5v11.8h-5v-11.8z m-10 0h5v11.8h-5v-11.8z"/></g> </Icon> ) export default MdAccountBalance
imports/plugins/core/ui/client/components/multiselect/multiselect.js
evereveofficial/reaction
import React, { Component, PropTypes } from "react"; import classnames from "classnames"; import Select from "react-select"; import { Translation } from "../translation"; import { i18next } from "/client/api"; class MultiSelect extends Component { static defaultProps = { multi: true, simpleValue: true } static propTypes = { i18nKeyLabel: PropTypes.string, i18nKeyPlaceholder: PropTypes.string, label: PropTypes.string, name: PropTypes.string, onChange: PropTypes.func, options: PropTypes.array, placeholder: PropTypes.string, value: PropTypes.oneOfType([PropTypes.array, PropTypes.string]) } renderLabel() { if (this.props.label) { return ( <label> <Translation defaultValue={this.props.label} i18nKey={this.props.i18nKeyLabel} /> </label> ); } return null; } handleChange = (value) => { if (typeof this.props.onChange === "function") { this.props.onChange(value, this.props.name); } } render() { const { label, i18nKeyLabel, // eslint-disable-line no-unused-vars placeholder, i18nKeyPlaceholder, ...selectProps } = this.props; const classes = classnames({ // Base "rui": true, "multiselect": true, "form-group": true }); const translatedPlaceholder = i18next.t(i18nKeyPlaceholder, { defaultValue: placeholder }); return ( <div className={classes}> {this.renderLabel()} <Select {...selectProps} placeholder={translatedPlaceholder} onChange={this.handleChange} /> </div> ); } } export default MultiSelect;
ajax/libs/analytics.js/2.8.18/analytics.js
jasonpang/cdnjs
(function umd(require){ if ('object' == typeof exports) { module.exports = require('1'); } else if ('function' == typeof define && define.amd) { define(function(){ return require('1'); }); } else { this['analytics'] = require('1'); } })((function outer(modules, cache, entries){ /** * Global */ var global = (function(){ return this; })(); /** * Require `name`. * * @param {String} name * @param {Boolean} jumped * @api public */ function require(name, jumped){ if (cache[name]) return cache[name].exports; if (modules[name]) return call(name, require); throw new Error('cannot find module "' + name + '"'); } /** * Call module `id` and cache it. * * @param {Number} id * @param {Function} require * @return {Function} * @api private */ function call(id, require){ var m = cache[id] = { exports: {} }; var mod = modules[id]; var name = mod[2]; var fn = mod[0]; fn.call(m.exports, function(req){ var dep = modules[id][1][req]; return require(dep ? dep : req); }, m, m.exports, outer, modules, cache, entries); // expose as `name`. if (name) cache[name] = cache[id]; return cache[id].exports; } /** * Require all entries exposing them on global if needed. */ for (var id in entries) { if (entries[id]) { global[entries[id]] = require(id); } else { require(id); } } /** * Duo flag. */ require.duo = true; /** * Expose cache. */ require.cache = cache; /** * Expose modules */ require.modules = modules; /** * Return newest require. */ return require; })({ 1: [function(require, module, exports) { /** * Analytics.js * * (C) 2013 Segment.io Inc. */ var _analytics = window.analytics; var Integrations = require('analytics.js-integrations'); var Analytics = require('./analytics'); var each = require('each'); /** * Expose the `analytics` singleton. */ var analytics = module.exports = exports = new Analytics(); /** * Expose require */ analytics.require = require; /** * Expose `VERSION`. */ exports.VERSION = require('../bower.json').version; /** * Add integrations. */ each(Integrations, function (name, Integration) { analytics.use(Integration); }); }, {"analytics.js-integrations":2,"./analytics":3,"each":4,"../bower.json":5}], 2: [function(require, module, exports) { /** * Module dependencies. */ var each = require('each'); var plugins = require('./integrations.js'); /** * Expose the integrations, using their own `name` from their `prototype`. */ each(plugins, function(plugin){ var name = (plugin.Integration || plugin).prototype.name; exports[name] = plugin; }); }, {"each":4,"./integrations.js":6}], 4: [function(require, module, exports) { /** * Module dependencies. */ var type = require('type'); /** * HOP reference. */ var has = Object.prototype.hasOwnProperty; /** * Iterate the given `obj` and invoke `fn(val, i)`. * * @param {String|Array|Object} obj * @param {Function} fn * @api public */ module.exports = function(obj, fn){ switch (type(obj)) { case 'array': return array(obj, fn); case 'object': if ('number' == typeof obj.length) return array(obj, fn); return object(obj, fn); case 'string': return string(obj, fn); } }; /** * Iterate string chars. * * @param {String} obj * @param {Function} fn * @api private */ function string(obj, fn) { for (var i = 0; i < obj.length; ++i) { fn(obj.charAt(i), i); } } /** * Iterate object keys. * * @param {Object} obj * @param {Function} fn * @api private */ function object(obj, fn) { for (var key in obj) { if (has.call(obj, key)) { fn(key, obj[key]); } } } /** * Iterate array-ish. * * @param {Array|Object} obj * @param {Function} fn * @api private */ function array(obj, fn) { for (var i = 0; i < obj.length; ++i) { fn(obj[i], i); } } }, {"type":7}], 7: [function(require, module, exports) { /** * toString ref. */ var toString = Object.prototype.toString; /** * Return the type of `val`. * * @param {Mixed} val * @return {String} * @api public */ module.exports = function(val){ switch (toString.call(val)) { case '[object Date]': return 'date'; case '[object RegExp]': return 'regexp'; case '[object Arguments]': return 'arguments'; case '[object Array]': return 'array'; case '[object Error]': return 'error'; } if (val === null) return 'null'; if (val === undefined) return 'undefined'; if (val !== val) return 'nan'; if (val && val.nodeType === 1) return 'element'; val = val.valueOf ? val.valueOf() : Object.prototype.valueOf.apply(val) return typeof val; }; }, {}], 6: [function(require, module, exports) { /** * DON'T EDIT THIS FILE. It's automatically generated! */ module.exports = [ require('./lib/adroll'), require('./lib/adwords'), require('./lib/alexa'), require('./lib/amplitude'), require('./lib/appcues'), require('./lib/atatus'), require('./lib/autosend'), require('./lib/awesm'), require('./lib/bing-ads'), require('./lib/blueshift'), require('./lib/bronto'), require('./lib/bugherd'), require('./lib/bugsnag'), require('./lib/chartbeat'), require('./lib/clicktale'), require('./lib/clicky'), require('./lib/comscore'), require('./lib/crazy-egg'), require('./lib/curebit'), require('./lib/customerio'), require('./lib/drip'), require('./lib/errorception'), require('./lib/evergage'), require('./lib/extole'), require('./lib/facebook-conversion-tracking'), require('./lib/foxmetrics'), require('./lib/frontleaf'), require('./lib/fullstory'), require('./lib/gauges'), require('./lib/get-satisfaction'), require('./lib/google-analytics'), require('./lib/google-tag-manager'), require('./lib/gosquared'), require('./lib/heap'), require('./lib/hellobar'), require('./lib/hittail'), require('./lib/hubspot'), require('./lib/improvely'), require('./lib/insidevault'), require('./lib/inspectlet'), require('./lib/intercom'), require('./lib/keen-io'), require('./lib/kenshoo'), require('./lib/kissmetrics'), require('./lib/klaviyo'), require('./lib/livechat'), require('./lib/lucky-orange'), require('./lib/lytics'), require('./lib/mixpanel'), require('./lib/mojn'), require('./lib/mouseflow'), require('./lib/mousestats'), require('./lib/navilytics'), require('./lib/nudgespot'), require('./lib/olark'), require('./lib/optimizely'), require('./lib/outbound'), require('./lib/perfect-audience'), require('./lib/pingdom'), require('./lib/piwik'), require('./lib/preact'), require('./lib/qualaroo'), require('./lib/quantcast'), require('./lib/rollbar'), require('./lib/saasquatch'), require('./lib/satismeter'), require('./lib/segmentio'), require('./lib/sentry'), require('./lib/snapengage'), require('./lib/spinnakr'), require('./lib/supporthero'), require('./lib/tapstream'), require('./lib/trakio'), require('./lib/twitter-ads'), require('./lib/userlike'), require('./lib/uservoice'), require('./lib/vero'), require('./lib/visual-website-optimizer'), require('./lib/webengage'), require('./lib/woopra'), require('./lib/yandex-metrica') ]; }, {"./lib/adroll":8,"./lib/adwords":9,"./lib/alexa":10,"./lib/amplitude":11,"./lib/appcues":12,"./lib/atatus":13,"./lib/autosend":14,"./lib/awesm":15,"./lib/bing-ads":16,"./lib/blueshift":17,"./lib/bronto":18,"./lib/bugherd":19,"./lib/bugsnag":20,"./lib/chartbeat":21,"./lib/clicktale":22,"./lib/clicky":23,"./lib/comscore":24,"./lib/crazy-egg":25,"./lib/curebit":26,"./lib/customerio":27,"./lib/drip":28,"./lib/errorception":29,"./lib/evergage":30,"./lib/extole":31,"./lib/facebook-conversion-tracking":32,"./lib/foxmetrics":33,"./lib/frontleaf":34,"./lib/fullstory":35,"./lib/gauges":36,"./lib/get-satisfaction":37,"./lib/google-analytics":38,"./lib/google-tag-manager":39,"./lib/gosquared":40,"./lib/heap":41,"./lib/hellobar":42,"./lib/hittail":43,"./lib/hubspot":44,"./lib/improvely":45,"./lib/insidevault":46,"./lib/inspectlet":47,"./lib/intercom":48,"./lib/keen-io":49,"./lib/kenshoo":50,"./lib/kissmetrics":51,"./lib/klaviyo":52,"./lib/livechat":53,"./lib/lucky-orange":54,"./lib/lytics":55,"./lib/mixpanel":56,"./lib/mojn":57,"./lib/mouseflow":58,"./lib/mousestats":59,"./lib/navilytics":60,"./lib/nudgespot":61,"./lib/olark":62,"./lib/optimizely":63,"./lib/outbound":64,"./lib/perfect-audience":65,"./lib/pingdom":66,"./lib/piwik":67,"./lib/preact":68,"./lib/qualaroo":69,"./lib/quantcast":70,"./lib/rollbar":71,"./lib/saasquatch":72,"./lib/satismeter":73,"./lib/segmentio":74,"./lib/sentry":75,"./lib/snapengage":76,"./lib/spinnakr":77,"./lib/supporthero":78,"./lib/tapstream":79,"./lib/trakio":80,"./lib/twitter-ads":81,"./lib/userlike":82,"./lib/uservoice":83,"./lib/vero":84,"./lib/visual-website-optimizer":85,"./lib/webengage":86,"./lib/woopra":87,"./lib/yandex-metrica":88}], 8: [function(require, module, exports) { /** * Module dependencies. */ var integration = require('analytics.js-integration'); var snake = require('to-snake-case'); var useHttps = require('use-https'); var each = require('each'); var is = require('is'); var del = require('obj-case').del; /** * HOP */ var has = Object.prototype.hasOwnProperty; /** * Expose `AdRoll` integration. */ var AdRoll = module.exports = integration('AdRoll') .assumesPageview() .global('__adroll_loaded') .global('adroll_adv_id') .global('adroll_pix_id') .global('adroll_custom_data') .option('advId', '') .option('pixId', '') .tag('http', '<script src="http://a.adroll.com/j/roundtrip.js">') .tag('https', '<script src="https://s.adroll.com/j/roundtrip.js">') .mapping('events'); /** * Initialize. * * http://support.adroll.com/getting-started-in-4-easy-steps/#step-one * http://support.adroll.com/enhanced-conversion-tracking/ * * @param {Object} page */ AdRoll.prototype.initialize = function(page){ window.adroll_adv_id = this.options.advId; window.adroll_pix_id = this.options.pixId; window.__adroll_loaded = true; var name = useHttps() ? 'https' : 'http'; this.load(name, this.ready); }; /** * Loaded? * * @return {Boolean} */ AdRoll.prototype.loaded = function(){ return window.__adroll; }; /** * Page. * * http://support.adroll.com/segmenting-clicks/ * * @param {Page} page */ AdRoll.prototype.page = function(page){ var name = page.fullName(); this.track(page.track(name)); }; /** * Track. * * @param {Track} track */ AdRoll.prototype.track = function(track){ var event = track.event(); var user = this.analytics.user(); var events = this.events(event); var total = track.revenue() || track.total() || 0; var orderId = track.orderId() || 0; var productId = track.id(); var sku = track.sku(); var customProps = track.properties(); var data = {}; if (user.id()) data.user_id = user.id(); if (orderId) data.order_id = orderId; if (productId) data.product_id = productId; if (sku) data.sku = sku; if (total) data.adroll_conversion_value_in_dollars = total; del(customProps, "revenue"); del(customProps, "total"); del(customProps, "orderId"); del(customProps, "id"); del(customProps, "sku"); if (!is.empty(customProps)) data.adroll_custom_data = customProps; each(events, function(event){ // the adroll interface only allows for // segment names which are snake cased. data.adroll_segments = snake(event); window.__adroll.record_user(data); }); // no events found if (!events.length) { data.adroll_segments = snake(event); window.__adroll.record_user(data); } }; }, {"analytics.js-integration":89,"to-snake-case":90,"use-https":91,"each":4,"is":92,"obj-case":93}], 89: [function(require, module, exports) { /** * Module dependencies. */ var bind = require('bind'); var callback = require('callback'); var clone = require('clone'); var debug = require('debug'); var defaults = require('defaults'); var protos = require('./protos'); var slug = require('slug'); var statics = require('./statics'); /** * Expose `createIntegration`. */ module.exports = createIntegration; /** * Create a new `Integration` constructor. * * @param {String} name * @return {Function} Integration */ function createIntegration(name){ /** * Initialize a new `Integration`. * * @param {Object} options */ function Integration(options){ if (options && options.addIntegration) { // plugin return options.addIntegration(Integration); } this.debug = debug('analytics:integration:' + slug(name)); this.options = defaults(clone(options) || {}, this.defaults); this._queue = []; this.once('ready', bind(this, this.flush)); Integration.emit('construct', this); this.ready = bind(this, this.ready); this._wrapInitialize(); this._wrapPage(); this._wrapTrack(); } Integration.prototype.defaults = {}; Integration.prototype.globals = []; Integration.prototype.templates = {}; Integration.prototype.name = name; for (var key in statics) Integration[key] = statics[key]; for (var key in protos) Integration.prototype[key] = protos[key]; return Integration; } }, {"bind":94,"callback":95,"clone":96,"debug":97,"defaults":98,"./protos":99,"slug":100,"./statics":101}], 94: [function(require, module, exports) { var bind = require('bind') , bindAll = require('bind-all'); /** * Expose `bind`. */ module.exports = exports = bind; /** * Expose `bindAll`. */ exports.all = bindAll; /** * Expose `bindMethods`. */ exports.methods = bindMethods; /** * Bind `methods` on `obj` to always be called with the `obj` as context. * * @param {Object} obj * @param {String} methods... */ function bindMethods (obj, methods) { methods = [].slice.call(arguments, 1); for (var i = 0, method; method = methods[i]; i++) { obj[method] = bind(obj, obj[method]); } return obj; } }, {"bind":102,"bind-all":103}], 102: [function(require, module, exports) { /** * Slice reference. */ var slice = [].slice; /** * Bind `obj` to `fn`. * * @param {Object} obj * @param {Function|String} fn or string * @return {Function} * @api public */ module.exports = function(obj, fn){ if ('string' == typeof fn) fn = obj[fn]; if ('function' != typeof fn) throw new Error('bind() requires a function'); var args = slice.call(arguments, 2); return function(){ return fn.apply(obj, args.concat(slice.call(arguments))); } }; }, {}], 103: [function(require, module, exports) { try { var bind = require('bind'); var type = require('type'); } catch (e) { var bind = require('bind-component'); var type = require('type-component'); } module.exports = function (obj) { for (var key in obj) { var val = obj[key]; if (type(val) === 'function') obj[key] = bind(obj, obj[key]); } return obj; }; }, {"bind":102,"type":7}], 95: [function(require, module, exports) { var next = require('next-tick'); /** * Expose `callback`. */ module.exports = callback; /** * Call an `fn` back synchronously if it exists. * * @param {Function} fn */ function callback (fn) { if ('function' === typeof fn) fn(); } /** * Call an `fn` back asynchronously if it exists. If `wait` is ommitted, the * `fn` will be called on next tick. * * @param {Function} fn * @param {Number} wait (optional) */ callback.async = function (fn, wait) { if ('function' !== typeof fn) return; if (!wait) return next(fn); setTimeout(fn, wait); }; /** * Symmetry. */ callback.sync = callback; }, {"next-tick":104}], 104: [function(require, module, exports) { "use strict" if (typeof setImmediate == 'function') { module.exports = function(f){ setImmediate(f) } } // legacy node.js else if (typeof process != 'undefined' && typeof process.nextTick == 'function') { module.exports = process.nextTick } // fallback for other environments / postMessage behaves badly on IE8 else if (typeof window == 'undefined' || window.ActiveXObject || !window.postMessage) { module.exports = function(f){ setTimeout(f) }; } else { var q = []; window.addEventListener('message', function(){ var i = 0; while (i < q.length) { try { q[i++](); } catch (e) { q = q.slice(i); window.postMessage('tic!', '*'); throw e; } } q.length = 0; }, true); module.exports = function(fn){ if (!q.length) window.postMessage('tic!', '*'); q.push(fn); } } }, {}], 96: [function(require, module, exports) { /** * Module dependencies. */ var type; try { type = require('type'); } catch(e){ type = require('type-component'); } /** * Module exports. */ module.exports = clone; /** * Clones objects. * * @param {Mixed} any object * @api public */ function clone(obj){ switch (type(obj)) { case 'object': var copy = {}; for (var key in obj) { if (obj.hasOwnProperty(key)) { copy[key] = clone(obj[key]); } } return copy; case 'array': var copy = new Array(obj.length); for (var i = 0, l = obj.length; i < l; i++) { copy[i] = clone(obj[i]); } return copy; case 'regexp': // from millermedeiros/amd-utils - MIT var flags = ''; flags += obj.multiline ? 'm' : ''; flags += obj.global ? 'g' : ''; flags += obj.ignoreCase ? 'i' : ''; return new RegExp(obj.source, flags); case 'date': return new Date(obj.getTime()); default: // string, number, boolean, … return obj; } } }, {"type":7}], 97: [function(require, module, exports) { if ('undefined' == typeof window) { module.exports = require('./lib/debug'); } else { module.exports = require('./debug'); } }, {"./lib/debug":105,"./debug":106}], 105: [function(require, module, exports) { /** * Module dependencies. */ var tty = require('tty'); /** * Expose `debug()` as the module. */ module.exports = debug; /** * Enabled debuggers. */ var names = [] , skips = []; (process.env.DEBUG || '') .split(/[\s,]+/) .forEach(function(name){ name = name.replace('*', '.*?'); if (name[0] === '-') { skips.push(new RegExp('^' + name.substr(1) + '$')); } else { names.push(new RegExp('^' + name + '$')); } }); /** * Colors. */ var colors = [6, 2, 3, 4, 5, 1]; /** * Previous debug() call. */ var prev = {}; /** * Previously assigned color. */ var prevColor = 0; /** * Is stdout a TTY? Colored output is disabled when `true`. */ var isatty = tty.isatty(2); /** * Select a color. * * @return {Number} * @api private */ function color() { return colors[prevColor++ % colors.length]; } /** * Humanize the given `ms`. * * @param {Number} m * @return {String} * @api private */ function humanize(ms) { var sec = 1000 , min = 60 * 1000 , hour = 60 * min; if (ms >= hour) return (ms / hour).toFixed(1) + 'h'; if (ms >= min) return (ms / min).toFixed(1) + 'm'; if (ms >= sec) return (ms / sec | 0) + 's'; return ms + 'ms'; } /** * Create a debugger with the given `name`. * * @param {String} name * @return {Type} * @api public */ function debug(name) { function disabled(){} disabled.enabled = false; var match = skips.some(function(re){ return re.test(name); }); if (match) return disabled; match = names.some(function(re){ return re.test(name); }); if (!match) return disabled; var c = color(); function colored(fmt) { fmt = coerce(fmt); var curr = new Date; var ms = curr - (prev[name] || curr); prev[name] = curr; fmt = ' \u001b[9' + c + 'm' + name + ' ' + '\u001b[3' + c + 'm\u001b[90m' + fmt + '\u001b[3' + c + 'm' + ' +' + humanize(ms) + '\u001b[0m'; console.error.apply(this, arguments); } function plain(fmt) { fmt = coerce(fmt); fmt = new Date().toUTCString() + ' ' + name + ' ' + fmt; console.error.apply(this, arguments); } colored.enabled = plain.enabled = true; return isatty || process.env.DEBUG_COLORS ? colored : plain; } /** * Coerce `val`. */ function coerce(val) { if (val instanceof Error) return val.stack || val.message; return val; } }, {}], 106: [function(require, module, exports) { /** * Expose `debug()` as the module. */ module.exports = debug; /** * Create a debugger with the given `name`. * * @param {String} name * @return {Type} * @api public */ function debug(name) { if (!debug.enabled(name)) return function(){}; return function(fmt){ fmt = coerce(fmt); var curr = new Date; var ms = curr - (debug[name] || curr); debug[name] = curr; fmt = name + ' ' + fmt + ' +' + debug.humanize(ms); // This hackery is required for IE8 // where `console.log` doesn't have 'apply' window.console && console.log && Function.prototype.apply.call(console.log, console, arguments); } } /** * The currently active debug mode names. */ debug.names = []; debug.skips = []; /** * Enables a debug mode by name. This can include modes * separated by a colon and wildcards. * * @param {String} name * @api public */ debug.enable = function(name) { try { localStorage.debug = name; } catch(e){} var split = (name || '').split(/[\s,]+/) , len = split.length; for (var i = 0; i < len; i++) { name = split[i].replace('*', '.*?'); if (name[0] === '-') { debug.skips.push(new RegExp('^' + name.substr(1) + '$')); } else { debug.names.push(new RegExp('^' + name + '$')); } } }; /** * Disable debug output. * * @api public */ debug.disable = function(){ debug.enable(''); }; /** * Humanize the given `ms`. * * @param {Number} m * @return {String} * @api private */ debug.humanize = function(ms) { var sec = 1000 , min = 60 * 1000 , hour = 60 * min; if (ms >= hour) return (ms / hour).toFixed(1) + 'h'; if (ms >= min) return (ms / min).toFixed(1) + 'm'; if (ms >= sec) return (ms / sec | 0) + 's'; return ms + 'ms'; }; /** * Returns true if the given mode name is enabled, false otherwise. * * @param {String} name * @return {Boolean} * @api public */ debug.enabled = function(name) { for (var i = 0, len = debug.skips.length; i < len; i++) { if (debug.skips[i].test(name)) { return false; } } for (var i = 0, len = debug.names.length; i < len; i++) { if (debug.names[i].test(name)) { return true; } } return false; }; /** * Coerce `val`. */ function coerce(val) { if (val instanceof Error) return val.stack || val.message; return val; } // persist try { if (window.localStorage) debug.enable(localStorage.debug); } catch(e){} }, {}], 98: [function(require, module, exports) { 'use strict'; /** * Merge default values. * * @param {Object} dest * @param {Object} defaults * @return {Object} * @api public */ var defaults = function (dest, src, recursive) { for (var prop in src) { if (recursive && dest[prop] instanceof Object && src[prop] instanceof Object) { dest[prop] = defaults(dest[prop], src[prop], true); } else if (! (prop in dest)) { dest[prop] = src[prop]; } } return dest; }; /** * Expose `defaults`. */ module.exports = defaults; }, {}], 99: [function(require, module, exports) { /** * Module dependencies. */ var loadScript = require('load-script'); var loadIframe = require('load-iframe'); var events = require('analytics-events'); var normalize = require('to-no-case'); var callback = require('callback'); var Emitter = require('emitter'); var tick = require('next-tick'); var after = require('after'); var each = require('each'); var type = require('type'); var fmt = require('fmt'); /** * Noop. */ function noop(){} /** * Window defaults. */ var setTimeout = window.setTimeout; var setInterval = window.setInterval; var onerror = window.onerror; var onload = null; /** * Mixin emitter. */ Emitter(exports); /** * Initialize. */ exports.initialize = function(){ var ready = this.ready; tick(ready); }; /** * Loaded? * * @return {Boolean} * @api private */ exports.loaded = function(){ return false; }; /** * Page. * * @param {Page} page */ exports.page = function(page){}; /** * Track. * * @param {Track} track */ exports.track = function(track){}; /** * Get events that match `str`. * * Examples: * * events = { my_event: 'a4991b88' } * .map(events, 'My Event'); * // => ["a4991b88"] * .map(events, 'whatever'); * // => [] * * events = [{ key: 'my event', value: '9b5eb1fa' }] * .map(events, 'my_event'); * // => ["9b5eb1fa"] * .map(events, 'whatever'); * // => [] * * @param {String} str * @return {Array} * @api public */ exports.map = function(obj, str){ var a = normalize(str); var ret = []; // noop if (!obj) return ret; // object if ('object' == type(obj)) { for (var k in obj) { var item = obj[k]; var b = normalize(k); if (b == a) ret.push(item); } } // array if ('array' == type(obj)) { if (!obj.length) return ret; if (!obj[0].key) return ret; for (var i = 0; i < obj.length; ++i) { var item = obj[i]; var b = normalize(item.key); if (b == a) ret.push(item.value); } } return ret; }; /** * Invoke a `method` that may or may not exist on the prototype with `args`, * queueing or not depending on whether the integration is "ready". Don't * trust the method call, since it contains integration party code. * * @param {String} method * @param {Mixed} args... * @api private */ exports.invoke = function(method){ if (!this[method]) return; var args = [].slice.call(arguments, 1); if (!this._ready) return this.queue(method, args); var ret; try { this.debug('%s with %o', method, args); ret = this[method].apply(this, args); } catch (e) { this.debug('error %o calling %s with %o', e, method, args); } return ret; }; /** * Queue a `method` with `args`. If the integration assumes an initial * pageview, then let the first call to `page` pass through. * * @param {String} method * @param {Array} args * @api private */ exports.queue = function(method, args){ if ('page' == method && this._assumesPageview && !this._initialized) { return this.page.apply(this, args); } this._queue.push({ method: method, args: args }); }; /** * Flush the internal queue. * * @api private */ exports.flush = function(){ this._ready = true; var call; while (call = this._queue.shift()) this[call.method].apply(this, call.args); }; /** * Reset the integration, removing its global variables. * * @api private */ exports.reset = function(){ for (var i = 0, key; key = this.globals[i]; i++) window[key] = undefined; window.setTimeout = setTimeout; window.setInterval = setInterval; window.onerror = onerror; window.onload = onload; }; /** * Load a tag by `name`. * * @param {String} name * @param {Function} [fn] */ exports.load = function(name, locals, fn){ if ('function' == typeof name) fn = name, locals = null, name = null; if (name && 'object' == typeof name) fn = locals, locals = name, name = null; if ('function' == typeof locals) fn = locals, locals = null; name = name || 'library'; locals = locals || {}; locals = this.locals(locals); var template = this.templates[name]; if (!template) throw new Error(fmt('template "%s" not defined.', name)); var attrs = render(template, locals); var fn = fn || noop; var self = this; var el; switch (template.type) { case 'img': attrs.width = 1; attrs.height = 1; el = loadImage(attrs, fn); break; case 'script': el = loadScript(attrs, function(err){ if (!err) return fn(); self.debug('error loading "%s" error="%s"', self.name, err); }); // TODO: hack until refactoring load-script delete attrs.src; each(attrs, function(key, val){ el.setAttribute(key, val); }); break; case 'iframe': el = loadIframe(attrs, fn); break; } return el; }; /** * Locals for tag templates. * * By default it includes a cache buster, * and all of the options. * * @param {Object} [locals] * @return {Object} */ exports.locals = function(locals){ locals = locals || {}; var cache = Math.floor(new Date().getTime() / 3600000); if (!locals.hasOwnProperty('cache')) locals.cache = cache; each(this.options, function(key, val){ if (!locals.hasOwnProperty(key)) locals[key] = val; }); return locals; }; /** * Simple way to emit ready. */ exports.ready = function(){ this.emit('ready'); }; /** * Wrap the initialize method in an exists check, so we don't have to do it for * every single integration. * * @api private */ exports._wrapInitialize = function(){ var initialize = this.initialize; this.initialize = function(){ this.debug('initialize'); this._initialized = true; var ret = initialize.apply(this, arguments); this.emit('initialize'); return ret; }; if (this._assumesPageview) this.initialize = after(2, this.initialize); }; /** * Wrap the page method to call `initialize` instead if the integration assumes * a pageview. * * @api private */ exports._wrapPage = function(){ var page = this.page; this.page = function(){ if (this._assumesPageview && !this._initialized) { return this.initialize.apply(this, arguments); } return page.apply(this, arguments); }; }; /** * Wrap the track method to call other ecommerce methods if * available depending on the `track.event()`. * * @api private */ exports._wrapTrack = function(){ var t = this.track; this.track = function(track){ var event = track.event(); var called; var ret; for (var method in events) { var regexp = events[method]; if (!this[method]) continue; if (!regexp.test(event)) continue; ret = this[method].apply(this, arguments); called = true; break; } if (!called) ret = t.apply(this, arguments); return ret; }; }; function loadImage(attrs, fn) { fn = fn || function(){}; var img = new Image; img.onerror = error(fn, 'failed to load pixel', img); img.onload = function(){ fn(); }; img.src = attrs.src; img.width = 1; img.height = 1; return img; } function error(fn, message, img){ return function(e){ e = e || window.event; var err = new Error(message); err.event = e; err.source = img; fn(err); }; } /** * Render template + locals into an `attrs` object. * * @param {Object} template * @param {Object} locals * @return {Object} */ function render(template, locals) { var attrs = {}; each(template.attrs, function(key, val){ attrs[key] = val.replace(/\{\{\ *(\w+)\ *\}\}/g, function(_, $1){ return locals[$1]; }); }); return attrs; } }, {"load-script":107,"load-iframe":108,"analytics-events":109,"to-no-case":110,"callback":95,"emitter":111,"next-tick":104,"after":112,"each":113,"type":114,"fmt":115}], 107: [function(require, module, exports) { /** * Module dependencies. */ var onload = require('script-onload'); var tick = require('next-tick'); var type = require('type'); /** * Expose `loadScript`. * * @param {Object} options * @param {Function} fn * @api public */ module.exports = function loadScript(options, fn){ if (!options) throw new Error('Cant load nothing...'); // Allow for the simplest case, just passing a `src` string. if ('string' == type(options)) options = { src : options }; var https = document.location.protocol === 'https:' || document.location.protocol === 'chrome-extension:'; // If you use protocol relative URLs, third-party scripts like Google // Analytics break when testing with `file:` so this fixes that. if (options.src && options.src.indexOf('//') === 0) { options.src = https ? 'https:' + options.src : 'http:' + options.src; } // Allow them to pass in different URLs depending on the protocol. if (https && options.https) options.src = options.https; else if (!https && options.http) options.src = options.http; // Make the `<script>` element and insert it before the first script on the // page, which is guaranteed to exist since this Javascript is running. var script = document.createElement('script'); script.type = 'text/javascript'; script.async = true; script.src = options.src; // If we have a fn, attach event handlers, even in IE. Based off of // the Third-Party Javascript script loading example: // https://github.com/thirdpartyjs/thirdpartyjs-code/blob/master/examples/templates/02/loading-files/index.html if ('function' == type(fn)) { onload(script, fn); } tick(function(){ // Append after event listeners are attached for IE. var firstScript = document.getElementsByTagName('script')[0]; firstScript.parentNode.insertBefore(script, firstScript); }); // Return the script element in case they want to do anything special, like // give it an ID or attributes. return script; }; }, {"script-onload":116,"next-tick":104,"type":7}], 116: [function(require, module, exports) { // https://github.com/thirdpartyjs/thirdpartyjs-code/blob/master/examples/templates/02/loading-files/index.html /** * Invoke `fn(err)` when the given `el` script loads. * * @param {Element} el * @param {Function} fn * @api public */ module.exports = function(el, fn){ return el.addEventListener ? add(el, fn) : attach(el, fn); }; /** * Add event listener to `el`, `fn()`. * * @param {Element} el * @param {Function} fn * @api private */ function add(el, fn){ el.addEventListener('load', function(_, e){ fn(null, e); }, false); el.addEventListener('error', function(e){ var err = new Error('script error "' + el.src + '"'); err.event = e; fn(err); }, false); } /** * Attach evnet. * * @param {Element} el * @param {Function} fn * @api private */ function attach(el, fn){ el.attachEvent('onreadystatechange', function(e){ if (!/complete|loaded/.test(el.readyState)) return; fn(null, e); }); el.attachEvent('onerror', function(e){ var err = new Error('failed to load the script "' + el.src + '"'); err.event = e || window.event; fn(err); }); } }, {}], 108: [function(require, module, exports) { /** * Module dependencies. */ var onload = require('script-onload'); var tick = require('next-tick'); var type = require('type'); /** * Expose `loadScript`. * * @param {Object} options * @param {Function} fn * @api public */ module.exports = function loadIframe(options, fn){ if (!options) throw new Error('Cant load nothing...'); // Allow for the simplest case, just passing a `src` string. if ('string' == type(options)) options = { src : options }; var https = document.location.protocol === 'https:' || document.location.protocol === 'chrome-extension:'; // If you use protocol relative URLs, third-party scripts like Google // Analytics break when testing with `file:` so this fixes that. if (options.src && options.src.indexOf('//') === 0) { options.src = https ? 'https:' + options.src : 'http:' + options.src; } // Allow them to pass in different URLs depending on the protocol. if (https && options.https) options.src = options.https; else if (!https && options.http) options.src = options.http; // Make the `<iframe>` element and insert it before the first iframe on the // page, which is guaranteed to exist since this Javaiframe is running. var iframe = document.createElement('iframe'); iframe.src = options.src; iframe.width = options.width || 1; iframe.height = options.height || 1; iframe.style.display = 'none'; // If we have a fn, attach event handlers, even in IE. Based off of // the Third-Party Javascript script loading example: // https://github.com/thirdpartyjs/thirdpartyjs-code/blob/master/examples/templates/02/loading-files/index.html if ('function' == type(fn)) { onload(iframe, fn); } tick(function(){ // Append after event listeners are attached for IE. var firstScript = document.getElementsByTagName('script')[0]; firstScript.parentNode.insertBefore(iframe, firstScript); }); // Return the iframe element in case they want to do anything special, like // give it an ID or attributes. return iframe; }; }, {"script-onload":116,"next-tick":104,"type":7}], 109: [function(require, module, exports) { module.exports = { removedProduct: /^[ _]?removed[ _]?product[ _]?$/i, viewedProduct: /^[ _]?viewed[ _]?product[ _]?$/i, viewedProductCategory: /^[ _]?viewed[ _]?product[ _]?category[ _]?$/i, addedProduct: /^[ _]?added[ _]?product[ _]?$/i, completedOrder: /^[ _]?completed[ _]?order[ _]?$/i, startedOrder: /^[ _]?started[ _]?order[ _]?$/i, updatedOrder: /^[ _]?updated[ _]?order[ _]?$/i, refundedOrder: /^[ _]?refunded?[ _]?order[ _]?$/i, viewedProductDetails: /^[ _]?viewed[ _]?product[ _]?details?[ _]?$/i, clickedProduct: /^[ _]?clicked[ _]?product[ _]?$/i, viewedPromotion: /^[ _]?viewed[ _]?promotion?[ _]?$/i, clickedPromotion: /^[ _]?clicked[ _]?promotion?[ _]?$/i, viewedCheckoutStep: /^[ _]?viewed[ _]?checkout[ _]?step[ _]?$/i, completedCheckoutStep: /^[ _]?completed[ _]?checkout[ _]?step[ _]?$/i }; }, {}], 110: [function(require, module, exports) { /** * Expose `toNoCase`. */ module.exports = toNoCase; /** * Test whether a string is camel-case. */ var hasSpace = /\s/; var hasSeparator = /[\W_]/; /** * Remove any starting case from a `string`, like camel or snake, but keep * spaces and punctuation that may be important otherwise. * * @param {String} string * @return {String} */ function toNoCase (string) { if (hasSpace.test(string)) return string.toLowerCase(); if (hasSeparator.test(string)) return unseparate(string).toLowerCase(); return uncamelize(string).toLowerCase(); } /** * Separator splitter. */ var separatorSplitter = /[\W_]+(.|$)/g; /** * Un-separate a `string`. * * @param {String} string * @return {String} */ function unseparate (string) { return string.replace(separatorSplitter, function (m, next) { return next ? ' ' + next : ''; }); } /** * Camelcase splitter. */ var camelSplitter = /(.)([A-Z]+)/g; /** * Un-camelcase a `string`. * * @param {String} string * @return {String} */ function uncamelize (string) { return string.replace(camelSplitter, function (m, previous, uppers) { return previous + ' ' + uppers.toLowerCase().split('').join(' '); }); } }, {}], 111: [function(require, module, exports) { /** * Module dependencies. */ var index = require('indexof'); /** * Expose `Emitter`. */ module.exports = Emitter; /** * Initialize a new `Emitter`. * * @api public */ function Emitter(obj) { if (obj) return mixin(obj); }; /** * Mixin the emitter properties. * * @param {Object} obj * @return {Object} * @api private */ function mixin(obj) { for (var key in Emitter.prototype) { obj[key] = Emitter.prototype[key]; } return obj; } /** * Listen on the given `event` with `fn`. * * @param {String} event * @param {Function} fn * @return {Emitter} * @api public */ Emitter.prototype.on = Emitter.prototype.addEventListener = function(event, fn){ this._callbacks = this._callbacks || {}; (this._callbacks[event] = this._callbacks[event] || []) .push(fn); return this; }; /** * Adds an `event` listener that will be invoked a single * time then automatically removed. * * @param {String} event * @param {Function} fn * @return {Emitter} * @api public */ Emitter.prototype.once = function(event, fn){ var self = this; this._callbacks = this._callbacks || {}; function on() { self.off(event, on); fn.apply(this, arguments); } fn._off = on; this.on(event, on); return this; }; /** * Remove the given callback for `event` or all * registered callbacks. * * @param {String} event * @param {Function} fn * @return {Emitter} * @api public */ Emitter.prototype.off = Emitter.prototype.removeListener = Emitter.prototype.removeAllListeners = Emitter.prototype.removeEventListener = function(event, fn){ this._callbacks = this._callbacks || {}; // all if (0 == arguments.length) { this._callbacks = {}; return this; } // specific event var callbacks = this._callbacks[event]; if (!callbacks) return this; // remove all handlers if (1 == arguments.length) { delete this._callbacks[event]; return this; } // remove specific handler var i = index(callbacks, fn._off || fn); if (~i) callbacks.splice(i, 1); return this; }; /** * Emit `event` with the given args. * * @param {String} event * @param {Mixed} ... * @return {Emitter} */ Emitter.prototype.emit = function(event){ this._callbacks = this._callbacks || {}; var args = [].slice.call(arguments, 1) , callbacks = this._callbacks[event]; if (callbacks) { callbacks = callbacks.slice(0); for (var i = 0, len = callbacks.length; i < len; ++i) { callbacks[i].apply(this, args); } } return this; }; /** * Return array of callbacks for `event`. * * @param {String} event * @return {Array} * @api public */ Emitter.prototype.listeners = function(event){ this._callbacks = this._callbacks || {}; return this._callbacks[event] || []; }; /** * Check if this emitter has `event` handlers. * * @param {String} event * @return {Boolean} * @api public */ Emitter.prototype.hasListeners = function(event){ return !! this.listeners(event).length; }; }, {"indexof":117}], 117: [function(require, module, exports) { module.exports = function(arr, obj){ if (arr.indexOf) return arr.indexOf(obj); for (var i = 0; i < arr.length; ++i) { if (arr[i] === obj) return i; } return -1; }; }, {}], 112: [function(require, module, exports) { module.exports = function after (times, func) { // After 0, really? if (times <= 0) return func(); // That's more like it. return function() { if (--times < 1) { return func.apply(this, arguments); } }; }; }, {}], 113: [function(require, module, exports) { /** * Module dependencies. */ try { var type = require('type'); } catch (err) { var type = require('component-type'); } var toFunction = require('to-function'); /** * HOP reference. */ var has = Object.prototype.hasOwnProperty; /** * Iterate the given `obj` and invoke `fn(val, i)` * in optional context `ctx`. * * @param {String|Array|Object} obj * @param {Function} fn * @param {Object} [ctx] * @api public */ module.exports = function(obj, fn, ctx){ fn = toFunction(fn); ctx = ctx || this; switch (type(obj)) { case 'array': return array(obj, fn, ctx); case 'object': if ('number' == typeof obj.length) return array(obj, fn, ctx); return object(obj, fn, ctx); case 'string': return string(obj, fn, ctx); } }; /** * Iterate string chars. * * @param {String} obj * @param {Function} fn * @param {Object} ctx * @api private */ function string(obj, fn, ctx) { for (var i = 0; i < obj.length; ++i) { fn.call(ctx, obj.charAt(i), i); } } /** * Iterate object keys. * * @param {Object} obj * @param {Function} fn * @param {Object} ctx * @api private */ function object(obj, fn, ctx) { for (var key in obj) { if (has.call(obj, key)) { fn.call(ctx, key, obj[key]); } } } /** * Iterate array-ish. * * @param {Array|Object} obj * @param {Function} fn * @param {Object} ctx * @api private */ function array(obj, fn, ctx) { for (var i = 0; i < obj.length; ++i) { fn.call(ctx, obj[i], i); } } }, {"type":114,"component-type":114,"to-function":118}], 114: [function(require, module, exports) { /** * toString ref. */ var toString = Object.prototype.toString; /** * Return the type of `val`. * * @param {Mixed} val * @return {String} * @api public */ module.exports = function(val){ switch (toString.call(val)) { case '[object Function]': return 'function'; case '[object Date]': return 'date'; case '[object RegExp]': return 'regexp'; case '[object Arguments]': return 'arguments'; case '[object Array]': return 'array'; case '[object String]': return 'string'; } if (val === null) return 'null'; if (val === undefined) return 'undefined'; if (val && val.nodeType === 1) return 'element'; if (val === Object(val)) return 'object'; return typeof val; }; }, {}], 118: [function(require, module, exports) { /** * Module Dependencies */ var expr; try { expr = require('props'); } catch(e) { expr = require('component-props'); } /** * Expose `toFunction()`. */ module.exports = toFunction; /** * Convert `obj` to a `Function`. * * @param {Mixed} obj * @return {Function} * @api private */ function toFunction(obj) { switch ({}.toString.call(obj)) { case '[object Object]': return objectToFunction(obj); case '[object Function]': return obj; case '[object String]': return stringToFunction(obj); case '[object RegExp]': return regexpToFunction(obj); default: return defaultToFunction(obj); } } /** * Default to strict equality. * * @param {Mixed} val * @return {Function} * @api private */ function defaultToFunction(val) { return function(obj){ return val === obj; }; } /** * Convert `re` to a function. * * @param {RegExp} re * @return {Function} * @api private */ function regexpToFunction(re) { return function(obj){ return re.test(obj); }; } /** * Convert property `str` to a function. * * @param {String} str * @return {Function} * @api private */ function stringToFunction(str) { // immediate such as "> 20" if (/^ *\W+/.test(str)) return new Function('_', 'return _ ' + str); // properties such as "name.first" or "age > 18" or "age > 18 && age < 36" return new Function('_', 'return ' + get(str)); } /** * Convert `object` to a function. * * @param {Object} object * @return {Function} * @api private */ function objectToFunction(obj) { var match = {}; for (var key in obj) { match[key] = typeof obj[key] === 'string' ? defaultToFunction(obj[key]) : toFunction(obj[key]); } return function(val){ if (typeof val !== 'object') return false; for (var key in match) { if (!(key in val)) return false; if (!match[key](val[key])) return false; } return true; }; } /** * Built the getter function. Supports getter style functions * * @param {String} str * @return {String} * @api private */ function get(str) { var props = expr(str); if (!props.length) return '_.' + str; var val, i, prop; for (i = 0; i < props.length; i++) { prop = props[i]; val = '_.' + prop; val = "('function' == typeof " + val + " ? " + val + "() : " + val + ")"; // mimic negative lookbehind to avoid problems with nested properties str = stripNested(prop, str, val); } return str; } /** * Mimic negative lookbehind to avoid problems with nested properties. * * See: http://blog.stevenlevithan.com/archives/mimic-lookbehind-javascript * * @param {String} prop * @param {String} str * @param {String} val * @return {String} * @api private */ function stripNested (prop, str, val) { return str.replace(new RegExp('(\\.)?' + prop, 'g'), function($0, $1) { return $1 ? $0 : val; }); } }, {"props":119,"component-props":119}], 119: [function(require, module, exports) { /** * Global Names */ var globals = /\b(this|Array|Date|Object|Math|JSON)\b/g; /** * Return immediate identifiers parsed from `str`. * * @param {String} str * @param {String|Function} map function or prefix * @return {Array} * @api public */ module.exports = function(str, fn){ var p = unique(props(str)); if (fn && 'string' == typeof fn) fn = prefixed(fn); if (fn) return map(str, p, fn); return p; }; /** * Return immediate identifiers in `str`. * * @param {String} str * @return {Array} * @api private */ function props(str) { return str .replace(/\.\w+|\w+ *\(|"[^"]*"|'[^']*'|\/([^/]+)\//g, '') .replace(globals, '') .match(/[$a-zA-Z_]\w*/g) || []; } /** * Return `str` with `props` mapped with `fn`. * * @param {String} str * @param {Array} props * @param {Function} fn * @return {String} * @api private */ function map(str, props, fn) { var re = /\.\w+|\w+ *\(|"[^"]*"|'[^']*'|\/([^/]+)\/|[a-zA-Z_]\w*/g; return str.replace(re, function(_){ if ('(' == _[_.length - 1]) return fn(_); if (!~props.indexOf(_)) return _; return fn(_); }); } /** * Return unique array. * * @param {Array} arr * @return {Array} * @api private */ function unique(arr) { var ret = []; for (var i = 0; i < arr.length; i++) { if (~ret.indexOf(arr[i])) continue; ret.push(arr[i]); } return ret; } /** * Map with prefix `str`. */ function prefixed(str) { return function(_){ return str + _; }; } }, {}], 115: [function(require, module, exports) { /** * toString. */ var toString = window.JSON ? JSON.stringify : function(_){ return String(_); }; /** * Export `fmt` */ module.exports = fmt; /** * Formatters */ fmt.o = toString; fmt.s = String; fmt.d = parseInt; /** * Format the given `str`. * * @param {String} str * @param {...} args * @return {String} * @api public */ function fmt(str){ var args = [].slice.call(arguments, 1); var j = 0; return str.replace(/%([a-z])/gi, function(_, f){ return fmt[f] ? fmt[f](args[j++]) : _ + f; }); } }, {}], 100: [function(require, module, exports) { /** * Generate a slug from the given `str`. * * example: * * generate('foo bar'); * // > foo-bar * * @param {String} str * @param {Object} options * @config {String|RegExp} [replace] characters to replace, defaulted to `/[^a-z0-9]/g` * @config {String} [separator] separator to insert, defaulted to `-` * @return {String} */ module.exports = function (str, options) { options || (options = {}); return str.toLowerCase() .replace(options.replace || /[^a-z0-9]/g, ' ') .replace(/^ +| +$/g, '') .replace(/ +/g, options.separator || '-') }; }, {}], 101: [function(require, module, exports) { /** * Module dependencies. */ var after = require('after'); var domify = require('domify'); var each = require('each'); var Emitter = require('emitter'); /** * Mixin emitter. */ Emitter(exports); /** * Add a new option to the integration by `key` with default `value`. * * @param {String} key * @param {Mixed} value * @return {Integration} */ exports.option = function(key, value){ this.prototype.defaults[key] = value; return this; }; /** * Add a new mapping option. * * This will create a method `name` that will return a mapping * for you to use. * * Example: * * Integration('My Integration') * .mapping('events'); * * new MyIntegration().track('My Event'); * * .track = function(track){ * var events = this.events(track.event()); * each(events, send); * }; * * @param {String} name * @return {Integration} */ exports.mapping = function(name){ this.option(name, []); this.prototype[name] = function(str){ return this.map(this.options[name], str); }; return this; }; /** * Register a new global variable `key` owned by the integration, which will be * used to test whether the integration is already on the page. * * @param {String} global * @return {Integration} */ exports.global = function(key){ this.prototype.globals.push(key); return this; }; /** * Mark the integration as assuming an initial pageview, so to defer loading * the script until the first `page` call, noop the first `initialize`. * * @return {Integration} */ exports.assumesPageview = function(){ this.prototype._assumesPageview = true; return this; }; /** * Mark the integration as being "ready" once `load` is called. * * @return {Integration} */ exports.readyOnLoad = function(){ this.prototype._readyOnLoad = true; return this; }; /** * Mark the integration as being "ready" once `initialize` is called. * * @return {Integration} */ exports.readyOnInitialize = function(){ this.prototype._readyOnInitialize = true; return this; }; /** * Define a tag to be loaded. * * @param {String} str DOM tag as string or URL * @return {Integration} */ exports.tag = function(name, str){ if (null == str) { str = name; name = 'library'; } this.prototype.templates[name] = objectify(str); return this; }; /** * Given a string, give back DOM attributes. * * Do it in a way where the browser doesn't load images or iframes. * It turns out, domify will load images/iframes, because * whenever you construct those DOM elements, * the browser immediately loads them. * * @param {String} str * @return {Object} */ function objectify(str) { // replace `src` with `data-src` to prevent image loading str = str.replace(' src="', ' data-src="'); var el = domify(str); var attrs = {}; each(el.attributes, function(attr){ // then replace it back var name = 'data-src' == attr.name ? 'src' : attr.name; if (!~str.indexOf(attr.name + '=')) return; attrs[name] = attr.value; }); return { type: el.tagName.toLowerCase(), attrs: attrs }; } }, {"after":112,"domify":120,"each":113,"emitter":111}], 120: [function(require, module, exports) { /** * Expose `parse`. */ module.exports = parse; /** * Tests for browser support. */ var div = document.createElement('div'); // Setup div.innerHTML = ' <link/><table></table><a href="/a">a</a><input type="checkbox"/>'; // Make sure that link elements get serialized correctly by innerHTML // This requires a wrapper element in IE var innerHTMLBug = !div.getElementsByTagName('link').length; div = undefined; /** * Wrap map from jquery. */ var map = { legend: [1, '<fieldset>', '</fieldset>'], tr: [2, '<table><tbody>', '</tbody></table>'], col: [2, '<table><tbody></tbody><colgroup>', '</colgroup></table>'], // for script/link/style tags to work in IE6-8, you have to wrap // in a div with a non-whitespace character in front, ha! _default: innerHTMLBug ? [1, 'X<div>', '</div>'] : [0, '', ''] }; map.td = map.th = [3, '<table><tbody><tr>', '</tr></tbody></table>']; map.option = map.optgroup = [1, '<select multiple="multiple">', '</select>']; map.thead = map.tbody = map.colgroup = map.caption = map.tfoot = [1, '<table>', '</table>']; map.polyline = map.ellipse = map.polygon = map.circle = map.text = map.line = map.path = map.rect = map.g = [1, '<svg xmlns="http://www.w3.org/2000/svg" version="1.1">','</svg>']; /** * Parse `html` and return a DOM Node instance, which could be a TextNode, * HTML DOM Node of some kind (<div> for example), or a DocumentFragment * instance, depending on the contents of the `html` string. * * @param {String} html - HTML string to "domify" * @param {Document} doc - The `document` instance to create the Node for * @return {DOMNode} the TextNode, DOM Node, or DocumentFragment instance * @api private */ function parse(html, doc) { if ('string' != typeof html) throw new TypeError('String expected'); // default to the global `document` object if (!doc) doc = document; // tag name var m = /<([\w:]+)/.exec(html); if (!m) return doc.createTextNode(html); html = html.replace(/^\s+|\s+$/g, ''); // Remove leading/trailing whitespace var tag = m[1]; // body support if (tag == 'body') { var el = doc.createElement('html'); el.innerHTML = html; return el.removeChild(el.lastChild); } // wrap map var wrap = map[tag] || map._default; var depth = wrap[0]; var prefix = wrap[1]; var suffix = wrap[2]; var el = doc.createElement('div'); el.innerHTML = prefix + html + suffix; while (depth--) el = el.lastChild; // one element if (el.firstChild == el.lastChild) { return el.removeChild(el.firstChild); } // several elements var fragment = doc.createDocumentFragment(); while (el.firstChild) { fragment.appendChild(el.removeChild(el.firstChild)); } return fragment; } }, {}], 90: [function(require, module, exports) { var toSpace = require('to-space-case'); /** * Expose `toSnakeCase`. */ module.exports = toSnakeCase; /** * Convert a `string` to snake case. * * @param {String} string * @return {String} */ function toSnakeCase (string) { return toSpace(string).replace(/\s/g, '_'); } }, {"to-space-case":121}], 121: [function(require, module, exports) { var clean = require('to-no-case'); /** * Expose `toSpaceCase`. */ module.exports = toSpaceCase; /** * Convert a `string` to space case. * * @param {String} string * @return {String} */ function toSpaceCase (string) { return clean(string).replace(/[\W_]+(.|$)/g, function (matches, match) { return match ? ' ' + match : ''; }); } }, {"to-no-case":122}], 122: [function(require, module, exports) { /** * Expose `toNoCase`. */ module.exports = toNoCase; /** * Test whether a string is camel-case. */ var hasSpace = /\s/; var hasCamel = /[a-z][A-Z]/; var hasSeparator = /[\W_]/; /** * Remove any starting case from a `string`, like camel or snake, but keep * spaces and punctuation that may be important otherwise. * * @param {String} string * @return {String} */ function toNoCase (string) { if (hasSpace.test(string)) return string.toLowerCase(); if (hasSeparator.test(string)) string = unseparate(string); if (hasCamel.test(string)) string = uncamelize(string); return string.toLowerCase(); } /** * Separator splitter. */ var separatorSplitter = /[\W_]+(.|$)/g; /** * Un-separate a `string`. * * @param {String} string * @return {String} */ function unseparate (string) { return string.replace(separatorSplitter, function (m, next) { return next ? ' ' + next : ''; }); } /** * Camelcase splitter. */ var camelSplitter = /(.)([A-Z]+)/g; /** * Un-camelcase a `string`. * * @param {String} string * @return {String} */ function uncamelize (string) { return string.replace(camelSplitter, function (m, previous, uppers) { return previous + ' ' + uppers.toLowerCase().split('').join(' '); }); } }, {}], 91: [function(require, module, exports) { /** * Protocol. */ module.exports = function (url) { switch (arguments.length) { case 0: return check(); case 1: return transform(url); } }; /** * Transform a protocol-relative `url` to the use the proper protocol. * * @param {String} url * @return {String} */ function transform (url) { return check() ? 'https:' + url : 'http:' + url; } /** * Check whether `https:` be used for loading scripts. * * @return {Boolean} */ function check () { return ( location.protocol == 'https:' || location.protocol == 'chrome-extension:' ); } }, {}], 92: [function(require, module, exports) { var isEmpty = require('is-empty'); try { var typeOf = require('type'); } catch (e) { var typeOf = require('component-type'); } /** * Types. */ var types = [ 'arguments', 'array', 'boolean', 'date', 'element', 'function', 'null', 'number', 'object', 'regexp', 'string', 'undefined' ]; /** * Expose type checkers. * * @param {Mixed} value * @return {Boolean} */ for (var i = 0, type; type = types[i]; i++) exports[type] = generate(type); /** * Add alias for `function` for old browsers. */ exports.fn = exports['function']; /** * Expose `empty` check. */ exports.empty = isEmpty; /** * Expose `nan` check. */ exports.nan = function (val) { return exports.number(val) && val != val; }; /** * Generate a type checker. * * @param {String} type * @return {Function} */ function generate (type) { return function (value) { return type === typeOf(value); }; } }, {"is-empty":123,"type":7,"component-type":7}], 123: [function(require, module, exports) { /** * Expose `isEmpty`. */ module.exports = isEmpty; /** * Has. */ var has = Object.prototype.hasOwnProperty; /** * Test whether a value is "empty". * * @param {Mixed} val * @return {Boolean} */ function isEmpty (val) { if (null == val) return true; if ('number' == typeof val) return 0 === val; if (undefined !== val.length) return 0 === val.length; for (var key in val) if (has.call(val, key)) return false; return true; } }, {}], 93: [function(require, module, exports) { var identity = function(_){ return _; }; /** * Module exports, export */ module.exports = multiple(find); module.exports.find = module.exports; /** * Export the replacement function, return the modified object */ module.exports.replace = function (obj, key, val, options) { multiple(replace).call(this, obj, key, val, options); return obj; }; /** * Export the delete function, return the modified object */ module.exports.del = function (obj, key, options) { multiple(del).call(this, obj, key, null, options); return obj; }; /** * Compose applying the function to a nested key */ function multiple (fn) { return function (obj, path, val, options) { var normalize = options && isFunction(options.normalizer) ? options.normalizer : defaultNormalize; path = normalize(path); var key; var finished = false; while (!finished) loop(); function loop() { for (key in obj) { var normalizedKey = normalize(key); if (0 === path.indexOf(normalizedKey)) { var temp = path.substr(normalizedKey.length); if (temp.charAt(0) === '.' || temp.length === 0) { path = temp.substr(1); var child = obj[key]; // we're at the end and there is nothing. if (null == child) { finished = true; return; } // we're at the end and there is something. if (!path.length) { finished = true; return; } // step into child obj = child; // but we're done here return; } } } key = undefined; // if we found no matching properties // on the current object, there's no match. finished = true; } if (!key) return; if (null == obj) return obj; // the `obj` and `key` is one above the leaf object and key, so // start object: { a: { 'b.c': 10 } } // end object: { 'b.c': 10 } // end key: 'b.c' // this way, you can do `obj[key]` and get `10`. return fn(obj, key, val); }; } /** * Find an object by its key * * find({ first_name : 'Calvin' }, 'firstName') */ function find (obj, key) { if (obj.hasOwnProperty(key)) return obj[key]; } /** * Delete a value for a given key * * del({ a : 'b', x : 'y' }, 'X' }) -> { a : 'b' } */ function del (obj, key) { if (obj.hasOwnProperty(key)) delete obj[key]; return obj; } /** * Replace an objects existing value with a new one * * replace({ a : 'b' }, 'a', 'c') -> { a : 'c' } */ function replace (obj, key, val) { if (obj.hasOwnProperty(key)) obj[key] = val; return obj; } /** * Normalize a `dot.separated.path`. * * A.HELL(!*&#(!)O_WOR LD.bar => ahelloworldbar * * @param {String} path * @return {String} */ function defaultNormalize(path) { return path.replace(/[^a-zA-Z0-9\.]+/g, '').toLowerCase(); } /** * Check if a value is a function. * * @param {*} val * @return {boolean} Returns `true` if `val` is a function, otherwise `false`. */ function isFunction(val) { return typeof val === 'function'; } }, {}], 9: [function(require, module, exports) { /** * Module dependencies. */ var integration = require('analytics.js-integration'); var domify = require('domify'); var each = require('each'); /** * HOP */ var has = Object.prototype.hasOwnProperty; /** * Expose `AdWords`. */ var AdWords = module.exports = integration('AdWords') .option('conversionId', '') .option('remarketing', false) .tag('<script src="//www.googleadservices.com/pagead/conversion_async.js">') .mapping('events'); /** * Load. * * @param {Function} fn * @api public */ AdWords.prototype.initialize = function(){ this.load(this.ready); }; /** * Loaded. * * @return {Boolean} * @api public */ AdWords.prototype.loaded = function(){ return !! document.body; }; /** * Page. * * https://support.google.com/adwords/answer/3111920#standard_parameters * https://support.google.com/adwords/answer/3103357 * https://developers.google.com/adwords-remarketing-tag/asynchronous/ * https://developers.google.com/adwords-remarketing-tag/parameters * * @param {Page} page */ AdWords.prototype.page = function(page){ var remarketing = !!this.options.remarketing; var id = this.options.conversionId; var props = {}; window.google_trackConversion({ google_conversion_id: id, google_custom_params: props, google_remarketing_only: remarketing }); }; /** * Track. * * @param {Track} * @api public */ AdWords.prototype.track = function(track){ var id = this.options.conversionId; var events = this.events(track.event()); var revenue = track.revenue() || 0; each(events, function(label){ var props = track.properties(); delete props.revenue window.google_trackConversion({ google_conversion_id: id, google_custom_params: props, google_conversion_language: 'en', google_conversion_format: '3', google_conversion_color: 'ffffff', google_conversion_label: label, google_conversion_value: revenue, google_remarketing_only: false }); }); }; }, {"analytics.js-integration":89,"domify":120,"each":4}], 10: [function(require, module, exports) { /** * Module dependencies. */ var integration = require('analytics.js-integration'); /** * Expose Alexa integration. */ var Alexa = module.exports = integration('Alexa') .assumesPageview() .global('_atrk_opts') .option('account', null) .option('domain', '') .option('dynamic', true) .tag('<script src="//d31qbv1cthcecs.cloudfront.net/atrk.js">'); /** * Initialize. * * @param {Object} page */ Alexa.prototype.initialize = function(page){ var self = this; window._atrk_opts = { atrk_acct: this.options.account, domain: this.options.domain, dynamic: this.options.dynamic }; this.load(function(){ window.atrk(); self.ready(); }); }; /** * Loaded? * * @return {Boolean} */ Alexa.prototype.loaded = function(){ return !! window.atrk; }; }, {"analytics.js-integration":89}], 11: [function(require, module, exports) { /** * Module dependencies. */ var integration = require('analytics.js-integration'); var utm = require('utm-params'); var top = require('top-domain'); /** * UMD ? */ var umd = 'function' == typeof define && define.amd; /** * Source. */ var src = '//d24n15hnbwhuhn.cloudfront.net/libs/amplitude-2.1.0-min.js'; /** * Expose `Amplitude` integration. */ var Amplitude = module.exports = integration('Amplitude') .global('amplitude') .option('apiKey', '') .option('trackAllPages', false) .option('trackNamedPages', true) .option('trackCategorizedPages', true) .option('trackUtmProperties', true) .tag('<script src="' + src + '">'); /** * Initialize. * * https://github.com/amplitude/Amplitude-Javascript * * @param {Object} page */ Amplitude.prototype.initialize = function(page){ // jscs:disable (function(e,t){var r=e.amplitude||{};r._q=[];function a(e){r[e]=function(){r._q.push([e].concat(Array.prototype.slice.call(arguments,0)))}}var i=["init","logEvent","logRevenue","setUserId","setUserProperties","setOptOut","setVersionName","setDomain","setDeviceId","setGlobalUserProperties"];for(var o=0;o<i.length;o++){a(i[o])}e.amplitude=r})(window,document); // jscs:enable this.setDomain(window.location.href); window.amplitude.init(this.options.apiKey, null, { includeUtm: this.options.trackUtmProperties }); var self = this; if (umd) { window.require([src], function(amplitude){ window.amplitude = amplitude; self.ready(); }); return; } this.load(function(){ self.ready(); }); }; /** * Loaded? * * @return {Boolean} */ Amplitude.prototype.loaded = function(){ return !! (window.amplitude && window.amplitude.options); }; /** * Page. * * @param {Page} page */ Amplitude.prototype.page = function(page){ var properties = page.properties(); var category = page.category(); var name = page.fullName(); var opts = this.options; // all pages if (opts.trackAllPages) { this.track(page.track()); } // categorized pages if (category && opts.trackCategorizedPages) { this.track(page.track(category)); } // named pages if (name && opts.trackNamedPages) { this.track(page.track(name)); } }; /** * Identify. * * @param {Facade} identify */ Amplitude.prototype.identify = function(identify){ var id = identify.userId(); var traits = identify.traits(); if (id) window.amplitude.setUserId(id); if (traits) window.amplitude.setUserProperties(traits); }; /** * Track. * * @param {Track} event */ Amplitude.prototype.track = function(track){ var props = track.properties(); var event = track.event(); var revenue = track.revenue(); // track the event window.amplitude.logEvent(event, props); // also track revenue if (revenue) { window.amplitude.logRevenue(revenue, props.quantity, props.productId); } }; /** * Set domain name to root domain * * @param {String} href */ Amplitude.prototype.setDomain = function(href){ var domain = top(href); window.amplitude.setDomain(domain); }; /** * Override device ID * * @param {String} deviceId */ Amplitude.prototype.setDeviceId = function(deviceId){ if (deviceId) window.amplitude.setDeviceId(deviceId); }; }, {"analytics.js-integration":89,"utm-params":124,"top-domain":125}], 124: [function(require, module, exports) { /** * Module dependencies. */ var parse = require('querystring').parse; /** * Expose `utm` */ module.exports = utm; /** * Get all utm params from the given `querystring` * * @param {String} query * @return {Object} * @api private */ function utm(query){ if ('?' == query.charAt(0)) query = query.substring(1); var query = query.replace(/\?/g, '&'); var params = parse(query); var param; var ret = {}; for (var key in params) { if (~key.indexOf('utm_')) { param = key.substr(4); if ('campaign' == param) param = 'name'; ret[param] = params[key]; } } return ret; } }, {"querystring":126}], 126: [function(require, module, exports) { /** * Module dependencies. */ var encode = encodeURIComponent; var decode = decodeURIComponent; var trim = require('trim'); var type = require('type'); var pattern = /(\w+)\[(\d+)\]/ /** * Parse the given query `str`. * * @param {String} str * @return {Object} * @api public */ exports.parse = function(str){ if ('string' != typeof str) return {}; str = trim(str); if ('' == str) return {}; if ('?' == str.charAt(0)) str = str.slice(1); var obj = {}; var pairs = str.split('&'); for (var i = 0; i < pairs.length; i++) { var parts = pairs[i].split('='); var key = decode(parts[0]); var m; if (m = pattern.exec(key)) { obj[m[1]] = obj[m[1]] || []; obj[m[1]][m[2]] = decode(parts[1]); continue; } obj[parts[0]] = null == parts[1] ? '' : decode(parts[1]); } return obj; }; /** * Stringify the given `obj`. * * @param {Object} obj * @return {String} * @api public */ exports.stringify = function(obj){ if (!obj) return ''; var pairs = []; for (var key in obj) { var value = obj[key]; if ('array' == type(value)) { for (var i = 0; i < value.length; ++i) { pairs.push(encode(key + '[' + i + ']') + '=' + encode(value[i])); } continue; } pairs.push(encode(key) + '=' + encode(obj[key])); } return pairs.join('&'); }; }, {"trim":127,"type":7}], 127: [function(require, module, exports) { exports = module.exports = trim; function trim(str){ if (str.trim) return str.trim(); return str.replace(/^\s*|\s*$/g, ''); } exports.left = function(str){ if (str.trimLeft) return str.trimLeft(); return str.replace(/^\s*/, ''); }; exports.right = function(str){ if (str.trimRight) return str.trimRight(); return str.replace(/\s*$/, ''); }; }, {}], 125: [function(require, module, exports) { /** * Module dependencies. */ var parse = require('url').parse; /** * Expose `domain` */ module.exports = domain; /** * RegExp */ var regexp = /[a-z0-9][a-z0-9\-]*[a-z0-9]\.[a-z\.]{2,6}$/i; /** * Get the top domain. * * Official Grammar: http://tools.ietf.org/html/rfc883#page-56 * Look for tlds with up to 2-6 characters. * * Example: * * domain('http://localhost:3000/baz'); * // => '' * domain('http://dev:3000/baz'); * // => '' * domain('http://127.0.0.1:3000/baz'); * // => '' * domain('http://segment.io/baz'); * // => 'segment.io' * * @param {String} url * @return {String} * @api public */ function domain(url){ var host = parse(url).hostname; var match = host.match(regexp); return match ? match[0] : ''; }; }, {"url":128}], 128: [function(require, module, exports) { /** * Parse the given `url`. * * @param {String} str * @return {Object} * @api public */ exports.parse = function(url){ var a = document.createElement('a'); a.href = url; return { href: a.href, host: a.host || location.host, port: ('0' === a.port || '' === a.port) ? port(a.protocol) : a.port, hash: a.hash, hostname: a.hostname || location.hostname, pathname: a.pathname.charAt(0) != '/' ? '/' + a.pathname : a.pathname, protocol: !a.protocol || ':' == a.protocol ? location.protocol : a.protocol, search: a.search, query: a.search.slice(1) }; }; /** * Check if `url` is absolute. * * @param {String} url * @return {Boolean} * @api public */ exports.isAbsolute = function(url){ return 0 == url.indexOf('//') || !!~url.indexOf('://'); }; /** * Check if `url` is relative. * * @param {String} url * @return {Boolean} * @api public */ exports.isRelative = function(url){ return !exports.isAbsolute(url); }; /** * Check if `url` is cross domain. * * @param {String} url * @return {Boolean} * @api public */ exports.isCrossDomain = function(url){ url = exports.parse(url); var location = exports.parse(window.location.href); return url.hostname !== location.hostname || url.port !== location.port || url.protocol !== location.protocol; }; /** * Return default port for `protocol`. * * @param {String} protocol * @return {String} * @api private */ function port (protocol){ switch (protocol) { case 'http:': return 80; case 'https:': return 443; default: return location.port; } } }, {}], 12: [function(require, module, exports) { /** * Module dependencies. */ var integration = require('analytics.js-integration'); var load = require('load-script'); var is = require('is'); /** * Expose plugin. */ module.exports = exports = function(analytics){ analytics.addIntegration(Appcues); }; /** * Expose `Appcues` integration. */ var Appcues = exports.Integration = integration('Appcues') .assumesPageview() .global('Appcues') .option('appcuesId', ''); /** * Initialize. * * http://appcues.com/docs/ * * @param {Object} */ Appcues.prototype.initialize = function(){ this.load(this.ready); }; /** * Loaded? * * @return {Boolean} */ Appcues.prototype.loaded = function(){ return is.object(window.Appcues); }; /** * Load the Appcues library. * * @param {Function} callback */ Appcues.prototype.load = function(callback){ var id = this.options.appcuesId || 'appcues'; var script = load('//fast.appcues.com/' + id + '.js', callback); }; /** * Identify. * * http://appcues.com/docs#identify * * @param {Identify} identify */ Appcues.prototype.identify = function(identify){ window.Appcues.identify(identify.userId(), identify.traits()); }; }, {"analytics.js-integration":89,"load-script":129,"is":92}], 129: [function(require, module, exports) { /** * Module dependencies. */ var onload = require('script-onload'); var tick = require('next-tick'); var type = require('type'); /** * Expose `loadScript`. * * @param {Object} options * @param {Function} fn * @api public */ module.exports = function loadScript(options, fn){ if (!options) throw new Error('Cant load nothing...'); // Allow for the simplest case, just passing a `src` string. if ('string' == type(options)) options = { src : options }; var https = document.location.protocol === 'https:' || document.location.protocol === 'chrome-extension:'; // If you use protocol relative URLs, third-party scripts like Google // Analytics break when testing with `file:` so this fixes that. if (options.src && options.src.indexOf('//') === 0) { options.src = https ? 'https:' + options.src : 'http:' + options.src; } // Allow them to pass in different URLs depending on the protocol. if (https && options.https) options.src = options.https; else if (!https && options.http) options.src = options.http; // Make the `<script>` element and insert it before the first script on the // page, which is guaranteed to exist since this Javascript is running. var script = document.createElement('script'); script.type = 'text/javascript'; script.async = true; script.src = options.src; // If we have a fn, attach event handlers, even in IE. Based off of // the Third-Party Javascript script loading example: // https://github.com/thirdpartyjs/thirdpartyjs-code/blob/master/examples/templates/02/loading-files/index.html if ('function' == type(fn)) { onload(script, fn); } tick(function(){ // Append after event listeners are attached for IE. var firstScript = document.getElementsByTagName('script')[0]; firstScript.parentNode.insertBefore(script, firstScript); }); // Return the script element in case they want to do anything special, like // give it an ID or attributes. return script; }; }, {"script-onload":116,"next-tick":104,"type":7}], 13: [function(require, module, exports) { /** * Module dependencies. */ var integration = require('analytics.js-integration'); var is = require('is'); /** * Expose `Atatus` integration. */ var Atatus = module.exports = integration('Atatus') .global('atatus') .option('apiKey', '') .tag('<script src="//www.atatus.com/atatus.js">'); /** * Initialize. * * https://www.atatus.com/docs.html * * @param {Object} page */ Atatus.prototype.initialize = function(page){ var self = this; this.load(function(){ // Configure Atatus and install default handler to capture uncaught exceptions window.atatus.config(self.options.apiKey).install(); self.ready(); }); }; /** * Loaded? * * @return {Boolean} */ Atatus.prototype.loaded = function(){ return is.object(window.atatus); }; /** * Identify. * * @param {Identify} identify */ Atatus.prototype.identify = function(identify){ window.atatus.setCustomData({ person: identify.traits() }); }; }, {"analytics.js-integration":89,"is":92}], 14: [function(require, module, exports) { /** * Module dependencies. */ var integration = require('analytics.js-integration'); /** * Expose `Autosend` integration. */ var Autosend = module.exports = integration('Autosend') .global('_autosend') .option('appKey', '') .tag('<script id="asnd-tracker" src="https://d2zjxodm1cz8d6.cloudfront.net/js/v1/autosend.js" data-auth-key="{{ appKey }}">'); /** * Initialize. * * http://autosend.io/faq/install-autosend-using-javascript/ * * @param {Object} page */ Autosend.prototype.initialize = function(page){ window._autosend = window._autosend || []; (function(){var a,b,c;a=function(f){return function(){window._autosend.push([f].concat(Array.prototype.slice.call(arguments,0))); }; }; b=["identify", "track", "cb"];for (c=0;c<b.length;c++){window._autosend[b[c]]=a(b[c]); } })(); this.load(this.ready); }; /** * Loaded? * * @return {Boolean} */ Autosend.prototype.loaded = function(){ return !! (window._autosend); }; /** * Identify. * * http://autosend.io/faq/install-autosend-using-javascript/ * * @param {Identify} identify */ Autosend.prototype.identify = function(identify){ var id = identify.userId(); if (!id) return; var traits = identify.traits(); traits.id = id; window._autosend.identify(traits); }; /** * Track. * * http://autosend.io/faq/install-autosend-using-javascript/ * * @param {Track} track */ Autosend.prototype.track = function(track){ window._autosend.track(track.event()); }; }, {"analytics.js-integration":89}], 15: [function(require, module, exports) { /** * Module dependencies. */ var integration = require('analytics.js-integration'); var each = require('each'); /** * Expose `Awesm` integration. */ var Awesm = module.exports = integration('awe.sm') .assumesPageview() .global('AWESM') .option('apiKey', '') .tag('<script src="//widgets.awe.sm/v3/widgets.js?key={{ apiKey }}&async=true">') .mapping('events'); /** * Initialize. * * http://developers.awe.sm/guides/javascript/ * * @param {Object} page */ Awesm.prototype.initialize = function(page){ window.AWESM = { api_key: this.options.apiKey }; this.load(this.ready); }; /** * Loaded? * * @return {Boolean} */ Awesm.prototype.loaded = function(){ return !! (window.AWESM && window.AWESM._exists); }; /** * Track. * * @param {Track} track */ Awesm.prototype.track = function(track){ var user = this.analytics.user(); var goals = this.events(track.event()); each(goals, function(goal){ window.AWESM.convert(goal, track.cents(), null, user.id()); }); }; }, {"analytics.js-integration":89,"each":4}], 16: [function(require, module, exports) { /** * Module dependencies. */ var integration = require('analytics.js-integration'); var onbody = require('on-body'); var domify = require('domify'); var extend = require('extend'); var bind = require('bind'); var when = require('when'); var each = require('each'); /** * HOP. */ var has = Object.prototype.hasOwnProperty; /** * Noop. */ var noop = function(){}; /** * Expose `Bing`. * * https://bingads.microsoft.com/campaign/signup */ var Bing = module.exports = integration('Bing Ads') .global('uetq') .option('tagId', '') .tag('<script src="//bat.bing.com/bat.js">'); /** * Initialize * * inferred from their snippet * https://gist.github.com/sperand-io/8bef4207e9c66e1aa83b */ Bing.prototype.initialize = function(){ window.uetq = window.uetq || []; var self = this; self.load(function(){ var setup = { ti: self.options.tagId, q: window.uetq }; window.uetq = new UET(setup); self.ready(); }); }; /** * Loaded? * * Check for custom `push` method bestowed by UET constructor * * @return {Boolean} */ Bing.prototype.loaded = function(){ return !! (window.uetq && window.uetq.push !== Array.prototype.push); }; /** * Page */ Bing.prototype.page = function(){ window.uetq.push("pageLoad"); }; /** * Track * * Send all events then set goals based * on them retroactively: http://advertise.bingads.microsoft.com/en-us/uahelp-topic?market=en&project=Bing_Ads&querytype=topic&query=HLP_BA_PROC_UET.htm * * @param {Track} track */ Bing.prototype.track = function(track){ var event = { ea: 'track', el: track.event() }; if (track.category()) event.ec = track.category(); if (track.revenue()) event.ev = track.revenue(); window.uetq.push(event); }; }, {"analytics.js-integration":89,"on-body":130,"domify":120,"extend":131,"bind":102,"when":132,"each":4}], 130: [function(require, module, exports) { var each = require('each'); /** * Cache whether `<body>` exists. */ var body = false; /** * Callbacks to call when the body exists. */ var callbacks = []; /** * Export a way to add handlers to be invoked once the body exists. * * @param {Function} callback A function to call when the body exists. */ module.exports = function onBody (callback) { if (body) { call(callback); } else { callbacks.push(callback); } }; /** * Set an interval to check for `document.body`. */ var interval = setInterval(function () { if (!document.body) return; body = true; each(callbacks, call); clearInterval(interval); }, 5); /** * Call a callback, passing it the body. * * @param {Function} callback The callback to call. */ function call (callback) { callback(document.body); } }, {"each":113}], 131: [function(require, module, exports) { module.exports = function extend (object) { // Takes an unlimited number of extenders. var args = Array.prototype.slice.call(arguments, 1); // For each extender, copy their properties on our object. for (var i = 0, source; source = args[i]; i++) { if (!source) continue; for (var property in source) { object[property] = source[property]; } } return object; }; }, {}], 132: [function(require, module, exports) { var callback = require('callback'); /** * Expose `when`. */ module.exports = when; /** * Loop on a short interval until `condition()` is true, then call `fn`. * * @param {Function} condition * @param {Function} fn * @param {Number} interval (optional) */ function when (condition, fn, interval) { if (condition()) return callback.async(fn); var ref = setInterval(function () { if (!condition()) return; callback(fn); clearInterval(ref); }, interval || 10); } }, {"callback":95}], 17: [function(require, module, exports) { /** * Module dependencies. */ var integration = require('analytics.js-integration'); /** * Expose `Blueshift` integration. */ var Blueshift = module.exports = integration('Blueshift') .global('blueshift') .global('_blueshiftid') .option('apiKey', '') .option('retarget', false) .tag('<script src="https://cdn.getblueshift.com/blueshift.js">'); /** * Initialize. * * Documentation: http://getblueshift.com/documentation * * @param {Object} page */ Blueshift.prototype.initialize = function(page){ window.blueshift=window.blueshift||[]; // jscs:disable window.blueshift.load=function(a){window._blueshiftid=a;var d=function(a){return function(){blueshift.push([a].concat(Array.prototype.slice.call(arguments,0)))}},e=["identify","track","click", "pageload", "capture", "retarget"];for(var f=0;f<e.length;f++)blueshift[e[f]]=d(e[f])}; // jscs:enable window.blueshift.load(this.options.apiKey); this.load(this.ready); }; /** * Loaded? * * @return {Boolean} */ Blueshift.prototype.loaded = function(){ return !! (window.blueshift && window._blueshiftid); }; /** * Page. * * @param {Page} page */ Blueshift.prototype.page = function(page){ if (this.options.retarget) window.blueshift.retarget(); var properties = page.properties(); properties._bsft_source = 'segment.com'; window.blueshift.pageload(properties); }; /** * Identify. * * @param {Identify} identify */ Blueshift.prototype.identify = function(identify){ if (!identify.userId()) return this.debug('user id required'); var traits = identify.traits({ created: 'created_at' }); traits._bsft_source = 'segment.com'; window.blueshift.identify(traits); }; /** * Group. * * @param {Group} group */ Blueshift.prototype.group = function(group){ var traits = group.traits({ created: 'created_at' }); traits._bsft_source = 'segment.com'; window.blueshift.track('group', traits); }; /** * Track. * * @param {Track} track */ Blueshift.prototype.track = function(track){ var properties = track.properties(); properties._bsft_source = 'segment.com'; window.blueshift.track(track.event(), properties); }; }, {"analytics.js-integration":89}], 18: [function(require, module, exports) { /** * Module dependencies. */ var integration = require('analytics.js-integration'); var Identify = require('facade').Identify; var Track = require('facade').Track; var pixel = require('load-pixel')('http://app.bronto.com/public/'); var qs = require('querystring'); var each = require('each'); /** * Expose `Bronto` integration. */ var Bronto = module.exports = integration('Bronto') .global('__bta') .option('siteId', '') .option('host', '') .tag('<script src="//p.bm23.com/bta.js">'); /** * Initialize. * * http://app.bronto.com/mail/help/help_view/?k=mail:home:api_tracking:tracking_data_store_js#addingjavascriptconversiontrackingtoyoursite * http://bronto.com/product-blog/features/using-conversion-tracking-private-domain#.Ut_Vk2T8KqB * http://bronto.com/product-blog/features/javascript-conversion-tracking-setup-and-reporting#.Ut_VhmT8KqB * * @param {Object} page */ Bronto.prototype.initialize = function(page){ var self = this; var params = qs.parse(window.location.search); if (!params._bta_tid && !params._bta_c) { this.debug('missing tracking URL parameters `_bta_tid` and `_bta_c`.'); } this.load(function(){ var opts = self.options; self.bta = new window.__bta(opts.siteId); if (opts.host) self.bta.setHost(opts.host); self.ready(); }); }; /** * Loaded? * * @return {Boolean} */ Bronto.prototype.loaded = function(){ return this.bta; }; /** * Completed order. * * The cookie is used to link the order being processed back to the delivery, * message, and contact which makes it a conversion. * Passing in just the email ensures that the order itself * gets linked to the contact record in Bronto even if the user * does not have a tracking cookie. * * @param {Track} track * @api private */ Bronto.prototype.completedOrder = function(track){ var user = this.analytics.user(); var products = track.products(); var props = track.properties(); var items = []; var identify = new Identify({ userId: user.id(), traits: user.traits() }); var email = identify.email(); // items each(products, function(product){ var track = new Track({ properties: product }); items.push({ item_id: track.id() || track.sku(), desc: product.description || track.name(), quantity: track.quantity(), amount: track.price(), }); }); // add conversion this.bta.addOrder({ order_id: track.orderId(), email: email, // they recommend not putting in a date // because it needs to be formatted correctly // YYYY-MM-DDTHH:MM:SS items: items }); }; }, {"analytics.js-integration":89,"facade":133,"load-pixel":134,"querystring":135,"each":4}], 133: [function(require, module, exports) { var Facade = require('./facade'); /** * Expose `Facade` facade. */ module.exports = Facade; /** * Expose specific-method facades. */ Facade.Alias = require('./alias'); Facade.Group = require('./group'); Facade.Identify = require('./identify'); Facade.Track = require('./track'); Facade.Page = require('./page'); Facade.Screen = require('./screen'); }, {"./facade":136,"./alias":137,"./group":138,"./identify":139,"./track":140,"./page":141,"./screen":142}], 136: [function(require, module, exports) { var traverse = require('isodate-traverse'); var isEnabled = require('./is-enabled'); var clone = require('./utils').clone; var type = require('./utils').type; var address = require('./address'); var objCase = require('obj-case'); var newDate = require('new-date'); /** * Expose `Facade`. */ module.exports = Facade; /** * Initialize a new `Facade` with an `obj` of arguments. * * @param {Object} obj */ function Facade (obj) { if (!obj.hasOwnProperty('timestamp')) obj.timestamp = new Date(); else obj.timestamp = newDate(obj.timestamp); traverse(obj); this.obj = obj; } /** * Mixin address traits. */ address(Facade.prototype); /** * Return a proxy function for a `field` that will attempt to first use methods, * and fallback to accessing the underlying object directly. You can specify * deeply nested fields too like: * * this.proxy('options.Librato'); * * @param {String} field */ Facade.prototype.proxy = function (field) { var fields = field.split('.'); field = fields.shift(); // Call a function at the beginning to take advantage of facaded fields var obj = this[field] || this.field(field); if (!obj) return obj; if (typeof obj === 'function') obj = obj.call(this) || {}; if (fields.length === 0) return transform(obj); obj = objCase(obj, fields.join('.')); return transform(obj); }; /** * Directly access a specific `field` from the underlying object, returning a * clone so outsiders don't mess with stuff. * * @param {String} field * @return {Mixed} */ Facade.prototype.field = function (field) { var obj = this.obj[field]; return transform(obj); }; /** * Utility method to always proxy a particular `field`. You can specify deeply * nested fields too like: * * Facade.proxy('options.Librato'); * * @param {String} field * @return {Function} */ Facade.proxy = function (field) { return function () { return this.proxy(field); }; }; /** * Utility method to directly access a `field`. * * @param {String} field * @return {Function} */ Facade.field = function (field) { return function () { return this.field(field); }; }; /** * Proxy multiple `path`. * * @param {String} path * @return {Array} */ Facade.multi = function(path){ return function(){ var multi = this.proxy(path + 's'); if ('array' == type(multi)) return multi; var one = this.proxy(path); if (one) one = [clone(one)]; return one || []; }; }; /** * Proxy one `path`. * * @param {String} path * @return {Mixed} */ Facade.one = function(path){ return function(){ var one = this.proxy(path); if (one) return one; var multi = this.proxy(path + 's'); if ('array' == type(multi)) return multi[0]; }; }; /** * Get the basic json object of this facade. * * @return {Object} */ Facade.prototype.json = function () { var ret = clone(this.obj); if (this.type) ret.type = this.type(); return ret; }; /** * Get the options of a call (formerly called "context"). If you pass an * integration name, it will get the options for that specific integration, or * undefined if the integration is not enabled. * * @param {String} integration (optional) * @return {Object or Null} */ Facade.prototype.context = Facade.prototype.options = function (integration) { var options = clone(this.obj.options || this.obj.context) || {}; if (!integration) return clone(options); if (!this.enabled(integration)) return; var integrations = this.integrations(); var value = integrations[integration] || objCase(integrations, integration); if ('boolean' == typeof value) value = {}; return value || {}; }; /** * Check whether an integration is enabled. * * @param {String} integration * @return {Boolean} */ Facade.prototype.enabled = function (integration) { var allEnabled = this.proxy('options.providers.all'); if (typeof allEnabled !== 'boolean') allEnabled = this.proxy('options.all'); if (typeof allEnabled !== 'boolean') allEnabled = this.proxy('integrations.all'); if (typeof allEnabled !== 'boolean') allEnabled = true; var enabled = allEnabled && isEnabled(integration); var options = this.integrations(); // If the integration is explicitly enabled or disabled, use that // First, check options.providers for backwards compatibility if (options.providers && options.providers.hasOwnProperty(integration)) { enabled = options.providers[integration]; } // Next, check for the integration's existence in 'options' to enable it. // If the settings are a boolean, use that, otherwise it should be enabled. if (options.hasOwnProperty(integration)) { var settings = options[integration]; if (typeof settings === 'boolean') { enabled = settings; } else { enabled = true; } } return enabled ? true : false; }; /** * Get all `integration` options. * * @param {String} integration * @return {Object} * @api private */ Facade.prototype.integrations = function(){ return this.obj.integrations || this.proxy('options.providers') || this.options(); }; /** * Check whether the user is active. * * @return {Boolean} */ Facade.prototype.active = function () { var active = this.proxy('options.active'); if (active === null || active === undefined) active = true; return active; }; /** * Get `sessionId / anonymousId`. * * @return {Mixed} * @api public */ Facade.prototype.sessionId = Facade.prototype.anonymousId = function(){ return this.field('anonymousId') || this.field('sessionId'); }; /** * Get `groupId` from `context.groupId`. * * @return {String} * @api public */ Facade.prototype.groupId = Facade.proxy('options.groupId'); /** * Get the call's "super properties" which are just traits that have been * passed in as if from an identify call. * * @param {Object} aliases * @return {Object} */ Facade.prototype.traits = function (aliases) { var ret = this.proxy('options.traits') || {}; var id = this.userId(); aliases = aliases || {}; if (id) ret.id = id; for (var alias in aliases) { var value = null == this[alias] ? this.proxy('options.traits.' + alias) : this[alias](); if (null == value) continue; ret[aliases[alias]] = value; delete ret[alias]; } return ret; }; /** * Add a convenient way to get the library name and version */ Facade.prototype.library = function(){ var library = this.proxy('options.library'); if (!library) return { name: 'unknown', version: null }; if (typeof library === 'string') return { name: library, version: null }; return library; }; /** * Setup some basic proxies. */ Facade.prototype.userId = Facade.field('userId'); Facade.prototype.channel = Facade.field('channel'); Facade.prototype.timestamp = Facade.field('timestamp'); Facade.prototype.userAgent = Facade.proxy('options.userAgent'); Facade.prototype.ip = Facade.proxy('options.ip'); /** * Return the cloned and traversed object * * @param {Mixed} obj * @return {Mixed} */ function transform(obj){ var cloned = clone(obj); return cloned; } }, {"isodate-traverse":143,"./is-enabled":144,"./utils":145,"./address":146,"obj-case":93,"new-date":147}], 143: [function(require, module, exports) { var is = require('is'); var isodate = require('isodate'); var each; try { each = require('each'); } catch (err) { each = require('each-component'); } /** * Expose `traverse`. */ module.exports = traverse; /** * Traverse an object or array, and return a clone with all ISO strings parsed * into Date objects. * * @param {Object} obj * @return {Object} */ function traverse (input, strict) { if (strict === undefined) strict = true; if (is.object(input)) return object(input, strict); if (is.array(input)) return array(input, strict); return input; } /** * Object traverser. * * @param {Object} obj * @param {Boolean} strict * @return {Object} */ function object (obj, strict) { each(obj, function (key, val) { if (isodate.is(val, strict)) { obj[key] = isodate.parse(val); } else if (is.object(val) || is.array(val)) { traverse(val, strict); } }); return obj; } /** * Array traverser. * * @param {Array} arr * @param {Boolean} strict * @return {Array} */ function array (arr, strict) { each(arr, function (val, x) { if (is.object(val)) { traverse(val, strict); } else if (isodate.is(val, strict)) { arr[x] = isodate.parse(val); } }); return arr; } }, {"is":148,"isodate":149,"each":4}], 148: [function(require, module, exports) { var isEmpty = require('is-empty'); try { var typeOf = require('type'); } catch (e) { var typeOf = require('component-type'); } /** * Types. */ var types = [ 'arguments', 'array', 'boolean', 'date', 'element', 'function', 'null', 'number', 'object', 'regexp', 'string', 'undefined' ]; /** * Expose type checkers. * * @param {Mixed} value * @return {Boolean} */ for (var i = 0, type; type = types[i]; i++) exports[type] = generate(type); /** * Add alias for `function` for old browsers. */ exports.fn = exports['function']; /** * Expose `empty` check. */ exports.empty = isEmpty; /** * Expose `nan` check. */ exports.nan = function (val) { return exports.number(val) && val != val; }; /** * Generate a type checker. * * @param {String} type * @return {Function} */ function generate (type) { return function (value) { return type === typeOf(value); }; } }, {"is-empty":123,"type":7,"component-type":7}], 149: [function(require, module, exports) { /** * Matcher, slightly modified from: * * https://github.com/csnover/js-iso8601/blob/lax/iso8601.js */ var matcher = /^(\d{4})(?:-?(\d{2})(?:-?(\d{2}))?)?(?:([ T])(\d{2}):?(\d{2})(?::?(\d{2})(?:[,\.](\d{1,}))?)?(?:(Z)|([+\-])(\d{2})(?::?(\d{2}))?)?)?$/; /** * Convert an ISO date string to a date. Fallback to native `Date.parse`. * * https://github.com/csnover/js-iso8601/blob/lax/iso8601.js * * @param {String} iso * @return {Date} */ exports.parse = function (iso) { var numericKeys = [1, 5, 6, 7, 11, 12]; var arr = matcher.exec(iso); var offset = 0; // fallback to native parsing if (!arr) return new Date(iso); // remove undefined values for (var i = 0, val; val = numericKeys[i]; i++) { arr[val] = parseInt(arr[val], 10) || 0; } // allow undefined days and months arr[2] = parseInt(arr[2], 10) || 1; arr[3] = parseInt(arr[3], 10) || 1; // month is 0-11 arr[2]--; // allow abitrary sub-second precision arr[8] = arr[8] ? (arr[8] + '00').substring(0, 3) : 0; // apply timezone if one exists if (arr[4] == ' ') { offset = new Date().getTimezoneOffset(); } else if (arr[9] !== 'Z' && arr[10]) { offset = arr[11] * 60 + arr[12]; if ('+' == arr[10]) offset = 0 - offset; } var millis = Date.UTC(arr[1], arr[2], arr[3], arr[5], arr[6] + offset, arr[7], arr[8]); return new Date(millis); }; /** * Checks whether a `string` is an ISO date string. `strict` mode requires that * the date string at least have a year, month and date. * * @param {String} string * @param {Boolean} strict * @return {Boolean} */ exports.is = function (string, strict) { if (strict && false === /^\d{4}-\d{2}-\d{2}/.test(string)) return false; return matcher.test(string); }; }, {}], 144: [function(require, module, exports) { /** * A few integrations are disabled by default. They must be explicitly * enabled by setting options[Provider] = true. */ var disabled = { Salesforce: true }; /** * Check whether an integration should be enabled by default. * * @param {String} integration * @return {Boolean} */ module.exports = function (integration) { return ! disabled[integration]; }; }, {}], 145: [function(require, module, exports) { /** * TODO: use component symlink, everywhere ? */ try { exports.inherit = require('inherit'); exports.clone = require('clone'); exports.type = require('type'); } catch (e) { exports.inherit = require('inherit-component'); exports.clone = require('clone-component'); exports.type = require('type-component'); } }, {"inherit":150,"clone":151,"type":7}], 150: [function(require, module, exports) { module.exports = function(a, b){ var fn = function(){}; fn.prototype = b.prototype; a.prototype = new fn; a.prototype.constructor = a; }; }, {}], 151: [function(require, module, exports) { /** * Module dependencies. */ var type; try { type = require('component-type'); } catch (_) { type = require('type'); } /** * Module exports. */ module.exports = clone; /** * Clones objects. * * @param {Mixed} any object * @api public */ function clone(obj){ switch (type(obj)) { case 'object': var copy = {}; for (var key in obj) { if (obj.hasOwnProperty(key)) { copy[key] = clone(obj[key]); } } return copy; case 'array': var copy = new Array(obj.length); for (var i = 0, l = obj.length; i < l; i++) { copy[i] = clone(obj[i]); } return copy; case 'regexp': // from millermedeiros/amd-utils - MIT var flags = ''; flags += obj.multiline ? 'm' : ''; flags += obj.global ? 'g' : ''; flags += obj.ignoreCase ? 'i' : ''; return new RegExp(obj.source, flags); case 'date': return new Date(obj.getTime()); default: // string, number, boolean, … return obj; } } }, {"component-type":7,"type":7}], 146: [function(require, module, exports) { /** * Module dependencies. */ var get = require('obj-case'); /** * Add address getters to `proto`. * * @param {Function} proto */ module.exports = function(proto){ proto.zip = trait('postalCode', 'zip'); proto.country = trait('country'); proto.street = trait('street'); proto.state = trait('state'); proto.city = trait('city'); function trait(a, b){ return function(){ var traits = this.traits(); var props = this.properties ? this.properties() : {}; return get(traits, 'address.' + a) || get(traits, a) || (b ? get(traits, 'address.' + b) : null) || (b ? get(traits, b) : null) || get(props, 'address.' + a) || get(props, a) || (b ? get(props, 'address.' + b) : null) || (b ? get(props, b) : null); }; } }; }, {"obj-case":93}], 147: [function(require, module, exports) { var is = require('is'); var isodate = require('isodate'); var milliseconds = require('./milliseconds'); var seconds = require('./seconds'); /** * Returns a new Javascript Date object, allowing a variety of extra input types * over the native Date constructor. * * @param {Date|String|Number} val */ module.exports = function newDate (val) { if (is.date(val)) return val; if (is.number(val)) return new Date(toMs(val)); // date strings if (isodate.is(val)) return isodate.parse(val); if (milliseconds.is(val)) return milliseconds.parse(val); if (seconds.is(val)) return seconds.parse(val); // fallback to Date.parse return new Date(val); }; /** * If the number passed val is seconds from the epoch, turn it into milliseconds. * Milliseconds would be greater than 31557600000 (December 31, 1970). * * @param {Number} num */ function toMs (num) { if (num < 31557600000) return num * 1000; return num; } }, {"is":152,"isodate":149,"./milliseconds":153,"./seconds":154}], 152: [function(require, module, exports) { var isEmpty = require('is-empty') , typeOf = require('type'); /** * Types. */ var types = [ 'arguments', 'array', 'boolean', 'date', 'element', 'function', 'null', 'number', 'object', 'regexp', 'string', 'undefined' ]; /** * Expose type checkers. * * @param {Mixed} value * @return {Boolean} */ for (var i = 0, type; type = types[i]; i++) exports[type] = generate(type); /** * Add alias for `function` for old browsers. */ exports.fn = exports['function']; /** * Expose `empty` check. */ exports.empty = isEmpty; /** * Expose `nan` check. */ exports.nan = function (val) { return exports.number(val) && val != val; }; /** * Generate a type checker. * * @param {String} type * @return {Function} */ function generate (type) { return function (value) { return type === typeOf(value); }; } }, {"is-empty":123,"type":7}], 153: [function(require, module, exports) { /** * Matcher. */ var matcher = /\d{13}/; /** * Check whether a string is a millisecond date string. * * @param {String} string * @return {Boolean} */ exports.is = function (string) { return matcher.test(string); }; /** * Convert a millisecond string to a date. * * @param {String} millis * @return {Date} */ exports.parse = function (millis) { millis = parseInt(millis, 10); return new Date(millis); }; }, {}], 154: [function(require, module, exports) { /** * Matcher. */ var matcher = /\d{10}/; /** * Check whether a string is a second date string. * * @param {String} string * @return {Boolean} */ exports.is = function (string) { return matcher.test(string); }; /** * Convert a second string to a date. * * @param {String} seconds * @return {Date} */ exports.parse = function (seconds) { var millis = parseInt(seconds, 10) * 1000; return new Date(millis); }; }, {}], 137: [function(require, module, exports) { /** * Module dependencies. */ var inherit = require('./utils').inherit; var Facade = require('./facade'); /** * Expose `Alias` facade. */ module.exports = Alias; /** * Initialize a new `Alias` facade with a `dictionary` of arguments. * * @param {Object} dictionary * @property {String} from * @property {String} to * @property {Object} options */ function Alias (dictionary) { Facade.call(this, dictionary); } /** * Inherit from `Facade`. */ inherit(Alias, Facade); /** * Return type of facade. * * @return {String} */ Alias.prototype.type = Alias.prototype.action = function () { return 'alias'; }; /** * Get `previousId`. * * @return {Mixed} * @api public */ Alias.prototype.from = Alias.prototype.previousId = function(){ return this.field('previousId') || this.field('from'); }; /** * Get `userId`. * * @return {String} * @api public */ Alias.prototype.to = Alias.prototype.userId = function(){ return this.field('userId') || this.field('to'); }; }, {"./utils":145,"./facade":136}], 138: [function(require, module, exports) { /** * Module dependencies. */ var inherit = require('./utils').inherit; var address = require('./address'); var isEmail = require('is-email'); var newDate = require('new-date'); var Facade = require('./facade'); /** * Expose `Group` facade. */ module.exports = Group; /** * Initialize a new `Group` facade with a `dictionary` of arguments. * * @param {Object} dictionary * @param {String} userId * @param {String} groupId * @param {Object} properties * @param {Object} options */ function Group (dictionary) { Facade.call(this, dictionary); } /** * Inherit from `Facade` */ inherit(Group, Facade); /** * Get the facade's action. */ Group.prototype.type = Group.prototype.action = function () { return 'group'; }; /** * Setup some basic proxies. */ Group.prototype.groupId = Facade.field('groupId'); /** * Get created or createdAt. * * @return {Date} */ Group.prototype.created = function(){ var created = this.proxy('traits.createdAt') || this.proxy('traits.created') || this.proxy('properties.createdAt') || this.proxy('properties.created'); if (created) return newDate(created); }; /** * Get the group's email, falling back to the group ID if it's a valid email. * * @return {String} */ Group.prototype.email = function () { var email = this.proxy('traits.email'); if (email) return email; var groupId = this.groupId(); if (isEmail(groupId)) return groupId; }; /** * Get the group's traits. * * @param {Object} aliases * @return {Object} */ Group.prototype.traits = function (aliases) { var ret = this.properties(); var id = this.groupId(); aliases = aliases || {}; if (id) ret.id = id; for (var alias in aliases) { var value = null == this[alias] ? this.proxy('traits.' + alias) : this[alias](); if (null == value) continue; ret[aliases[alias]] = value; delete ret[alias]; } return ret; }; /** * Special traits. */ Group.prototype.name = Facade.proxy('traits.name'); Group.prototype.industry = Facade.proxy('traits.industry'); Group.prototype.employees = Facade.proxy('traits.employees'); /** * Get traits or properties. * * TODO: remove me * * @return {Object} */ Group.prototype.properties = function(){ return this.field('traits') || this.field('properties') || {}; }; }, {"./utils":145,"./address":146,"is-email":155,"new-date":147,"./facade":136}], 155: [function(require, module, exports) { /** * Expose `isEmail`. */ module.exports = isEmail; /** * Email address matcher. */ var matcher = /.+\@.+\..+/; /** * Loosely validate an email address. * * @param {String} string * @return {Boolean} */ function isEmail (string) { return matcher.test(string); } }, {}], 139: [function(require, module, exports) { var address = require('./address'); var Facade = require('./facade'); var isEmail = require('is-email'); var newDate = require('new-date'); var utils = require('./utils'); var get = require('obj-case'); var trim = require('trim'); var inherit = utils.inherit; var clone = utils.clone; var type = utils.type; /** * Expose `Idenfity` facade. */ module.exports = Identify; /** * Initialize a new `Identify` facade with a `dictionary` of arguments. * * @param {Object} dictionary * @param {String} userId * @param {String} sessionId * @param {Object} traits * @param {Object} options */ function Identify (dictionary) { Facade.call(this, dictionary); } /** * Inherit from `Facade`. */ inherit(Identify, Facade); /** * Get the facade's action. */ Identify.prototype.type = Identify.prototype.action = function () { return 'identify'; }; /** * Get the user's traits. * * @param {Object} aliases * @return {Object} */ Identify.prototype.traits = function (aliases) { var ret = this.field('traits') || {}; var id = this.userId(); aliases = aliases || {}; if (id) ret.id = id; for (var alias in aliases) { var value = null == this[alias] ? this.proxy('traits.' + alias) : this[alias](); if (null == value) continue; ret[aliases[alias]] = value; if (alias !== aliases[alias]) delete ret[alias]; } return ret; }; /** * Get the user's email, falling back to their user ID if it's a valid email. * * @return {String} */ Identify.prototype.email = function () { var email = this.proxy('traits.email'); if (email) return email; var userId = this.userId(); if (isEmail(userId)) return userId; }; /** * Get the user's created date, optionally looking for `createdAt` since lots of * people do that instead. * * @return {Date or Undefined} */ Identify.prototype.created = function () { var created = this.proxy('traits.created') || this.proxy('traits.createdAt'); if (created) return newDate(created); }; /** * Get the company created date. * * @return {Date or undefined} */ Identify.prototype.companyCreated = function(){ var created = this.proxy('traits.company.created') || this.proxy('traits.company.createdAt'); if (created) return newDate(created); }; /** * Get the user's name, optionally combining a first and last name if that's all * that was provided. * * @return {String or Undefined} */ Identify.prototype.name = function () { var name = this.proxy('traits.name'); if (typeof name === 'string') return trim(name); var firstName = this.firstName(); var lastName = this.lastName(); if (firstName && lastName) return trim(firstName + ' ' + lastName); }; /** * Get the user's first name, optionally splitting it out of a single name if * that's all that was provided. * * @return {String or Undefined} */ Identify.prototype.firstName = function () { var firstName = this.proxy('traits.firstName'); if (typeof firstName === 'string') return trim(firstName); var name = this.proxy('traits.name'); if (typeof name === 'string') return trim(name).split(' ')[0]; }; /** * Get the user's last name, optionally splitting it out of a single name if * that's all that was provided. * * @return {String or Undefined} */ Identify.prototype.lastName = function () { var lastName = this.proxy('traits.lastName'); if (typeof lastName === 'string') return trim(lastName); var name = this.proxy('traits.name'); if (typeof name !== 'string') return; var space = trim(name).indexOf(' '); if (space === -1) return; return trim(name.substr(space + 1)); }; /** * Get the user's unique id. * * @return {String or undefined} */ Identify.prototype.uid = function(){ return this.userId() || this.username() || this.email(); }; /** * Get description. * * @return {String} */ Identify.prototype.description = function(){ return this.proxy('traits.description') || this.proxy('traits.background'); }; /** * Get the age. * * If the age is not explicitly set * the method will compute it from `.birthday()` * if possible. * * @return {Number} */ Identify.prototype.age = function(){ var date = this.birthday(); var age = get(this.traits(), 'age'); if (null != age) return age; if ('date' != type(date)) return; var now = new Date; return now.getFullYear() - date.getFullYear(); }; /** * Get the avatar. * * .photoUrl needed because help-scout * implementation uses `.avatar || .photoUrl`. * * .avatarUrl needed because trakio uses it. * * @return {Mixed} */ Identify.prototype.avatar = function(){ var traits = this.traits(); return get(traits, 'avatar') || get(traits, 'photoUrl') || get(traits, 'avatarUrl'); }; /** * Get the position. * * .jobTitle needed because some integrations use it. * * @return {Mixed} */ Identify.prototype.position = function(){ var traits = this.traits(); return get(traits, 'position') || get(traits, 'jobTitle'); }; /** * Setup sme basic "special" trait proxies. */ Identify.prototype.username = Facade.proxy('traits.username'); Identify.prototype.website = Facade.one('traits.website'); Identify.prototype.websites = Facade.multi('traits.website'); Identify.prototype.phone = Facade.one('traits.phone'); Identify.prototype.phones = Facade.multi('traits.phone'); Identify.prototype.address = Facade.proxy('traits.address'); Identify.prototype.gender = Facade.proxy('traits.gender'); Identify.prototype.birthday = Facade.proxy('traits.birthday'); }, {"./address":146,"./facade":136,"is-email":155,"new-date":147,"./utils":145,"obj-case":93,"trim":127}], 140: [function(require, module, exports) { var inherit = require('./utils').inherit; var clone = require('./utils').clone; var type = require('./utils').type; var Facade = require('./facade'); var Identify = require('./identify'); var isEmail = require('is-email'); var get = require('obj-case'); /** * Expose `Track` facade. */ module.exports = Track; /** * Initialize a new `Track` facade with a `dictionary` of arguments. * * @param {object} dictionary * @property {String} event * @property {String} userId * @property {String} sessionId * @property {Object} properties * @property {Object} options */ function Track (dictionary) { Facade.call(this, dictionary); } /** * Inherit from `Facade`. */ inherit(Track, Facade); /** * Return the facade's action. * * @return {String} */ Track.prototype.type = Track.prototype.action = function () { return 'track'; }; /** * Setup some basic proxies. */ Track.prototype.event = Facade.field('event'); Track.prototype.value = Facade.proxy('properties.value'); /** * Misc */ Track.prototype.category = Facade.proxy('properties.category'); /** * Ecommerce */ Track.prototype.id = Facade.proxy('properties.id'); Track.prototype.sku = Facade.proxy('properties.sku'); Track.prototype.tax = Facade.proxy('properties.tax'); Track.prototype.name = Facade.proxy('properties.name'); Track.prototype.price = Facade.proxy('properties.price'); Track.prototype.total = Facade.proxy('properties.total'); Track.prototype.coupon = Facade.proxy('properties.coupon'); Track.prototype.shipping = Facade.proxy('properties.shipping'); Track.prototype.discount = Facade.proxy('properties.discount'); /** * Description */ Track.prototype.description = Facade.proxy('properties.description'); /** * Plan */ Track.prototype.plan = Facade.proxy('properties.plan'); /** * Order id. * * @return {String} * @api public */ Track.prototype.orderId = function(){ return this.proxy('properties.id') || this.proxy('properties.orderId'); }; /** * Get subtotal. * * @return {Number} */ Track.prototype.subtotal = function(){ var subtotal = get(this.properties(), 'subtotal'); var total = this.total(); var n; if (subtotal) return subtotal; if (!total) return 0; if (n = this.tax()) total -= n; if (n = this.shipping()) total -= n; if (n = this.discount()) total += n; return total; }; /** * Get products. * * @return {Array} */ Track.prototype.products = function(){ var props = this.properties(); var products = get(props, 'products'); return 'array' == type(products) ? products : []; }; /** * Get quantity. * * @return {Number} */ Track.prototype.quantity = function(){ var props = this.obj.properties || {}; return props.quantity || 1; }; /** * Get currency. * * @return {String} */ Track.prototype.currency = function(){ var props = this.obj.properties || {}; return props.currency || 'USD'; }; /** * BACKWARDS COMPATIBILITY: should probably re-examine where these come from. */ Track.prototype.referrer = Facade.proxy('properties.referrer'); Track.prototype.query = Facade.proxy('options.query'); /** * Get the call's properties. * * @param {Object} aliases * @return {Object} */ Track.prototype.properties = function (aliases) { var ret = this.field('properties') || {}; aliases = aliases || {}; for (var alias in aliases) { var value = null == this[alias] ? this.proxy('properties.' + alias) : this[alias](); if (null == value) continue; ret[aliases[alias]] = value; delete ret[alias]; } return ret; }; /** * Get the call's username. * * @return {String or Undefined} */ Track.prototype.username = function () { return this.proxy('traits.username') || this.proxy('properties.username') || this.userId() || this.sessionId(); }; /** * Get the call's email, using an the user ID if it's a valid email. * * @return {String or Undefined} */ Track.prototype.email = function () { var email = this.proxy('traits.email'); email = email || this.proxy('properties.email'); if (email) return email; var userId = this.userId(); if (isEmail(userId)) return userId; }; /** * Get the call's revenue, parsing it from a string with an optional leading * dollar sign. * * For products/services that don't have shipping and are not directly taxed, * they only care about tracking `revenue`. These are things like * SaaS companies, who sell monthly subscriptions. The subscriptions aren't * taxed directly, and since it's a digital product, it has no shipping. * * The only case where there's a difference between `revenue` and `total` * (in the context of analytics) is on ecommerce platforms, where they want * the `revenue` function to actually return the `total` (which includes * tax and shipping, total = subtotal + tax + shipping). This is probably * because on their backend they assume tax and shipping has been applied to * the value, and so can get the revenue on their own. * * @return {Number} */ Track.prototype.revenue = function () { var revenue = this.proxy('properties.revenue'); var event = this.event(); // it's always revenue, unless it's called during an order completion. if (!revenue && event && event.match(/completed ?order/i)) { revenue = this.proxy('properties.total'); } return currency(revenue); }; /** * Get cents. * * @return {Number} */ Track.prototype.cents = function(){ var revenue = this.revenue(); return 'number' != typeof revenue ? this.value() || 0 : revenue * 100; }; /** * A utility to turn the pieces of a track call into an identify. Used for * integrations with super properties or rate limits. * * TODO: remove me. * * @return {Facade} */ Track.prototype.identify = function () { var json = this.json(); json.traits = this.traits(); return new Identify(json); }; /** * Get float from currency value. * * @param {Mixed} val * @return {Number} */ function currency(val) { if (!val) return; if (typeof val === 'number') return val; if (typeof val !== 'string') return; val = val.replace(/\$/g, ''); val = parseFloat(val); if (!isNaN(val)) return val; } }, {"./utils":145,"./facade":136,"./identify":139,"is-email":155,"obj-case":93}], 141: [function(require, module, exports) { var inherit = require('./utils').inherit; var Facade = require('./facade'); var Track = require('./track'); /** * Expose `Page` facade */ module.exports = Page; /** * Initialize new `Page` facade with `dictionary`. * * @param {Object} dictionary * @param {String} category * @param {String} name * @param {Object} traits * @param {Object} options */ function Page(dictionary){ Facade.call(this, dictionary); } /** * Inherit from `Facade` */ inherit(Page, Facade); /** * Get the facade's action. * * @return {String} */ Page.prototype.type = Page.prototype.action = function(){ return 'page'; }; /** * Fields */ Page.prototype.category = Facade.field('category'); Page.prototype.name = Facade.field('name'); /** * Proxies. */ Page.prototype.title = Facade.proxy('properties.title'); Page.prototype.path = Facade.proxy('properties.path'); Page.prototype.url = Facade.proxy('properties.url'); /** * Referrer. */ Page.prototype.referrer = function(){ return this.proxy('properties.referrer') || this.proxy('context.referrer.url'); }; /** * Get the page properties mixing `category` and `name`. * * @return {Object} */ Page.prototype.properties = function(){ var props = this.field('properties') || {}; var category = this.category(); var name = this.name(); if (category) props.category = category; if (name) props.name = name; return props; }; /** * Get the page fullName. * * @return {String} */ Page.prototype.fullName = function(){ var category = this.category(); var name = this.name(); return name && category ? category + ' ' + name : name; }; /** * Get event with `name`. * * @return {String} */ Page.prototype.event = function(name){ return name ? 'Viewed ' + name + ' Page' : 'Loaded a Page'; }; /** * Convert this Page to a Track facade with `name`. * * @param {String} name * @return {Track} */ Page.prototype.track = function(name){ var props = this.properties(); return new Track({ event: this.event(name), timestamp: this.timestamp(), context: this.context(), properties: props }); }; }, {"./utils":145,"./facade":136,"./track":140}], 142: [function(require, module, exports) { var inherit = require('./utils').inherit; var Page = require('./page'); var Track = require('./track'); /** * Expose `Screen` facade */ module.exports = Screen; /** * Initialize new `Screen` facade with `dictionary`. * * @param {Object} dictionary * @param {String} category * @param {String} name * @param {Object} traits * @param {Object} options */ function Screen(dictionary){ Page.call(this, dictionary); } /** * Inherit from `Page` */ inherit(Screen, Page); /** * Get the facade's action. * * @return {String} * @api public */ Screen.prototype.type = Screen.prototype.action = function(){ return 'screen'; }; /** * Get event with `name`. * * @param {String} name * @return {String} * @api public */ Screen.prototype.event = function(name){ return name ? 'Viewed ' + name + ' Screen' : 'Loaded a Screen'; }; /** * Convert this Screen. * * @param {String} name * @return {Track} * @api public */ Screen.prototype.track = function(name){ var props = this.properties(); return new Track({ event: this.event(name), timestamp: this.timestamp(), context: this.context(), properties: props }); }; }, {"./utils":145,"./page":141,"./track":140}], 134: [function(require, module, exports) { /** * Module dependencies. */ var stringify = require('querystring').stringify; var sub = require('substitute'); /** * Factory function to create a pixel loader. * * @param {String} path * @return {Function} * @api public */ module.exports = function(path){ return function(query, obj, fn){ if ('function' == typeof obj) fn = obj, obj = {}; obj = obj || {}; fn = fn || function(){}; var url = sub(path, obj); var img = new Image; img.onerror = error(fn, 'failed to load pixel', img); img.onload = function(){ fn(); }; query = stringify(query); if (query) query = '?' + query; img.src = url + query; img.width = 1; img.height = 1; return img; }; }; /** * Create an error handler. * * @param {Fucntion} fn * @param {String} message * @param {Image} img * @return {Function} * @api private */ function error(fn, message, img){ return function(e){ e = e || window.event; var err = new Error(message); err.event = e; err.source = img; fn(err); }; } }, {"querystring":126,"substitute":156}], 156: [function(require, module, exports) { /** * Expose `substitute` */ module.exports = substitute; /** * Type. */ var type = Object.prototype.toString; /** * Substitute `:prop` with the given `obj` in `str` * * @param {String} str * @param {Object or Array} obj * @param {RegExp} expr * @return {String} * @api public */ function substitute(str, obj, expr){ if (!obj) throw new TypeError('expected an object'); expr = expr || /:(\w+)/g; return str.replace(expr, function(_, prop){ switch (type.call(obj)) { case '[object Object]': return null != obj[prop] ? obj[prop] : _; case '[object Array]': var val = obj.shift(); return null != val ? val : _; } }); } }, {}], 135: [function(require, module, exports) { /** * Module dependencies. */ var encode = encodeURIComponent; var decode = decodeURIComponent; var trim = require('trim'); var type = require('type'); /** * Parse the given query `str`. * * @param {String} str * @return {Object} * @api public */ exports.parse = function(str){ if ('string' != typeof str) return {}; str = trim(str); if ('' == str) return {}; if ('?' == str.charAt(0)) str = str.slice(1); var obj = {}; var pairs = str.split('&'); for (var i = 0; i < pairs.length; i++) { var parts = pairs[i].split('='); var key = decode(parts[0]); var m; if (m = /(\w+)\[(\d+)\]/.exec(key)) { obj[m[1]] = obj[m[1]] || []; obj[m[1]][m[2]] = decode(parts[1]); continue; } obj[parts[0]] = null == parts[1] ? '' : decode(parts[1]); } return obj; }; /** * Stringify the given `obj`. * * @param {Object} obj * @return {String} * @api public */ exports.stringify = function(obj){ if (!obj) return ''; var pairs = []; for (var key in obj) { var value = obj[key]; if ('array' == type(value)) { for (var i = 0; i < value.length; ++i) { pairs.push(encode(key + '[' + i + ']') + '=' + encode(value[i])); } continue; } pairs.push(encode(key) + '=' + encode(obj[key])); } return pairs.join('&'); }; }, {"trim":127,"type":7}], 19: [function(require, module, exports) { /** * Module dependencies. */ var integration = require('analytics.js-integration'); var tick = require('next-tick'); /** * Expose `BugHerd` integration. */ var BugHerd = module.exports = integration('BugHerd') .assumesPageview() .global('BugHerdConfig') .global('_bugHerd') .option('apiKey', '') .option('showFeedbackTab', true) .tag('<script src="//www.bugherd.com/sidebarv2.js?apikey={{ apiKey }}">'); /** * Initialize. * * http://support.bugherd.com/home * * @param {Object} page */ BugHerd.prototype.initialize = function(page){ window.BugHerdConfig = { feedback: { hide: !this.options.showFeedbackTab }}; var ready = this.ready; this.load(function(){ tick(ready); }); }; /** * Loaded? * * @return {Boolean} */ BugHerd.prototype.loaded = function(){ return !! window._bugHerd; }; }, {"analytics.js-integration":89,"next-tick":104}], 20: [function(require, module, exports) { /** * Module dependencies. */ var integration = require('analytics.js-integration'); var is = require('is'); var extend = require('extend'); var onError = require('on-error'); /** * UMD ? */ var umd = 'function' == typeof define && define.amd; /** * Source. */ var src = '//d2wy8f7a9ursnm.cloudfront.net/bugsnag-2.min.js'; /** * Expose `Bugsnag` integration. */ var Bugsnag = module.exports = integration('Bugsnag') .global('Bugsnag') .option('apiKey', '') .tag('<script src="' + src + '">'); /** * Initialize. * * https://bugsnag.com/docs/notifiers/js * * @param {Object} page */ Bugsnag.prototype.initialize = function(page){ var self = this; if (umd) { window.require([src], function(bugsnag){ bugsnag.apiKey = self.options.apiKey; window.Bugsnag = bugsnag; self.ready(); }); return; } this.load(function(){ window.Bugsnag.apiKey = self.options.apiKey; self.ready(); }); }; /** * Loaded? * * @return {Boolean} */ Bugsnag.prototype.loaded = function(){ return is.object(window.Bugsnag); }; /** * Identify. * * @param {Identify} identify */ Bugsnag.prototype.identify = function(identify){ window.Bugsnag.metaData = window.Bugsnag.metaData || {}; extend(window.Bugsnag.metaData, identify.traits()); }; }, {"analytics.js-integration":89,"is":92,"extend":131,"on-error":157}], 157: [function(require, module, exports) { /** * Expose `onError`. */ module.exports = onError; /** * Callbacks. */ var callbacks = []; /** * Preserve existing handler. */ if ('function' == typeof window.onerror) callbacks.push(window.onerror); /** * Bind to `window.onerror`. */ window.onerror = handler; /** * Error handler. */ function handler () { for (var i = 0, fn; fn = callbacks[i]; i++) fn.apply(this, arguments); } /** * Call a `fn` on `window.onerror`. * * @param {Function} fn */ function onError (fn) { callbacks.push(fn); if (window.onerror != handler) { callbacks.push(window.onerror); window.onerror = handler; } } }, {}], 21: [function(require, module, exports) { /** * Module dependencies. */ var integration = require('analytics.js-integration'); var defaults = require('defaults'); var onBody = require('on-body'); /** * Expose `Chartbeat` integration. */ var Chartbeat = module.exports = integration('Chartbeat') .assumesPageview() .global('_sf_async_config') .global('_sf_endpt') .global('pSUPERFLY') .option('domain', '') .option('uid', null) .tag('<script src="//static.chartbeat.com/js/chartbeat.js">'); /** * Initialize. * * http://chartbeat.com/docs/configuration_variables/ * * @param {Object} page */ Chartbeat.prototype.initialize = function(page){ var self = this; window._sf_async_config = window._sf_async_config || {}; window._sf_async_config.useCanonical = true; defaults(window._sf_async_config, this.options); onBody(function(){ window._sf_endpt = new Date().getTime(); // Note: Chartbeat depends on document.body existing so the script does // not load until that is confirmed. Otherwise it may trigger errors. self.load(self.ready); }); }; /** * Loaded? * * @return {Boolean} */ Chartbeat.prototype.loaded = function(){ return !! window.pSUPERFLY; }; /** * Page. * * http://chartbeat.com/docs/handling_virtual_page_changes/ * * @param {Page} page */ Chartbeat.prototype.page = function(page){ var category = page.category(); if (category) window._sf_async_config.sections = category; var author = page.proxy('properties.author'); if (author) window._sf_async_config.authors = author; var props = page.properties(); var name = page.fullName(); window.pSUPERFLY.virtualPage(props.path, name || props.title); }; }, {"analytics.js-integration":89,"defaults":158,"on-body":130}], 158: [function(require, module, exports) { /** * Expose `defaults`. */ module.exports = defaults; function defaults (dest, defaults) { for (var prop in defaults) { if (! (prop in dest)) { dest[prop] = defaults[prop]; } } return dest; }; }, {}], 22: [function(require, module, exports) { /** * Module dependencies. */ var date = require('load-date'); var domify = require('domify'); var each = require('each'); var integration = require('analytics.js-integration'); var is = require('is'); var useHttps = require('use-https'); var onBody = require('on-body'); /** * Expose `ClickTale` integration. */ var ClickTale = module.exports = integration('ClickTale') .assumesPageview() .global('WRInitTime') .global('ClickTale') .global('ClickTaleSetUID') .global('ClickTaleField') .global('ClickTaleEvent') .option('httpCdnUrl', 'http://s.clicktale.net/WRe0.js') .option('httpsCdnUrl', '') .option('projectId', '') .option('recordingRatio', 0.01) .option('partitionId', '') .tag('<script src="{{src}}">'); /** * Initialize. * * http://wiki.clicktale.com/Article/JavaScript_API * * @param {Object} page */ ClickTale.prototype.initialize = function(page){ var self = this; window.WRInitTime = date.getTime(); onBody(function(body){ body.appendChild(domify('<div id="ClickTaleDiv" style="display: none;">')); }); var http = this.options.httpCdnUrl; var https = this.options.httpsCdnUrl; if (useHttps() && !https) return this.debug('https option required'); var src = useHttps() ? https : http; this.load({ src: src }, function(){ window.ClickTale( self.options.projectId, self.options.recordingRatio, self.options.partitionId ); self.ready(); }); }; /** * Loaded? * * @return {Boolean} */ ClickTale.prototype.loaded = function(){ return is.fn(window.ClickTale); }; /** * Identify. * * http://wiki.clicktale.com/Article/ClickTaleTag#ClickTaleSetUID * http://wiki.clicktale.com/Article/ClickTaleTag#ClickTaleField * * @param {Identify} identify */ ClickTale.prototype.identify = function(identify){ var id = identify.userId(); window.ClickTaleSetUID(id); each(identify.traits(), function(key, value){ window.ClickTaleField(key, value); }); }; /** * Track. * * http://wiki.clicktale.com/Article/ClickTaleTag#ClickTaleEvent * * @param {Track} track */ ClickTale.prototype.track = function(track){ window.ClickTaleEvent(track.event()); }; }, {"load-date":159,"domify":120,"each":4,"analytics.js-integration":89,"is":92,"use-https":91,"on-body":130}], 159: [function(require, module, exports) { /* * Load date. * * For reference: http://www.html5rocks.com/en/tutorials/webperformance/basics/ */ var time = new Date() , perf = window.performance; if (perf && perf.timing && perf.timing.responseEnd) { time = new Date(perf.timing.responseEnd); } module.exports = time; }, {}], 23: [function(require, module, exports) { /** * Module dependencies. */ var Identify = require('facade').Identify; var extend = require('extend'); var integration = require('analytics.js-integration'); var is = require('is'); /** * Expose `Clicky` integration. */ var Clicky = module.exports = integration('Clicky') .assumesPageview() .global('clicky') .global('clicky_site_ids') .global('clicky_custom') .option('siteId', null) .tag('<script src="//static.getclicky.com/js"></script>'); /** * Initialize. * * http://clicky.com/help/customization * * @param {Object} page */ Clicky.prototype.initialize = function(page){ var user = this.analytics.user(); window.clicky_site_ids = window.clicky_site_ids || [this.options.siteId]; this.identify(new Identify({ userId: user.id(), traits: user.traits() })); this.load(this.ready); }; /** * Loaded? * * @return {Boolean} */ Clicky.prototype.loaded = function(){ return is.object(window.clicky); }; /** * Page. * * http://clicky.com/help/customization#/help/custom/manual * * @param {Page} page */ Clicky.prototype.page = function(page){ var properties = page.properties(); var category = page.category(); var name = page.fullName(); window.clicky.log(properties.path, name || properties.title); }; /** * Identify. * * @param {Identify} id (optional) */ Clicky.prototype.identify = function(identify){ window.clicky_custom = window.clicky_custom || {}; window.clicky_custom.session = window.clicky_custom.session || {}; var traits = identify.traits(); var username = identify.username(); var email = identify.email(); var name = identify.name(); if (username || email || name) traits.username = username || email || name; extend(window.clicky_custom.session, traits); }; /** * Track. * * http://clicky.com/help/customization#/help/custom/manual * * @param {Track} event */ Clicky.prototype.track = function(track){ window.clicky.goal(track.event(), track.revenue()); }; }, {"facade":133,"extend":131,"analytics.js-integration":89,"is":92}], 24: [function(require, module, exports) { /** * Module dependencies. */ var integration = require('analytics.js-integration'); var useHttps = require('use-https'); /** * Expose `Comscore` integration. */ var Comscore = module.exports = integration('comScore') .assumesPageview() .global('_comscore') .global('COMSCORE') .option('c1', '2') .option('c2', '') .tag('http', '<script src="http://b.scorecardresearch.com/beacon.js">') .tag('https', '<script src="https://sb.scorecardresearch.com/beacon.js">'); /** * Initialize. * * @param {Object} page */ Comscore.prototype.initialize = function(page){ window._comscore = window._comscore || [this.options]; var name = useHttps() ? 'https' : 'http'; this.load(name, this.ready); }; /** * Loaded? * * @return {Boolean} */ Comscore.prototype.loaded = function(){ return !! window.COMSCORE; }; /** * Page * * @param {Object} page */ Comscore.prototype.page = function(page){ window.COMSCORE.beacon(this.options); }; }, {"analytics.js-integration":89,"use-https":91}], 25: [function(require, module, exports) { /** * Module dependencies. */ var integration = require('analytics.js-integration'); /** * Expose `CrazyEgg` integration. */ var CrazyEgg = module.exports = integration('Crazy Egg') .assumesPageview() .global('CE2') .option('accountNumber', '') .tag('<script src="//dnn506yrbagrg.cloudfront.net/pages/scripts/{{ path }}.js?{{ cache }}">'); /** * Initialize. * * @param {Object} page */ CrazyEgg.prototype.initialize = function(page){ var number = this.options.accountNumber; var path = number.slice(0,4) + '/' + number.slice(4); var cache = Math.floor(new Date().getTime() / 3600000); this.load({ path: path, cache: cache }, this.ready); }; /** * Loaded? * * @return {Boolean} */ CrazyEgg.prototype.loaded = function(){ return !! window.CE2; }; }, {"analytics.js-integration":89}], 26: [function(require, module, exports) { /** * Module dependencies. */ var integration = require('analytics.js-integration'); var push = require('global-queue')('_curebitq'); var Identify = require('facade').Identify; var throttle = require('throttle'); var Track = require('facade').Track; var iso = require('to-iso-string'); var clone = require('clone'); var each = require('each'); var bind = require('bind'); /** * Expose `Curebit` integration. */ var Curebit = module.exports = integration('Curebit') .global('_curebitq') .global('curebit') .option('siteId', '') .option('iframeWidth', '100%') .option('iframeHeight', '480') .option('iframeBorder', 0) .option('iframeId', 'curebit_integration') .option('responsive', true) .option('device', '') .option('insertIntoId', '') .option('campaigns', {}) .option('server', 'https://www.curebit.com') .tag('<script src="//d2jjzw81hqbuqv.cloudfront.net/integration/curebit-1.0.min.js">'); /** * Initialize. * * @param {Object} page */ Curebit.prototype.initialize = function(page){ push('init', { site_id: this.options.siteId, server: this.options.server }); this.load(this.ready); // throttle the call to `page` since curebit needs to append an iframe this.page = throttle(bind(this, this.page), 250); }; /** * Loaded? * * @return {Boolean} */ Curebit.prototype.loaded = function(){ return !!window.curebit; }; /** * Page. * * Call the `register_affiliate` method of the Curebit API that will load a * custom iframe onto the page, only if this page's path is marked as a * campaign. * * http://www.curebit.com/docs/affiliate/registration * * This is throttled to prevent accidentally drawing the iframe multiple times, * from multiple `.page()` calls. The `250` is from the curebit script. * * @param {String} url * @param {String} id * @param {Function} fn * @api private */ Curebit.prototype.injectIntoId = function(url, id, fn){ var server = this.options.server; when(function(){ return document.getElementById(id); }, function(){ var script = document.createElement('script'); script.src = url; var parent = document.getElementById(id); parent.appendChild(script); onload(script, fn); }); }; /** * Campaign tags. * * @param {Page} page */ Curebit.prototype.page = function(page){ var user = this.analytics.user(); var campaigns = this.options.campaigns; var path = window.location.pathname; if (!campaigns[path]) return; var tags = (campaigns[path] || '').split(','); if (!tags.length) return; var settings = { responsive: this.options.responsive, device: this.options.device, campaign_tags: tags, iframe: { width: this.options.iframeWidth, height: this.options.iframeHeight, id: this.options.iframeId, frameborder: this.options.iframeBorder, container: this.options.insertIntoId } }; var identify = new Identify({ userId: user.id(), traits: user.traits() }); // if we have an email, add any information about the user if (identify.email()) { settings.affiliate_member = { email: identify.email(), first_name: identify.firstName(), last_name: identify.lastName(), customer_id: identify.userId() }; } push('register_affiliate', settings); }; /** * Completed order. * * Fire the Curebit `register_purchase` with the order details and items. * * https://www.curebit.com/docs/ecommerce/custom * * @param {Track} track */ Curebit.prototype.completedOrder = function(track){ var user = this.analytics.user(); var orderId = track.orderId(); var products = track.products(); var props = track.properties(); var items = []; var identify = new Identify({ traits: user.traits(), userId: user.id() }); each(products, function(product){ var track = new Track({ properties: product }); items.push({ product_id: track.id() || track.sku(), quantity: track.quantity(), image_url: product.image, price: track.price(), title: track.name(), url: product.url, }); }); push('register_purchase', { order_date: iso(props.date || new Date()), order_number: orderId, coupon_code: track.coupon(), subtotal: track.total(), customer_id: identify.userId(), first_name: identify.firstName(), last_name: identify.lastName(), email: identify.email(), items: items }); }; }, {"analytics.js-integration":89,"global-queue":160,"facade":133,"throttle":161,"to-iso-string":162,"clone":96,"each":4,"bind":102}], 160: [function(require, module, exports) { /** * Expose `generate`. */ module.exports = generate; /** * Generate a global queue pushing method with `name`. * * @param {String} name * @param {Object} options * @property {Boolean} wrap * @return {Function} */ function generate (name, options) { options = options || {}; return function (args) { args = [].slice.call(arguments); window[name] || (window[name] = []); options.wrap === false ? window[name].push.apply(window[name], args) : window[name].push(args); }; } }, {}], 161: [function(require, module, exports) { /** * Module exports. */ module.exports = throttle; /** * Returns a new function that, when invoked, invokes `func` at most one time per * `wait` milliseconds. * * @param {Function} func The `Function` instance to wrap. * @param {Number} wait The minimum number of milliseconds that must elapse in between `func` invokations. * @return {Function} A new function that wraps the `func` function passed in. * @api public */ function throttle (func, wait) { var rtn; // return value var last = 0; // last invokation timestamp return function throttled () { var now = new Date().getTime(); var delta = now - last; if (delta >= wait) { rtn = func.apply(this, arguments); last = now; } return rtn; }; } }, {}], 162: [function(require, module, exports) { /** * Expose `toIsoString`. */ module.exports = toIsoString; /** * Turn a `date` into an ISO string. * * https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toISOString * * @param {Date} date * @return {String} */ function toIsoString (date) { return date.getUTCFullYear() + '-' + pad(date.getUTCMonth() + 1) + '-' + pad(date.getUTCDate()) + 'T' + pad(date.getUTCHours()) + ':' + pad(date.getUTCMinutes()) + ':' + pad(date.getUTCSeconds()) + '.' + String((date.getUTCMilliseconds()/1000).toFixed(3)).slice(2, 5) + 'Z'; } /** * Pad a `number` with a ten's place zero. * * @param {Number} number * @return {String} */ function pad (number) { var n = number.toString(); return n.length === 1 ? '0' + n : n; } }, {}], 27: [function(require, module, exports) { /** * Module dependencies. */ var alias = require('alias'); var convertDates = require('convert-dates'); var Identify = require('facade').Identify; var integration = require('analytics.js-integration'); /** * Expose `Customerio` integration. */ var Customerio = module.exports = integration('Customer.io') .global('_cio') .option('siteId', '') .tag('<script id="cio-tracker" src="https://assets.customer.io/assets/track.js" data-site-id="{{ siteId }}">'); /** * Initialize. * * http://customer.io/docs/api/javascript.html * * @param {Object} page */ Customerio.prototype.initialize = function(page){ window._cio = window._cio || []; (function(){var a,b,c; a = function(f){return function(){window._cio.push([f].concat(Array.prototype.slice.call(arguments,0))); }; }; b = ['identify', 'track']; for (c = 0; c < b.length; c++) {window._cio[b[c]] = a(b[c]); } })(); this.load(this.ready); }; /** * Loaded? * * @return {Boolean} */ Customerio.prototype.loaded = function(){ return (!! window._cio) && (window._cio.push !== Array.prototype.push); }; /** * Identify. * * http://customer.io/docs/api/javascript.html#section-Identify_customers * * @param {Identify} identify */ Customerio.prototype.identify = function(identify){ if (!identify.userId()) return this.debug('user id required'); var traits = identify.traits({ createdAt: 'created' }); traits = alias(traits, { created: 'created_at' }); traits = convertDates(traits, convertDate); window._cio.identify(traits); }; /** * Group. * * @param {Group} group */ Customerio.prototype.group = function(group){ var traits = group.traits(); var user = this.analytics.user(); traits = alias(traits, function(trait){ return 'Group ' + trait; }); this.identify(new Identify({ userId: user.id(), traits: traits })); }; /** * Track. * * http://customer.io/docs/api/javascript.html#section-Track_a_custom_event * * @param {Track} track */ Customerio.prototype.track = function(track){ var properties = track.properties(); properties = convertDates(properties, convertDate); window._cio.track(track.event(), properties); }; /** * Convert a date to the format Customer.io supports. * * @param {Date} date * @return {Number} */ function convertDate(date){ return Math.floor(date.getTime() / 1000); } }, {"alias":163,"convert-dates":164,"facade":133,"analytics.js-integration":89}], 163: [function(require, module, exports) { var type = require('type'); try { var clone = require('clone'); } catch (e) { var clone = require('clone-component'); } /** * Expose `alias`. */ module.exports = alias; /** * Alias an `object`. * * @param {Object} obj * @param {Mixed} method */ function alias (obj, method) { switch (type(method)) { case 'object': return aliasByDictionary(clone(obj), method); case 'function': return aliasByFunction(clone(obj), method); } } /** * Convert the keys in an `obj` using a dictionary of `aliases`. * * @param {Object} obj * @param {Object} aliases */ function aliasByDictionary (obj, aliases) { for (var key in aliases) { if (undefined === obj[key]) continue; obj[aliases[key]] = obj[key]; delete obj[key]; } return obj; } /** * Convert the keys in an `obj` using a `convert` function. * * @param {Object} obj * @param {Function} convert */ function aliasByFunction (obj, convert) { // have to create another object so that ie8 won't infinite loop on keys var output = {}; for (var key in obj) output[convert(key)] = obj[key]; return output; } }, {"type":7,"clone":151}], 164: [function(require, module, exports) { var is = require('is'); try { var clone = require('clone'); } catch (e) { var clone = require('clone-component'); } /** * Expose `convertDates`. */ module.exports = convertDates; /** * Recursively convert an `obj`'s dates to new values. * * @param {Object} obj * @param {Function} convert * @return {Object} */ function convertDates (obj, convert) { obj = clone(obj); for (var key in obj) { var val = obj[key]; if (is.date(val)) obj[key] = convert(val); if (is.object(val)) obj[key] = convertDates(val, convert); } return obj; } }, {"is":92,"clone":96}], 28: [function(require, module, exports) { /** * Module dependencies. */ var alias = require('alias'); var integration = require('analytics.js-integration'); var is = require('is'); var load = require('load-script'); var push = require('global-queue')('_dcq'); /** * Expose `Drip` integration. */ var Drip = module.exports = integration('Drip') .assumesPageview() .global('_dc') .global('_dcqi') .global('_dcq') .global('_dcs') .option('account', '') .tag('<script src="//tag.getdrip.com/{{ account }}.js">'); /** * Initialize. * * @param {Object} page */ Drip.prototype.initialize = function(page){ window._dcq = window._dcq || []; window._dcs = window._dcs || {}; window._dcs.account = this.options.account; this.load(this.ready); }; /** * Loaded? * * @return {Boolean} */ Drip.prototype.loaded = function(){ return is.object(window._dc); }; /** * Track. * * @param {Track} track */ Drip.prototype.track = function(track){ var props = track.properties(); var cents = track.cents(); if (cents) props.value = cents; delete props.revenue; push('track', track.event(), props); }; /** * Identify. * * @param {Identify} identify */ Drip.prototype.identify = function(identify){ push('identify', identify.traits()); }; }, {"alias":163,"analytics.js-integration":89,"is":92,"load-script":129,"global-queue":160}], 29: [function(require, module, exports) { /** * Module dependencies. */ var extend = require('extend'); var integration = require('analytics.js-integration'); var onError = require('on-error'); var push = require('global-queue')('_errs'); /** * Expose `Errorception` integration. */ var Errorception = module.exports = integration('Errorception') .assumesPageview() .global('_errs') .option('projectId', '') .option('meta', true) .tag('<script src="//beacon.errorception.com/{{ projectId }}.js">'); /** * Initialize. * * https://github.com/amplitude/Errorception-Javascript * * @param {Object} page */ Errorception.prototype.initialize = function(page){ window._errs = window._errs || [this.options.projectId]; onError(push); this.load(this.ready); }; /** * Loaded? * * @return {Boolean} */ Errorception.prototype.loaded = function(){ return !! (window._errs && window._errs.push !== Array.prototype.push); }; /** * Identify. * * http://blog.errorception.com/2012/11/capture-custom-data-with-your-errors.html * * @param {Object} identify */ Errorception.prototype.identify = function(identify){ if (!this.options.meta) return; var traits = identify.traits(); window._errs = window._errs || []; window._errs.meta = window._errs.meta || {}; extend(window._errs.meta, traits); }; }, {"extend":131,"analytics.js-integration":89,"on-error":157,"global-queue":160}], 30: [function(require, module, exports) { /** * Module dependencies. */ var each = require('each'); var integration = require('analytics.js-integration'); var push = require('global-queue')('_aaq'); /** * Expose `Evergage` integration.integration. */ var Evergage = module.exports = integration('Evergage') .assumesPageview() .global('_aaq') .option('account', '') .option('dataset', '') .tag('<script src="//cdn.evergage.com/beacon/{{ account }}/{{ dataset }}/scripts/evergage.min.js">'); /** * Initialize. * * @param {Object} page */ Evergage.prototype.initialize = function(page){ var account = this.options.account; var dataset = this.options.dataset; window._aaq = window._aaq || []; push('setEvergageAccount', account); push('setDataset', dataset); push('setUseSiteConfig', true); this.load(this.ready); }; /** * Loaded? * * @return {Boolean} */ Evergage.prototype.loaded = function(){ return !! (window._aaq && window._aaq.push !== Array.prototype.push); }; /** * Page. * * @param {Page} page */ Evergage.prototype.page = function(page){ var props = page.properties(); var name = page.name(); if (name) push('namePage', name); each(props, function(key, value){ push('setCustomField', key, value, 'page'); }); window.Evergage.init(true); }; /** * Identify. * * @param {Identify} identify */ Evergage.prototype.identify = function(identify){ var id = identify.userId(); if (!id) return; push('setUser', id); var traits = identify.traits({ email: 'userEmail', name: 'userName' }); each(traits, function(key, value){ push('setUserField', key, value, 'page'); }); }; /** * Group. * * @param {Group} group */ Evergage.prototype.group = function(group){ var props = group.traits(); var id = group.groupId(); if (!id) return; push('setCompany', id); each(props, function(key, value){ push('setAccountField', key, value, 'page'); }); }; /** * Track. * * @param {Track} track */ Evergage.prototype.track = function(track){ push('trackAction', track.event(), track.properties()); }; }, {"each":4,"analytics.js-integration":89,"global-queue":160}], 31: [function(require, module, exports) { 'use strict'; /** * Module dependencies. */ var bind = require('bind'); var domify = require('domify'); var each = require('each'); var extend = require('extend'); var integration = require('analytics.js-integration'); var json = require('json'); /** * Expose `Extole` integration. */ var Extole = module.exports = integration('Extole') .global('extole') .option('clientId', '') .mapping('events') .tag('main', '<script src="//tags.extole.com/{{ clientId }}/core.js">'); /** * Initialize. * * @param {Object} page */ Extole.prototype.initialize = function(){ if (this.loaded()) return this.ready(); this.load('main', bind(this, this.ready)); }; /** * Loaded? * * @return {Boolean} */ Extole.prototype.loaded = function(){ return !!window.extole; }; /** * Track. * * @param {Track} track */ Extole.prototype.track = function(track){ var user = this.analytics.user(); var traits = user.traits(); var userId = user.id(); var email = traits.email; if (!userId && !email) { return this.debug('User must be identified before `#track` calls'); } var event = track.event(); var extoleEvents = this.events(event); if (!extoleEvents.length) { return this.debug('No events found for %s', event); } each(extoleEvents, bind(this, function(extoleEvent){ this._registerConversion(this._createConversionTag({ type: extoleEvent, params: this._formatConversionParams(event, email, userId, track.properties()) })); })); }; /** * Register a conversion to Extole. * * @api private * @param {HTMLElement} conversionTag An Extole conversion tag. */ // TODO: If I understand Extole's lib correctly, this is sometimes async, // sometimes sync. Should probably refactor this into more predictable/sane // behavior Extole.prototype._registerConversion = function(conversionTag){ if (window.extole.main && window.extole.main.fireConversion) { return window.extole.main.fireConversion(conversionTag); } if (window.extole.initializeGo) { window.extole.initializeGo().andWhenItsReady(function(){ window.extole.main.fireConversion(conversionTag); }); } }; /** * formatConversionParams. Formats details from a Segment track event into a * data format Extole can accept. * * @param {string} event * @param {string} email * @param {string|number} userId * @param {Object} properties The result of calling `track.properties()`. * @return {Object} */ Extole.prototype._formatConversionParams = function(event, email, userId, properties){ var total; if (properties.total) { total = properties.total; delete properties.total; properties['tag:cart_value'] = total; } return extend({ 'tag:segment_event': event, e: email, partner_conversion_id: userId }, properties); }; /** * Create an Extole conversion tag. * * @param {Object} conversion An Extole conversion object. * @return {HTMLElement} */ Extole.prototype._createConversionTag = function(conversion){ return domify('<script type="extole/conversion">' + json.stringify(conversion) + '</script>'); }; }, {"bind":102,"domify":120,"each":4,"extend":131,"analytics.js-integration":89,"json":165}], 165: [function(require, module, exports) { var json = window.JSON || {}; var stringify = json.stringify; var parse = json.parse; module.exports = parse && stringify ? JSON : require('json-fallback'); }, {"json-fallback":166}], 166: [function(require, module, exports) { /* json2.js 2014-02-04 Public Domain. NO WARRANTY EXPRESSED OR IMPLIED. USE AT YOUR OWN RISK. See http://www.JSON.org/js.html This code should be minified before deployment. See http://javascript.crockford.com/jsmin.html USE YOUR OWN COPY. IT IS EXTREMELY UNWISE TO LOAD CODE FROM SERVERS YOU DO NOT CONTROL. This file creates a global JSON object containing two methods: stringify and parse. JSON.stringify(value, replacer, space) value any JavaScript value, usually an object or array. replacer an optional parameter that determines how object values are stringified for objects. It can be a function or an array of strings. space an optional parameter that specifies the indentation of nested structures. If it is omitted, the text will be packed without extra whitespace. If it is a number, it will specify the number of spaces to indent at each level. If it is a string (such as '\t' or '&nbsp;'), it contains the characters used to indent at each level. This method produces a JSON text from a JavaScript value. When an object value is found, if the object contains a toJSON method, its toJSON method will be called and the result will be stringified. A toJSON method does not serialize: it returns the value represented by the name/value pair that should be serialized, or undefined if nothing should be serialized. The toJSON method will be passed the key associated with the value, and this will be bound to the value For example, this would serialize Dates as ISO strings. Date.prototype.toJSON = function (key) { function f(n) { // Format integers to have at least two digits. return n < 10 ? '0' + n : n; } return this.getUTCFullYear() + '-' + f(this.getUTCMonth() + 1) + '-' + f(this.getUTCDate()) + 'T' + f(this.getUTCHours()) + ':' + f(this.getUTCMinutes()) + ':' + f(this.getUTCSeconds()) + 'Z'; }; You can provide an optional replacer method. It will be passed the key and value of each member, with this bound to the containing object. The value that is returned from your method will be serialized. If your method returns undefined, then the member will be excluded from the serialization. If the replacer parameter is an array of strings, then it will be used to select the members to be serialized. It filters the results such that only members with keys listed in the replacer array are stringified. Values that do not have JSON representations, such as undefined or functions, will not be serialized. Such values in objects will be dropped; in arrays they will be replaced with null. You can use a replacer function to replace those with JSON values. JSON.stringify(undefined) returns undefined. The optional space parameter produces a stringification of the value that is filled with line breaks and indentation to make it easier to read. If the space parameter is a non-empty string, then that string will be used for indentation. If the space parameter is a number, then the indentation will be that many spaces. Example: text = JSON.stringify(['e', {pluribus: 'unum'}]); // text is '["e",{"pluribus":"unum"}]' text = JSON.stringify(['e', {pluribus: 'unum'}], null, '\t'); // text is '[\n\t"e",\n\t{\n\t\t"pluribus": "unum"\n\t}\n]' text = JSON.stringify([new Date()], function (key, value) { return this[key] instanceof Date ? 'Date(' + this[key] + ')' : value; }); // text is '["Date(---current time---)"]' JSON.parse(text, reviver) This method parses a JSON text to produce an object or array. It can throw a SyntaxError exception. The optional reviver parameter is a function that can filter and transform the results. It receives each of the keys and values, and its return value is used instead of the original value. If it returns what it received, then the structure is not modified. If it returns undefined then the member is deleted. Example: // Parse the text. Values that look like ISO date strings will // be converted to Date objects. myData = JSON.parse(text, function (key, value) { var a; if (typeof value === 'string') { a = /^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2}(?:\.\d*)?)Z$/.exec(value); if (a) { return new Date(Date.UTC(+a[1], +a[2] - 1, +a[3], +a[4], +a[5], +a[6])); } } return value; }); myData = JSON.parse('["Date(09/09/2001)"]', function (key, value) { var d; if (typeof value === 'string' && value.slice(0, 5) === 'Date(' && value.slice(-1) === ')') { d = new Date(value.slice(5, -1)); if (d) { return d; } } return value; }); This is a reference implementation. You are free to copy, modify, or redistribute. */ /*jslint evil: true, regexp: true */ /*members "", "\b", "\t", "\n", "\f", "\r", "\"", JSON, "\\", apply, call, charCodeAt, getUTCDate, getUTCFullYear, getUTCHours, getUTCMinutes, getUTCMonth, getUTCSeconds, hasOwnProperty, join, lastIndex, length, parse, prototype, push, replace, slice, stringify, test, toJSON, toString, valueOf */ // Create a JSON object only if one does not already exist. We create the // methods in a closure to avoid creating global variables. (function () { 'use strict'; var JSON = module.exports = {}; function f(n) { // Format integers to have at least two digits. return n < 10 ? '0' + n : n; } if (typeof Date.prototype.toJSON !== 'function') { Date.prototype.toJSON = function () { return isFinite(this.valueOf()) ? this.getUTCFullYear() + '-' + f(this.getUTCMonth() + 1) + '-' + f(this.getUTCDate()) + 'T' + f(this.getUTCHours()) + ':' + f(this.getUTCMinutes()) + ':' + f(this.getUTCSeconds()) + 'Z' : null; }; String.prototype.toJSON = Number.prototype.toJSON = Boolean.prototype.toJSON = function () { return this.valueOf(); }; } var cx, escapable, gap, indent, meta, rep; function quote(string) { // If the string contains no control characters, no quote characters, and no // backslash characters, then we can safely slap some quotes around it. // Otherwise we must also replace the offending characters with safe escape // sequences. escapable.lastIndex = 0; return escapable.test(string) ? '"' + string.replace(escapable, function (a) { var c = meta[a]; return typeof c === 'string' ? c : '\\u' + ('0000' + a.charCodeAt(0).toString(16)).slice(-4); }) + '"' : '"' + string + '"'; } function str(key, holder) { // Produce a string from holder[key]. var i, // The loop counter. k, // The member key. v, // The member value. length, mind = gap, partial, value = holder[key]; // If the value has a toJSON method, call it to obtain a replacement value. if (value && typeof value === 'object' && typeof value.toJSON === 'function') { value = value.toJSON(key); } // If we were called with a replacer function, then call the replacer to // obtain a replacement value. if (typeof rep === 'function') { value = rep.call(holder, key, value); } // What happens next depends on the value's type. switch (typeof value) { case 'string': return quote(value); case 'number': // JSON numbers must be finite. Encode non-finite numbers as null. return isFinite(value) ? String(value) : 'null'; case 'boolean': case 'null': // If the value is a boolean or null, convert it to a string. Note: // typeof null does not produce 'null'. The case is included here in // the remote chance that this gets fixed someday. return String(value); // If the type is 'object', we might be dealing with an object or an array or // null. case 'object': // Due to a specification blunder in ECMAScript, typeof null is 'object', // so watch out for that case. if (!value) { return 'null'; } // Make an array to hold the partial results of stringifying this object value. gap += indent; partial = []; // Is the value an array? if (Object.prototype.toString.apply(value) === '[object Array]') { // The value is an array. Stringify every element. Use null as a placeholder // for non-JSON values. length = value.length; for (i = 0; i < length; i += 1) { partial[i] = str(i, value) || 'null'; } // Join all of the elements together, separated with commas, and wrap them in // brackets. v = partial.length === 0 ? '[]' : gap ? '[\n' + gap + partial.join(',\n' + gap) + '\n' + mind + ']' : '[' + partial.join(',') + ']'; gap = mind; return v; } // If the replacer is an array, use it to select the members to be stringified. if (rep && typeof rep === 'object') { length = rep.length; for (i = 0; i < length; i += 1) { if (typeof rep[i] === 'string') { k = rep[i]; v = str(k, value); if (v) { partial.push(quote(k) + (gap ? ': ' : ':') + v); } } } } else { // Otherwise, iterate through all of the keys in the object. for (k in value) { if (Object.prototype.hasOwnProperty.call(value, k)) { v = str(k, value); if (v) { partial.push(quote(k) + (gap ? ': ' : ':') + v); } } } } // Join all of the member texts together, separated with commas, // and wrap them in braces. v = partial.length === 0 ? '{}' : gap ? '{\n' + gap + partial.join(',\n' + gap) + '\n' + mind + '}' : '{' + partial.join(',') + '}'; gap = mind; return v; } } // If the JSON object does not yet have a stringify method, give it one. if (typeof JSON.stringify !== 'function') { escapable = /[\\\"\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g; meta = { // table of character substitutions '\b': '\\b', '\t': '\\t', '\n': '\\n', '\f': '\\f', '\r': '\\r', '"' : '\\"', '\\': '\\\\' }; JSON.stringify = function (value, replacer, space) { // The stringify method takes a value and an optional replacer, and an optional // space parameter, and returns a JSON text. The replacer can be a function // that can replace values, or an array of strings that will select the keys. // A default replacer method can be provided. Use of the space parameter can // produce text that is more easily readable. var i; gap = ''; indent = ''; // If the space parameter is a number, make an indent string containing that // many spaces. if (typeof space === 'number') { for (i = 0; i < space; i += 1) { indent += ' '; } // If the space parameter is a string, it will be used as the indent string. } else if (typeof space === 'string') { indent = space; } // If there is a replacer, it must be a function or an array. // Otherwise, throw an error. rep = replacer; if (replacer && typeof replacer !== 'function' && (typeof replacer !== 'object' || typeof replacer.length !== 'number')) { throw new Error('JSON.stringify'); } // Make a fake root object containing our value under the key of ''. // Return the result of stringifying the value. return str('', {'': value}); }; } // If the JSON object does not yet have a parse method, give it one. if (typeof JSON.parse !== 'function') { cx = /[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g; JSON.parse = function (text, reviver) { // The parse method takes a text and an optional reviver function, and returns // a JavaScript value if the text is a valid JSON text. var j; function walk(holder, key) { // The walk method is used to recursively walk the resulting structure so // that modifications can be made. var k, v, value = holder[key]; if (value && typeof value === 'object') { for (k in value) { if (Object.prototype.hasOwnProperty.call(value, k)) { v = walk(value, k); if (v !== undefined) { value[k] = v; } else { delete value[k]; } } } } return reviver.call(holder, key, value); } // Parsing happens in four stages. In the first stage, we replace certain // Unicode characters with escape sequences. JavaScript handles many characters // incorrectly, either silently deleting them, or treating them as line endings. text = String(text); cx.lastIndex = 0; if (cx.test(text)) { text = text.replace(cx, function (a) { return '\\u' + ('0000' + a.charCodeAt(0).toString(16)).slice(-4); }); } // In the second stage, we run the text against regular expressions that look // for non-JSON patterns. We are especially concerned with '()' and 'new' // because they can cause invocation, and '=' because it can cause mutation. // But just to be safe, we want to reject all unexpected forms. // We split the second stage into 4 regexp operations in order to work around // crippling inefficiencies in IE's and Safari's regexp engines. First we // replace the JSON backslash pairs with '@' (a non-JSON character). Second, we // replace all simple value tokens with ']' characters. Third, we delete all // open brackets that follow a colon or comma or that begin the text. Finally, // we look to see that the remaining characters are only whitespace or ']' or // ',' or ':' or '{' or '}'. If that is so, then the text is safe for eval. if (/^[\],:{}\s]*$/ .test(text.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g, '@') .replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, ']') .replace(/(?:^|:|,)(?:\s*\[)+/g, ''))) { // In the third stage we use the eval function to compile the text into a // JavaScript structure. The '{' operator is subject to a syntactic ambiguity // in JavaScript: it can begin a block or an object literal. We wrap the text // in parens to eliminate the ambiguity. j = eval('(' + text + ')'); // In the optional fourth stage, we recursively walk the new structure, passing // each name/value pair to a reviver function for possible transformation. return typeof reviver === 'function' ? walk({'': j}, '') : j; } // If the text is not JSON parseable, then a SyntaxError is thrown. throw new SyntaxError('JSON.parse'); }; } }()); }, {}], 32: [function(require, module, exports) { /** * Module dependencies. */ var integration = require('analytics.js-integration'); var push = require('global-queue')('_fbq'); var each = require('each'); /** * HOP */ var has = Object.prototype.hasOwnProperty; /** * Expose `Facebook` */ var Facebook = module.exports = integration('Facebook Conversion Tracking') .global('_fbq') .option('currency', 'USD') .tag('<script src="//connect.facebook.net/en_US/fbds.js">') .mapping('events'); /** * Initialize Facebook Conversion Tracking * * https://developers.facebook.com/docs/ads-for-websites/conversion-pixel-code-migration * * @param {Object} page */ Facebook.prototype.initialize = function(page){ window._fbq = window._fbq || []; this.load(this.ready); window._fbq.loaded = true; }; /** * Loaded? * * @return {Boolean} */ Facebook.prototype.loaded = function(){ return !! (window._fbq && window._fbq.loaded); }; /** * Page. * * @param {Page} page */ Facebook.prototype.page = function(page){ var name = page.fullName(); this.track(page.track(name)); } /** * Track. * * https://developers.facebook.com/docs/reference/ads-api/custom-audience-website-faq/#fbpixel * * @param {Track} track */ Facebook.prototype.track = function(track){ var event = track.event(); var events = this.events(event); var revenue = track.revenue() || 0; var self = this; each(events, function(event){ push('track', event, { value: String(revenue.toFixed(2)), currency: self.options.currency }); }); }; }, {"analytics.js-integration":89,"global-queue":160,"each":4}], 33: [function(require, module, exports) { /** * Module dependencies. */ var push = require('global-queue')('_fxm'); var integration = require('analytics.js-integration'); var Track = require('facade').Track; var each = require('each'); /** * Expose `FoxMetrics` integration. */ var FoxMetrics = module.exports = integration('FoxMetrics') .assumesPageview() .global('_fxm') .option('appId', '') .tag('<script src="//d35tca7vmefkrc.cloudfront.net/scripts/{{ appId }}.js">'); /** * Initialize. * * http://foxmetrics.com/documentation/apijavascript * * @param {Object} page */ FoxMetrics.prototype.initialize = function(page){ window._fxm = window._fxm || []; this.load(this.ready); }; /** * Loaded? * * @return {Boolean} */ FoxMetrics.prototype.loaded = function(){ return !! (window._fxm && window._fxm.appId); }; /** * Page. * * @param {Page} page */ FoxMetrics.prototype.page = function(page){ var properties = page.proxy('properties'); var category = page.category(); var name = page.name(); this._category = category; // store for later push( '_fxm.pages.view', properties.title, // title name, // name category, // category properties.url, // url properties.referrer // referrer ); }; /** * Identify. * * @param {Identify} identify */ FoxMetrics.prototype.identify = function(identify){ var id = identify.userId(); if (!id) return; push( '_fxm.visitor.profile', id, // user id identify.firstName(), // first name identify.lastName(), // last name identify.email(), // email identify.address(), // address undefined, // social undefined, // partners identify.traits() // attributes ); }; /** * Track. * * @param {Track} track */ FoxMetrics.prototype.track = function(track){ var props = track.properties(); var category = this._category || props.category; push(track.event(), category, props); }; /** * Viewed product. * * @param {Track} track * @api private */ FoxMetrics.prototype.viewedProduct = function(track){ ecommerce('productview', track); }; /** * Removed product. * * @param {Track} track * @api private */ FoxMetrics.prototype.removedProduct = function(track){ ecommerce('removecartitem', track); }; /** * Added product. * * @param {Track} track * @api private */ FoxMetrics.prototype.addedProduct = function(track){ ecommerce('cartitem', track); }; /** * Completed Order. * * @param {Track} track * @api private */ FoxMetrics.prototype.completedOrder = function(track){ var orderId = track.orderId(); // transaction push( '_fxm.ecommerce.order', orderId, track.subtotal(), track.shipping(), track.tax(), track.city(), track.state(), track.zip(), track.quantity() ); // items each(track.products(), function(product){ var track = new Track({ properties: product }); ecommerce('purchaseitem', track, [ track.quantity(), track.price(), orderId ]); }); }; /** * Track ecommerce `event` with `track` * with optional `arr` to append. * * @param {String} event * @param {Track} track * @param {Array} arr * @api private */ function ecommerce(event, track, arr){ push.apply(null, [ '_fxm.ecommerce.' + event, track.id() || track.sku(), track.name(), track.category() ].concat(arr || [])); } }, {"global-queue":160,"analytics.js-integration":89,"facade":133,"each":4}], 34: [function(require, module, exports) { /** * Module dependencies. */ var integration = require('analytics.js-integration'); var bind = require('bind'); var when = require('when'); var is = require('is'); /** * Expose `Frontleaf` integration. */ var Frontleaf = module.exports = integration('Frontleaf') .global('_fl') .global('_flBaseUrl') .option('baseUrl', 'https://api.frontleaf.com') .option('token', '') .option('stream', '') .option('trackNamedPages', false) .option('trackCategorizedPages', false) .tag('<script id="_fl" src="{{ baseUrl }}/lib/tracker.js">'); /** * Initialize. * * http://docs.frontleaf.com/#/technical-implementation/tracking-customers/tracking-beacon * * @param {Object} page */ Frontleaf.prototype.initialize = function(page){ window._fl = window._fl || []; window._flBaseUrl = window._flBaseUrl || this.options.baseUrl; this._push('setApiToken', this.options.token); this._push('setStream', this.options.stream); var loaded = bind(this, this.loaded); var ready = this.ready; this.load({ baseUrl: window._flBaseUrl }, this.ready); }; /** * Loaded? * * @return {Boolean} */ Frontleaf.prototype.loaded = function(){ return is.array(window._fl) && window._fl.ready === true; }; /** * Identify. * * @param {Identify} identify */ Frontleaf.prototype.identify = function(identify){ var userId = identify.userId(); if (userId) { this._push('setUser', { id: userId, name: identify.name() || identify.username(), data: clean(identify.traits()) }); } }; /** * Group. * * @param {Group} group */ Frontleaf.prototype.group = function(group){ var groupId = group.groupId(); if (groupId) { this._push('setAccount', { id: groupId, name: group.proxy('traits.name'), data: clean(group.traits()) }); } }; /** * Page. * * @param {Page} page */ Frontleaf.prototype.page = function(page){ var category = page.category(); var name = page.fullName(); var opts = this.options; // categorized pages if (category && opts.trackCategorizedPages) { this.track(page.track(category)); } // named pages if (name && opts.trackNamedPages) { this.track(page.track(name)); } }; /** * Track. * * @param {Track} track */ Frontleaf.prototype.track = function(track){ var event = track.event(); this._push('event', event, clean(track.properties())); }; /** * Push a command onto the global Frontleaf queue. * * @param {String} command * @return {Object} args * @api private */ Frontleaf.prototype._push = function(command){ var args = [].slice.call(arguments, 1); window._fl.push(function(t){ t[command].apply(command, args); }); }; /** * Clean all nested objects and arrays. * * @param {Object} obj * @return {Object} * @api private */ function clean(obj){ var ret = {}; // Remove traits/properties that are already represented // outside of the data container var excludeKeys = ["id","name","firstName","lastName"]; var len = excludeKeys.length; for (var i = 0; i < len; i++) { clear(obj, excludeKeys[i]); } // Flatten nested hierarchy, preserving arrays obj = flatten(obj); // Discard nulls, represent arrays as comma-separated strings for (var key in obj) { var val = obj[key]; if (null == val) { continue; } if (is.array(val)) { ret[key] = val.toString(); continue; } ret[key] = val; } return ret; } /** * Remove a property from an object if set. * * @param {Object} obj * @param {String} key * @api private */ function clear(obj, key){ if (obj.hasOwnProperty(key)) { delete obj[key]; } } /** * Flatten a nested object into a single level space-delimited * hierarchy. * * Based on https://github.com/hughsk/flat * * @param {Object} source * @return {Object} * @api private */ function flatten(source){ var output = {}; function step(object, prev){ for (var key in object) { var value = object[key]; var newKey = prev ? prev + ' ' + key : key; if (!is.array(value) && is.object(value)) { return step(value, newKey); } output[newKey] = value; } } step(source); return output; } }, {"analytics.js-integration":89,"bind":102,"when":132,"is":92}], 35: [function(require, module, exports) { /** * Module dependencies. */ var foldl = require('foldl'); var is = require('is'); var camel = require('to-camel-case'); var integration = require('analytics.js-integration'); /** * Expose `FullStory` integration. * * https://www.fullstory.com/docs/developer */ var FullStory = module.exports = integration('FullStory') .option('org', '') .option('debug', false) .tag('<script src="https://www.fullstory.com/s/fs.js"></script>') /** * Initialize. */ FullStory.prototype.initialize = function(){ var self = this; window._fs_debug = this.options.debug; window._fs_host = 'www.fullstory.com'; window._fs_org = this.options.org; (function(m,n,e,t,l,o,g,y){ g=m[e]=function(a,b){g.q?g.q.push([a,b]):g._api(a,b);};g.q=[]; // jscs:disable g.identify=function(i,v){g(l,{uid:i});if(v)g(l,v)};g.setUserVars=function(v){FS(l,v)}; // jscs:enable g.setSessionVars=function(v){FS('session',v)};g.setPageVars=function(v){FS('page',v)}; self.ready(); self.load(); })(window,document,'FS','script','user'); }; /** * Loaded? * * @return {Boolean} */ FullStory.prototype.loaded = function(){ return !! window.FS; }; /** * Identify. * * @param {Identify} identify */ FullStory.prototype.identify = function(identify){ var id = identify.userId() || identify.anonymousId(); var traits = identify.traits({ name: 'displayName' }); var newTraits = foldl(function(results, value, key){ if (key !== 'id') results[key === 'displayName' || key === 'email' ? key : convert(key, value)] = value; return results; }, {}, traits); window.FS.identify(String(id), newTraits); }; /** * Convert to FullStory format. * * @param {String} trait * @param {Property} value */ function convert (trait, value) { trait = camel(trait); if (is.string(value)) return trait += '_str'; if (isInt(value)) return trait += '_int'; if (isFloat(value)) return trait += '_real'; if (is.date(value)) return trait += '_date'; if (is.boolean(value)) return trait += '_bool'; } /** * Check if n is a float. */ function isFloat(n) { return n === +n && n !== (n|0); } /** * Check if n is an integer. */ function isInt(n) { return n === +n && n === (n|0); } }, {"foldl":167,"is":92,"to-camel-case":168,"analytics.js-integration":89}], 167: [function(require, module, exports) { 'use strict'; /** * Module dependencies. */ // XXX: Hacky fix for Duo not supporting scoped modules var each; try { each = require('@ndhoule/each'); } catch(e) { each = require('each'); } /** * Reduces all the values in a collection down into a single value. Does so by iterating through the * collection from left to right, repeatedly calling an `iterator` function and passing to it four * arguments: `(accumulator, value, index, collection)`. * * Returns the final return value of the `iterator` function. * * @name foldl * @api public * @param {Function} iterator The function to invoke per iteration. * @param {*} accumulator The initial accumulator value, passed to the first invocation of `iterator`. * @param {Array|Object} collection The collection to iterate over. * @return {*} The return value of the final call to `iterator`. * @example * foldl(function(total, n) { * return total + n; * }, 0, [1, 2, 3]); * //=> 6 * * var phonebook = { bob: '555-111-2345', tim: '655-222-6789', sheila: '655-333-1298' }; * * foldl(function(results, phoneNumber) { * if (phoneNumber[0] === '6') { * return results.concat(phoneNumber); * } * return results; * }, [], phonebook); * // => ['655-222-6789', '655-333-1298'] */ var foldl = function foldl(iterator, accumulator, collection) { if (typeof iterator !== 'function') { throw new TypeError('Expected a function but received a ' + typeof iterator); } each(function(val, i, collection) { accumulator = iterator(accumulator, val, i, collection); }, collection); return accumulator; }; /** * Exports. */ module.exports = foldl; }, {"each":169}], 169: [function(require, module, exports) { 'use strict'; /** * Module dependencies. */ // XXX: Hacky fix for Duo not supporting scoped modules var keys; try { keys = require('@ndhoule/keys'); } catch(e) { keys = require('keys'); } /** * Object.prototype.toString reference. */ var objToString = Object.prototype.toString; /** * Tests if a value is a number. * * @name isNumber * @api private * @param {*} val The value to test. * @return {boolean} Returns `true` if `val` is a number, otherwise `false`. */ // TODO: Move to library var isNumber = function isNumber(val) { var type = typeof val; return type === 'number' || (type === 'object' && objToString.call(val) === '[object Number]'); }; /** * Tests if a value is an array. * * @name isArray * @api private * @param {*} val The value to test. * @return {boolean} Returns `true` if the value is an array, otherwise `false`. */ // TODO: Move to library var isArray = typeof Array.isArray === 'function' ? Array.isArray : function isArray(val) { return objToString.call(val) === '[object Array]'; }; /** * Tests if a value is array-like. Array-like means the value is not a function and has a numeric * `.length` property. * * @name isArrayLike * @api private * @param {*} val * @return {boolean} */ // TODO: Move to library var isArrayLike = function isArrayLike(val) { return val != null && (isArray(val) || (val !== 'function' && isNumber(val.length))); }; /** * Internal implementation of `each`. Works on arrays and array-like data structures. * * @name arrayEach * @api private * @param {Function(value, key, collection)} iterator The function to invoke per iteration. * @param {Array} array The array(-like) structure to iterate over. * @return {undefined} */ var arrayEach = function arrayEach(iterator, array) { for (var i = 0; i < array.length; i += 1) { // Break iteration early if `iterator` returns `false` if (iterator(array[i], i, array) === false) { break; } } }; /** * Internal implementation of `each`. Works on objects. * * @name baseEach * @api private * @param {Function(value, key, collection)} iterator The function to invoke per iteration. * @param {Object} object The object to iterate over. * @return {undefined} */ var baseEach = function baseEach(iterator, object) { var ks = keys(object); for (var i = 0; i < ks.length; i += 1) { // Break iteration early if `iterator` returns `false` if (iterator(object[ks[i]], ks[i], object) === false) { break; } } }; /** * Iterate over an input collection, invoking an `iterator` function for each element in the * collection and passing to it three arguments: `(value, index, collection)`. The `iterator` * function can end iteration early by returning `false`. * * @name each * @api public * @param {Function(value, key, collection)} iterator The function to invoke per iteration. * @param {Array|Object|string} collection The collection to iterate over. * @return {undefined} Because `each` is run only for side effects, always returns `undefined`. * @example * var log = console.log.bind(console); * * each(log, ['a', 'b', 'c']); * //-> 'a', 0, ['a', 'b', 'c'] * //-> 'b', 1, ['a', 'b', 'c'] * //-> 'c', 2, ['a', 'b', 'c'] * //=> undefined * * each(log, 'tim'); * //-> 't', 2, 'tim' * //-> 'i', 1, 'tim' * //-> 'm', 0, 'tim' * //=> undefined * * // Note: Iteration order not guaranteed across environments * each(log, { name: 'tim', occupation: 'enchanter' }); * //-> 'tim', 'name', { name: 'tim', occupation: 'enchanter' } * //-> 'enchanter', 'occupation', { name: 'tim', occupation: 'enchanter' } * //=> undefined */ var each = function each(iterator, collection) { return (isArrayLike(collection) ? arrayEach : baseEach).call(this, iterator, collection); }; /** * Exports. */ module.exports = each; }, {"keys":170}], 170: [function(require, module, exports) { 'use strict'; /** * charAt reference. */ var strCharAt = String.prototype.charAt; /** * Returns the character at a given index. * * @param {string} str * @param {number} index * @return {string|undefined} */ // TODO: Move to a library var charAt = function(str, index) { return strCharAt.call(str, index); }; /** * hasOwnProperty reference. */ var hop = Object.prototype.hasOwnProperty; /** * Object.prototype.toString reference. */ var toStr = Object.prototype.toString; /** * hasOwnProperty, wrapped as a function. * * @name has * @api private * @param {*} context * @param {string|number} prop * @return {boolean} */ // TODO: Move to a library var has = function has(context, prop) { return hop.call(context, prop); }; /** * Returns true if a value is a string, otherwise false. * * @name isString * @api private * @param {*} val * @return {boolean} */ // TODO: Move to a library var isString = function isString(val) { return toStr.call(val) === '[object String]'; }; /** * Returns true if a value is array-like, otherwise false. Array-like means a * value is not null, undefined, or a function, and has a numeric `length` * property. * * @name isArrayLike * @api private * @param {*} val * @return {boolean} */ // TODO: Move to a library var isArrayLike = function isArrayLike(val) { return val != null && (typeof val !== 'function' && typeof val.length === 'number'); }; /** * indexKeys * * @name indexKeys * @api private * @param {} target * @param {} pred * @return {Array} */ var indexKeys = function indexKeys(target, pred) { pred = pred || has; var results = []; for (var i = 0, len = target.length; i < len; i += 1) { if (pred(target, i)) { results.push(String(i)); } } return results; }; /** * Returns an array of all the owned * * @name objectKeys * @api private * @param {*} target * @param {Function} pred Predicate function used to include/exclude values from * the resulting array. * @return {Array} */ var objectKeys = function objectKeys(target, pred) { pred = pred || has; var results = []; for (var key in target) { if (pred(target, key)) { results.push(String(key)); } } return results; }; /** * Creates an array composed of all keys on the input object. Ignores any non-enumerable properties. * More permissive than the native `Object.keys` function (non-objects will not throw errors). * * @name keys * @api public * @category Object * @param {Object} source The value to retrieve keys from. * @return {Array} An array containing all the input `source`'s keys. * @example * keys({ likes: 'avocado', hates: 'pineapple' }); * //=> ['likes', 'pineapple']; * * // Ignores non-enumerable properties * var hasHiddenKey = { name: 'Tim' }; * Object.defineProperty(hasHiddenKey, 'hidden', { * value: 'i am not enumerable!', * enumerable: false * }) * keys(hasHiddenKey); * //=> ['name']; * * // Works on arrays * keys(['a', 'b', 'c']); * //=> ['0', '1', '2'] * * // Skips unpopulated indices in sparse arrays * var arr = [1]; * arr[4] = 4; * keys(arr); * //=> ['0', '4'] */ module.exports = function keys(source) { if (source == null) { return []; } // IE6-8 compatibility (string) if (isString(source)) { return indexKeys(source, charAt); } // IE6-8 compatibility (arguments) if (isArrayLike(source)) { return indexKeys(source, has); } return objectKeys(source); }; }, {}], 168: [function(require, module, exports) { var toSpace = require('to-space-case'); /** * Expose `toCamelCase`. */ module.exports = toCamelCase; /** * Convert a `string` to camel case. * * @param {String} string * @return {String} */ function toCamelCase (string) { return toSpace(string).replace(/\s(\w)/g, function (matches, letter) { return letter.toUpperCase(); }); } }, {"to-space-case":121}], 36: [function(require, module, exports) { /** * Module dependencies. */ var integration = require('analytics.js-integration'); var push = require('global-queue')('_gauges'); /** * Expose `Gauges` integration. */ var Gauges = module.exports = integration('Gauges') .assumesPageview() .global('_gauges') .option('siteId', '') .tag('<script id="gauges-tracker" src="//secure.gaug.es/track.js" data-site-id="{{ siteId }}">'); /** * Initialize Gauges. * * http://get.gaug.es/documentation/tracking/ * * @param {Object} page */ Gauges.prototype.initialize = function(page){ window._gauges = window._gauges || []; this.load(this.ready); }; /** * Loaded? * * @return {Boolean} */ Gauges.prototype.loaded = function(){ return !! (window._gauges && window._gauges.push !== Array.prototype.push); }; /** * Page. * * @param {Page} page */ Gauges.prototype.page = function(page){ push('track'); }; }, {"analytics.js-integration":89,"global-queue":160}], 37: [function(require, module, exports) { /** * Module dependencies. */ var integration = require('analytics.js-integration'); var onBody = require('on-body'); /** * Expose `GetSatisfaction` integration. */ var GetSatisfaction = module.exports = integration('Get Satisfaction') .assumesPageview() .global('GSFN') .option('widgetId', '') .tag('<script src="https://loader.engage.gsfn.us/loader.js">'); /** * Initialize. * * https://console.getsatisfaction.com/start/101022?signup=true#engage * * @param {Object} page */ GetSatisfaction.prototype.initialize = function(page){ var self = this; var widget = this.options.widgetId; var div = document.createElement('div'); var id = div.id = 'getsat-widget-' + widget; onBody(function(body){ body.appendChild(div); }); // usually the snippet is sync, so wait for it before initializing the tab this.load(function(){ window.GSFN.loadWidget(widget, { containerId: id }); self.ready(); }); }; /** * Loaded? * * @return {Boolean} */ GetSatisfaction.prototype.loaded = function(){ return !! window.GSFN; }; }, {"analytics.js-integration":89,"on-body":130}], 38: [function(require, module, exports) { /** * Module dependencies. */ var integration = require('analytics.js-integration'); var push = require('global-queue')('_gaq'); var length = require('object').length; var canonical = require('canonical'); var useHttps = require('use-https'); var Track = require('facade').Track; var callback = require('callback'); var defaults = require('defaults'); var load = require('load-script'); var keys = require('object').keys; var select = require('select'); var dot = require('obj-case'); var each = require('each'); var type = require('type'); var url = require('url'); var is = require('is'); var group; var user; /** * Expose plugin. */ module.exports = exports = function(analytics){ analytics.addIntegration(GA); group = analytics.group(); user = analytics.user(); }; /** * Expose `GA` integration. * * http://support.google.com/analytics/bin/answer.py?hl=en&answer=2558867 * https://developers.google.com/analytics/devguides/collection/gajs/methods/gaJSApiBasicConfiguration#_gat.GA_Tracker_._setSiteSpeedSampleRate */ var GA = exports.Integration = integration('Google Analytics') .readyOnLoad() .global('ga') .global('gaplugins') .global('_gaq') .global('GoogleAnalyticsObject') .option('anonymizeIp', false) .option('classic', false) .option('domain', 'auto') .option('doubleClick', false) .option('enhancedEcommerce', false) .option('enhancedLinkAttribution', false) .option('nonInteraction', false) .option('ignoredReferrers', null) .option('includeSearch', false) .option('siteSpeedSampleRate', 1) .option('trackingId', '') .option('trackNamedPages', true) .option('trackCategorizedPages', true) .option('sendUserId', false) .option('metrics', {}) .option('dimensions', {}) .tag('library', '<script src="//www.google-analytics.com/analytics.js">') .tag('double click', '<script src="//stats.g.doubleclick.net/dc.js">') .tag('http', '<script src="http://www.google-analytics.com/ga.js">') .tag('https', '<script src="https://ssl.google-analytics.com/ga.js">'); /** * On `construct` swap any config-based methods to the proper implementation. */ GA.on('construct', function(integration){ if (integration.options.classic) { integration.initialize = integration.initializeClassic; integration.loaded = integration.loadedClassic; integration.page = integration.pageClassic; integration.track = integration.trackClassic; integration.completedOrder = integration.completedOrderClassic; } else if (integration.options.enhancedEcommerce) { integration.viewedProduct = integration.viewedProductEnhanced; integration.clickedProduct = integration.clickedProductEnhanced; integration.addedProduct = integration.addedProductEnhanced; integration.removedProduct = integration.removedProductEnhanced; integration.startedOrder = integration.startedOrderEnhanced; integration.viewedCheckoutStep = integration.viewedCheckoutStepEnhanced; integration.completedCheckoutStep = integration.completedCheckoutStepEnhanced; integration.updatedOrder = integration.updatedOrderEnhanced; integration.completedOrder = integration.completedOrderEnhanced; integration.refundedOrder = integration.refundedOrderEnhanced; integration.viewedPromotion = integration.viewedPromotionEnhanced; integration.clickedPromotion = integration.clickedPromotionEnhanced; } }); /** * Initialize. * * https://developers.google.com/analytics/devguides/collection/analyticsjs/advanced */ GA.prototype.initialize = function(){ var opts = this.options; // setup the tracker globals window.GoogleAnalyticsObject = 'ga'; window.ga = window.ga || function(){ window.ga.q = window.ga.q || []; window.ga.q.push(arguments); }; window.ga.l = new Date().getTime(); if (window.location.hostname === 'localhost') opts.domain = 'none'; window.ga('create', opts.trackingId, { cookieDomain: opts.domain || GA.prototype.defaults.domain, // to protect against empty string siteSpeedSampleRate: opts.siteSpeedSampleRate, allowLinker: true }); // display advertising if (opts.doubleClick) { window.ga('require', 'displayfeatures'); } // send global id if (opts.sendUserId && user.id()) { window.ga('set', 'userId', user.id()); } // anonymize after initializing, otherwise a warning is shown // in google analytics debugger if (opts.anonymizeIp) window.ga('set', 'anonymizeIp', true); // custom dimensions & metrics var custom = metrics(user.traits(), opts); if (length(custom)) window.ga('set', custom); this.load('library', this.ready); }; /** * Loaded? * * @return {Boolean} */ GA.prototype.loaded = function(){ return !! window.gaplugins; }; /** * Page. * * https://developers.google.com/analytics/devguides/collection/analyticsjs/pages * https://developers.google.com/analytics/devguides/collection/analyticsjs/single-page-applications#multiple-hits * * * @param {Page} page */ GA.prototype.page = function(page){ var category = page.category(); var props = page.properties(); var name = page.fullName(); var opts = this.options; var campaign = page.proxy('context.campaign') || {}; var pageview = {}; var pagePath = path(props, this.options); var pageTitle = name || props.title; var track; this._category = category; // store for later pageview.page = pagePath; pageview.title = pageTitle; pageview.location = props.url; if (campaign.name) pageview.campaignName = campaign.name; if (campaign.source) pageview.campaignSource = campaign.source; if (campaign.medium) pageview.campaignMedium = campaign.medium; if (campaign.content) pageview.campaignContent = campaign.content; if (campaign.term) pageview.campaignKeyword = campaign.term; // custom dimensions and metrics var custom = metrics(props, opts); if (length(custom)) window.ga('set', custom); // set window.ga('set', { page: pagePath, title: pageTitle }); // send window.ga('send', 'pageview', pageview); // categorized pages if (category && this.options.trackCategorizedPages) { track = page.track(category); this.track(track, { nonInteraction: 1 }); } // named pages if (name && this.options.trackNamedPages) { track = page.track(name); this.track(track, { nonInteraction: 1 }); } }; /** * Identify. * * @param {Identify} event */ GA.prototype.identify = function(identify){ var opts = this.options; //set userId if (opts.sendUserId && identify.userId()) { window.ga('set', 'userId', identify.userId()); } //set dimensions var custom = metrics(user.traits(), opts); if (length(custom)) window.ga('set', custom); }; /** * Track. * * https://developers.google.com/analytics/devguides/collection/analyticsjs/events * https://developers.google.com/analytics/devguides/collection/analyticsjs/field-reference * * @param {Track} event */ GA.prototype.track = function(track, options){ var contextOpts = track.options(this.name); var interfaceOpts = this.options; var opts = defaults(options || {}, contextOpts); opts = defaults(opts, interfaceOpts); var props = track.properties(); var campaign = track.proxy('context.campaign') || {}; // custom dimensions & metrics var custom = metrics(props, interfaceOpts); if (length(custom)) window.ga('set', custom); var payload = { eventAction: track.event(), eventCategory: props.category || this._category || 'All', eventLabel: props.label, eventValue: formatValue(props.value || track.revenue()), nonInteraction: !!(props.nonInteraction || opts.nonInteraction) }; if (campaign.name) payload.campaignName = campaign.name; if (campaign.source) payload.campaignSource = campaign.source; if (campaign.medium) payload.campaignMedium = campaign.medium; if (campaign.content) payload.campaignContent = campaign.content; if (campaign.term) payload.campaignKeyword = campaign.term; window.ga('send', 'event', payload); }; /** * Completed order. * * https://developers.google.com/analytics/devguides/collection/analyticsjs/ecommerce * https://developers.google.com/analytics/devguides/collection/analyticsjs/ecommerce#multicurrency * * @param {Track} track * @api private */ GA.prototype.completedOrder = function(track){ var total = track.total() || track.revenue() || 0; var orderId = track.orderId(); var products = track.products(); var props = track.properties(); // orderId is required. if (!orderId) return; // require ecommerce if (!this.ecommerce) { window.ga('require', 'ecommerce'); this.ecommerce = true; } // add transaction window.ga('ecommerce:addTransaction', { affiliation: props.affiliation, shipping: track.shipping(), revenue: total, tax: track.tax(), id: orderId, currency: track.currency() }); // add products each(products, function(product){ var productTrack = createProductTrack(track, product); window.ga('ecommerce:addItem', { category: productTrack.category(), quantity: productTrack.quantity(), price: productTrack.price(), name: productTrack.name(), sku: productTrack.sku(), id: orderId, currency: productTrack.currency() }); }); // send window.ga('ecommerce:send'); }; /** * Initialize (classic). * * https://developers.google.com/analytics/devguides/collection/gajs/methods/gaJSApiBasicConfiguration */ GA.prototype.initializeClassic = function(){ var opts = this.options; var anonymize = opts.anonymizeIp; var db = opts.doubleClick; var domain = opts.domain; var enhanced = opts.enhancedLinkAttribution; var ignore = opts.ignoredReferrers; var sample = opts.siteSpeedSampleRate; window._gaq = window._gaq || []; push('_setAccount', opts.trackingId); push('_setAllowLinker', true); if (anonymize) push('_gat._anonymizeIp'); if (domain) push('_setDomainName', domain); if (sample) push('_setSiteSpeedSampleRate', sample); if (enhanced) { var protocol = 'https:' === document.location.protocol ? 'https:' : 'http:'; var pluginUrl = protocol + '//www.google-analytics.com/plugins/ga/inpage_linkid.js'; push('_require', 'inpage_linkid', pluginUrl); } if (ignore) { if (!is.array(ignore)) ignore = [ignore]; each(ignore, function(domain){ push('_addIgnoredRef', domain); }); } if (this.options.doubleClick) { this.load('double click', this.ready); } else { var name = useHttps() ? 'https' : 'http'; this.load(name, this.ready); } }; /** * Loaded? (classic) * * @return {Boolean} */ GA.prototype.loadedClassic = function(){ return !! (window._gaq && window._gaq.push !== Array.prototype.push); }; /** * Page (classic). * * https://developers.google.com/analytics/devguides/collection/gajs/methods/gaJSApiBasicConfiguration * * @param {Page} page */ GA.prototype.pageClassic = function(page){ var opts = page.options(this.name); var category = page.category(); var props = page.properties(); var name = page.fullName(); var track; push('_trackPageview', path(props, this.options)); // categorized pages if (category && this.options.trackCategorizedPages) { track = page.track(category); this.track(track, { nonInteraction: 1 }); } // named pages if (name && this.options.trackNamedPages) { track = page.track(name); this.track(track, { nonInteraction: 1 }); } }; /** * Track (classic). * * https://developers.google.com/analytics/devguides/collection/gajs/methods/gaJSApiEventTracking * * @param {Track} track */ GA.prototype.trackClassic = function(track, options){ var opts = options || track.options(this.name); var props = track.properties(); var revenue = track.revenue(); var event = track.event(); var category = this._category || props.category || 'All'; var label = props.label; var value = formatValue(revenue || props.value); var nonInteraction = !!(props.nonInteraction || opts.nonInteraction); push('_trackEvent', category, event, label, value, nonInteraction); }; /** * Completed order. * * https://developers.google.com/analytics/devguides/collection/gajs/gaTrackingEcommerce * https://developers.google.com/analytics/devguides/collection/gajs/gaTrackingEcommerce#localcurrencies * * @param {Track} track * @api private */ GA.prototype.completedOrderClassic = function(track){ var total = track.total() || track.revenue() || 0; var orderId = track.orderId(); var products = track.products() || []; var props = track.properties(); var currency = track.currency(); // required if (!orderId) return; // add transaction push('_addTrans', orderId, props.affiliation, total, track.tax(), track.shipping(), track.city(), track.state(), track.country()); // add items each(products, function(product){ var track = new Track({ properties: product }); push('_addItem', orderId, track.sku(), track.name(), track.category(), track.price(), track.quantity()); }); // send push('_set', 'currencyCode', currency); push('_trackTrans'); }; /** * Return the path based on `properties` and `options`. * * @param {Object} properties * @param {Object} options */ function path(properties, options) { if (!properties) return; var str = properties.path; if (options.includeSearch && properties.search) str += properties.search; return str; } /** * Format the value property to Google's liking. * * @param {Number} value * @return {Number} */ function formatValue(value) { if (!value || value < 0) return 0; return Math.round(value); } /** * Map google's custom dimensions & metrics with `obj`. * * Example: * * metrics({ revenue: 1.9 }, { { metrics : { revenue: 'metric8' } }); * // => { metric8: 1.9 } * * metrics({ revenue: 1.9 }, {}); * // => {} * * @param {Object} obj * @param {Object} data * @return {Object|null} * @api private */ function metrics(obj, data){ var dimensions = data.dimensions; var metrics = data.metrics; var names = keys(metrics).concat(keys(dimensions)); var ret = {}; for (var i = 0; i < names.length; ++i) { var name = names[i]; var key = metrics[name] || dimensions[name]; var value = dot(obj, name) || obj[name]; if (null == value) continue; ret[key] = value; } return ret; } /** * Loads ec.js (unless already loaded) */ GA.prototype.loadEnhancedEcommerce = function(track){ if (!this.enhancedEcommerceLoaded) { window.ga('require', 'ec'); this.enhancedEcommerceLoaded = true; } // Ensure we set currency for every hit window.ga('set', '&cu', track.currency()); }; /** * Pushes an event and all previously set EE data to GA. */ GA.prototype.pushEnhancedEcommerce = function(track){ // Send a custom non-interaction event to ensure all EE data is pushed. // Without doing this we'd need to require page display after setting EE data. ga('send', 'event', track.category() || 'EnhancedEcommerce', track.event(), { nonInteraction: 1 }); }; /** * Started order - Enhanced Ecommerce * * https://developers.google.com/analytics/devguides/collection/analyticsjs/enhanced-ecommerce#checkout-steps * * @param {Track} track */ GA.prototype.startedOrderEnhanced = function(track){ // same as viewed checkout step #1 this.viewedCheckoutStep(track); }; /** * Updated order - Enhanced Ecommerce * * https://developers.google.com/analytics/devguides/collection/analyticsjs/enhanced-ecommerce#checkout-steps * * @param {Track} track */ GA.prototype.updatedOrderEnhanced = function(track){ // Same event as started order - will override this.startedOrderEnhanced(track); }; /** * Viewed checkout step - Enhanced Ecommerce * * https://developers.google.com/analytics/devguides/collection/analyticsjs/enhanced-ecommerce#checkout-steps * * @param {Track} track */ GA.prototype.viewedCheckoutStepEnhanced = function(track){ var products = track.products(); var props = track.properties(); var options = extractCheckoutOptions(props); this.loadEnhancedEcommerce(track); each(products, function(product){ var productTrack = createProductTrack(track, product); enhancedEcommerceTrackProduct(productTrack); }); window.ga('ec:setAction','checkout', { step: props.step || 1, option: options || undefined }); this.pushEnhancedEcommerce(track); }; /** * Completed checkout step - Enhanced Ecommerce * * https://developers.google.com/analytics/devguides/collection/analyticsjs/enhanced-ecommerce#checkout-options * * @param {Track} track */ GA.prototype.completedCheckoutStepEnhanced = function(track){ var props = track.properties(); var options = extractCheckoutOptions(props); // Only send an event if we have step and options to update if (!props.step || !options) return; this.loadEnhancedEcommerce(track); window.ga('ec:setAction', 'checkout_option', { step: props.step || 1, option: options }); window.ga('send', 'event', 'Checkout', 'Option'); }; /** * Completed order - Enhanced Ecommerce * * https://developers.google.com/analytics/devguides/collection/analyticsjs/enhanced-ecommerce#measuring-transactions * * @param {Track} track */ GA.prototype.completedOrderEnhanced = function(track){ var total = track.total() || track.revenue() || 0; var orderId = track.orderId(); var products = track.products(); var props = track.properties(); // orderId is required. if (!orderId) return; this.loadEnhancedEcommerce(track); each(products, function(product){ var productTrack = createProductTrack(track, product); enhancedEcommerceTrackProduct(productTrack); }); window.ga('ec:setAction', 'purchase', { id: orderId, affiliation: props.affiliation, revenue: total, tax: track.tax(), shipping: track.shipping(), coupon: track.coupon() }); this.pushEnhancedEcommerce(track); }; /** * Refunded order - Enhanced Ecommerce * * https://developers.google.com/analytics/devguides/collection/analyticsjs/enhanced-ecommerce#measuring-refunds * * @param {Track} track */ GA.prototype.refundedOrderEnhanced = function(track){ var orderId = track.orderId(); var products = track.products(); // orderId is required. if (!orderId) return; this.loadEnhancedEcommerce(track); // Without any products it's a full refund each(products, function(product){ var track = new Track({ properties: product }); window.ga('ec:addProduct', { id: track.id() || track.sku(), quantity: track.quantity() }); }); window.ga('ec:setAction', 'refund', { id: orderId }); this.pushEnhancedEcommerce(track); }; /** * Added product - Enhanced Ecommerce * * https://developers.google.com/analytics/devguides/collection/analyticsjs/enhanced-ecommerce#add-remove-cart * * @param {Track} track */ GA.prototype.addedProductEnhanced = function(track){ this.loadEnhancedEcommerce(track); enhancedEcommerceProductAction(track, 'add'); this.pushEnhancedEcommerce(track); }; /** * Removed product - Enhanced Ecommerce * * https://developers.google.com/analytics/devguides/collection/analyticsjs/enhanced-ecommerce#add-remove-cart * * @param {Track} track */ GA.prototype.removedProductEnhanced = function(track){ this.loadEnhancedEcommerce(track); enhancedEcommerceProductAction(track, 'remove'); this.pushEnhancedEcommerce(track); }; /** * Viewed product details - Enhanced Ecommerce * * https://developers.google.com/analytics/devguides/collection/analyticsjs/enhanced-ecommerce#product-detail-view * * @param {Track} track */ GA.prototype.viewedProductEnhanced = function(track){ this.loadEnhancedEcommerce(track); enhancedEcommerceProductAction(track, 'detail'); this.pushEnhancedEcommerce(track); }; /** * Clicked product - Enhanced Ecommerce * * https://developers.google.com/analytics/devguides/collection/analyticsjs/enhanced-ecommerce#measuring-actions * * @param {Track} track */ GA.prototype.clickedProductEnhanced = function(track){ var props = track.properties(); this.loadEnhancedEcommerce(track); enhancedEcommerceProductAction(track, 'click', { list: props.list }); this.pushEnhancedEcommerce(track); }; /** * Viewed promotion - Enhanced Ecommerce * * https://developers.google.com/analytics/devguides/collection/analyticsjs/enhanced-ecommerce#measuring-promo-impressions * * @param {Track} track */ GA.prototype.viewedPromotionEnhanced = function(track){ var props = track.properties(); this.loadEnhancedEcommerce(track); window.ga('ec:addPromo', { id: track.id(), name: track.name(), creative: props.creative, position: props.position }); this.pushEnhancedEcommerce(track); }; /** * Clicked promotion - Enhanced Ecommerce * * https://developers.google.com/analytics/devguides/collection/analyticsjs/enhanced-ecommerce#measuring-promo-clicks * * @param {Track} track */ GA.prototype.clickedPromotionEnhanced = function(track){ var props = track.properties(); this.loadEnhancedEcommerce(track); window.ga('ec:addPromo', { id: track.id(), name: track.name(), creative: props.creative, position: props.position }); ga('ec:setAction', 'promo_click', {}); this.pushEnhancedEcommerce(track); }; /** * Enhanced ecommerce track product. * * Simple helper so that we don't repeat `ec:addProduct` everywhere. * * @param {Track} track */ function enhancedEcommerceTrackProduct(track){ var props = track.properties(); window.ga('ec:addProduct', { id: track.id() || track.sku(), name: track.name(), category: track.category(), quantity: track.quantity(), price: track.price(), brand: props.brand, variant: props.variant, currency: track.currency() }); } /** * Set `action` on `track` with `data`. * * @param {Track} track * @param {String} action * @param {Object} data */ function enhancedEcommerceProductAction(track, action, data){ enhancedEcommerceTrackProduct(track); window.ga('ec:setAction', action, data || {}); } /** * Extracts checkout options. * * @param {Object} props * @return {Null|String} */ function extractCheckoutOptions(props){ var options = [ props.paymentMethod, props.shippingMethod ]; // Remove all nulls, empty strings, zeroes, and join with commas. var valid = select(options, function(e){return e; }); return valid.length > 0 ? valid.join(', ') : null; } /** * Creates a track out of product properties. * * @param {Track} track * @param {Object} properties * @return {Track} */ function createProductTrack(track, properties) { properties.currency = properties.currency || track.currency(); return new Track({ properties: properties }); } }, {"analytics.js-integration":89,"global-queue":160,"object":171,"canonical":172,"use-https":91,"facade":133,"callback":95,"defaults":158,"load-script":129,"select":173,"obj-case":93,"each":4,"type":114,"url":174,"is":92}], 171: [function(require, module, exports) { /** * HOP ref. */ var has = Object.prototype.hasOwnProperty; /** * Return own keys in `obj`. * * @param {Object} obj * @return {Array} * @api public */ exports.keys = Object.keys || function(obj){ var keys = []; for (var key in obj) { if (has.call(obj, key)) { keys.push(key); } } return keys; }; /** * Return own values in `obj`. * * @param {Object} obj * @return {Array} * @api public */ exports.values = function(obj){ var vals = []; for (var key in obj) { if (has.call(obj, key)) { vals.push(obj[key]); } } return vals; }; /** * Merge `b` into `a`. * * @param {Object} a * @param {Object} b * @return {Object} a * @api public */ exports.merge = function(a, b){ for (var key in b) { if (has.call(b, key)) { a[key] = b[key]; } } return a; }; /** * Return length of `obj`. * * @param {Object} obj * @return {Number} * @api public */ exports.length = function(obj){ return exports.keys(obj).length; }; /** * Check if `obj` is empty. * * @param {Object} obj * @return {Boolean} * @api public */ exports.isEmpty = function(obj){ return 0 == exports.length(obj); }; }, {}], 172: [function(require, module, exports) { module.exports = function canonical () { var tags = document.getElementsByTagName('link'); for (var i = 0, tag; tag = tags[i]; i++) { if ('canonical' == tag.getAttribute('rel')) return tag.getAttribute('href'); } }; }, {}], 173: [function(require, module, exports) { /** * Module dependencies. */ var toFunction = require('to-function'); /** * Filter the given `arr` with callback `fn(val, i)`, * when a truthy value is return then `val` is included * in the array returned. * * @param {Array} arr * @param {Function} fn * @return {Array} * @api public */ module.exports = function(arr, fn){ var ret = []; fn = toFunction(fn); for (var i = 0; i < arr.length; ++i) { if (fn(arr[i], i)) { ret.push(arr[i]); } } return ret; }; }, {"to-function":175}], 175: [function(require, module, exports) { /** * Module Dependencies */ var expr; try { expr = require('props'); } catch(e) { expr = require('component-props'); } /** * Expose `toFunction()`. */ module.exports = toFunction; /** * Convert `obj` to a `Function`. * * @param {Mixed} obj * @return {Function} * @api private */ function toFunction(obj) { switch ({}.toString.call(obj)) { case '[object Object]': return objectToFunction(obj); case '[object Function]': return obj; case '[object String]': return stringToFunction(obj); case '[object RegExp]': return regexpToFunction(obj); default: return defaultToFunction(obj); } } /** * Default to strict equality. * * @param {Mixed} val * @return {Function} * @api private */ function defaultToFunction(val) { return function(obj){ return val === obj; }; } /** * Convert `re` to a function. * * @param {RegExp} re * @return {Function} * @api private */ function regexpToFunction(re) { return function(obj){ return re.test(obj); }; } /** * Convert property `str` to a function. * * @param {String} str * @return {Function} * @api private */ function stringToFunction(str) { // immediate such as "> 20" if (/^ *\W+/.test(str)) return new Function('_', 'return _ ' + str); // properties such as "name.first" or "age > 18" or "age > 18 && age < 36" return new Function('_', 'return ' + get(str)); } /** * Convert `object` to a function. * * @param {Object} object * @return {Function} * @api private */ function objectToFunction(obj) { var match = {}; for (var key in obj) { match[key] = typeof obj[key] === 'string' ? defaultToFunction(obj[key]) : toFunction(obj[key]); } return function(val){ if (typeof val !== 'object') return false; for (var key in match) { if (!(key in val)) return false; if (!match[key](val[key])) return false; } return true; }; } /** * Built the getter function. Supports getter style functions * * @param {String} str * @return {String} * @api private */ function get(str) { var props = expr(str); if (!props.length) return '_.' + str; var val, i, prop; for (i = 0; i < props.length; i++) { prop = props[i]; val = '_.' + prop; val = "('function' == typeof " + val + " ? " + val + "() : " + val + ")"; // mimic negative lookbehind to avoid problems with nested properties str = stripNested(prop, str, val); } return str; } /** * Mimic negative lookbehind to avoid problems with nested properties. * * See: http://blog.stevenlevithan.com/archives/mimic-lookbehind-javascript * * @param {String} prop * @param {String} str * @param {String} val * @return {String} * @api private */ function stripNested (prop, str, val) { return str.replace(new RegExp('(\\.)?' + prop, 'g'), function($0, $1) { return $1 ? $0 : val; }); } }, {"props":119,"component-props":119}], 174: [function(require, module, exports) { /** * Parse the given `url`. * * @param {String} str * @return {Object} * @api public */ exports.parse = function(url){ var a = document.createElement('a'); a.href = url; return { href: a.href, host: a.host, port: a.port, hash: a.hash, hostname: a.hostname, pathname: a.pathname, protocol: a.protocol, search: a.search, query: a.search.slice(1) } }; /** * Check if `url` is absolute. * * @param {String} url * @return {Boolean} * @api public */ exports.isAbsolute = function(url){ if (0 == url.indexOf('//')) return true; if (~url.indexOf('://')) return true; return false; }; /** * Check if `url` is relative. * * @param {String} url * @return {Boolean} * @api public */ exports.isRelative = function(url){ return ! exports.isAbsolute(url); }; /** * Check if `url` is cross domain. * * @param {String} url * @return {Boolean} * @api public */ exports.isCrossDomain = function(url){ url = exports.parse(url); return url.hostname != location.hostname || url.port != location.port || url.protocol != location.protocol; }; }, {}], 39: [function(require, module, exports) { /** * Module dependencies. */ var push = require('global-queue')('dataLayer', { wrap: false }); var integration = require('analytics.js-integration'); /** * Expose `GTM`. */ var GTM = module.exports = integration('Google Tag Manager') .assumesPageview() .global('dataLayer') .global('google_tag_manager') .option('containerId', '') .option('trackNamedPages', true) .option('trackCategorizedPages', true) .tag('<script src="//www.googletagmanager.com/gtm.js?id={{ containerId }}&l=dataLayer">'); /** * Initialize. * * https://developers.google.com/tag-manager * * @param {Object} page */ GTM.prototype.initialize = function(){ push({ 'gtm.start': +new Date, event: 'gtm.js' }); this.load(this.ready); }; /** * Loaded? * * @return {Boolean} */ GTM.prototype.loaded = function(){ return !! (window.dataLayer && [].push != window.dataLayer.push); }; /** * Page. * * @param {Page} page * @api public */ GTM.prototype.page = function(page){ var category = page.category(); var props = page.properties(); var name = page.fullName(); var opts = this.options; var track; // all if (opts.trackAllPages) { this.track(page.track()); } // categorized if (category && opts.trackCategorizedPages) { this.track(page.track(category)); } // named if (name && opts.trackNamedPages) { this.track(page.track(name)); } }; /** * Track. * * https://developers.google.com/tag-manager/devguide#events * * @param {Track} track * @api public */ GTM.prototype.track = function(track){ var props = track.properties(); props.event = track.event(); push(props); }; }, {"global-queue":160,"analytics.js-integration":89}], 40: [function(require, module, exports) { /** * Module dependencies. */ var integration = require('analytics.js-integration'); var Identify = require('facade').Identify; var Track = require('facade').Track; var callback = require('callback'); var load = require('load-script'); var onBody = require('on-body'); var each = require('each'); var is = require('is'); var pick = require('pick'); var omit = require('omit'); /** * Expose `GoSquared` integration. */ var GoSquared = module.exports = integration('GoSquared') .assumesPageview() .global('_gs') .option('apiSecret', '') .option('anonymizeIP', false) .option('cookieDomain', null) .option('useCookies', true) .option('trackHash', false) .option('trackLocal', false) .option('trackParams', true) .tag('<script src="//d1l6p2sc9645hc.cloudfront.net/tracker.js">'); /** * Initialize. * * https://www.gosquared.com/developer/tracker * Options: https://www.gosquared.com/developer/tracker/configuration * * @param {Object} page */ GoSquared.prototype.initialize = function(page){ var self = this; var options = this.options; var user = this.analytics.user(); push(options.apiSecret); each(options, function(name, value){ if ('apiSecret' == name) return; if (null == value) return; push('set', name, value); }); self.identify(new Identify({ traits: user.traits(), userId: user.id() })); self.load(this.ready); }; /** * Loaded? (checks if the tracker version is set) * * @return {Boolean} */ GoSquared.prototype.loaded = function(){ return !! (window._gs && window._gs.v); }; /** * Page. * * https://www.gosquared.com/docs/tracking/api/#pageviews * * @param {Page} page */ GoSquared.prototype.page = function(page){ var props = page.properties(); var name = page.fullName(); push('track', props.path, name || props.title) }; /** * Identify. * * https://www.gosquared.com/docs/tracking/identify * * @param {Identify} identify */ GoSquared.prototype.identify = function(identify){ var traits = identify.traits({ createdAt: 'created_at', firstName: 'first_name', lastName: 'last_name', title: 'company_position', industry: 'company_industry' }); // https://www.gosquared.com/docs/tracking/api/#properties var specialKeys = [ 'id', 'email', 'name', 'first_name', 'last_name', 'username', 'description', 'avatar', 'phone', 'created_at', 'company_name', 'company_size', 'company_position', 'company_industry' ]; // Segment allows traits to all be in a flat object // GoSquared requires all custom properties to be in a `custom` object, // select all special keys var props = pick.apply(null, [traits].concat(specialKeys)); props.custom = omit(specialKeys, traits); var id = identify.userId(); if (id) { push('identify', id, props); } else { push('properties', props); } var email = identify.email(); var username = identify.username(); var name = email || username || id; if (name) push('set', 'visitorName', name); }; /** * Track. * * https://www.gosquared.com/docs/tracking/events * * @param {Track} track */ GoSquared.prototype.track = function(track){ push('event', track.event(), track.properties()); }; /** * Checked out. * * https://www.gosquared.com/docs/tracking/ecommerce * * @param {Track} track * @api private */ GoSquared.prototype.completedOrder = function(track){ var products = track.products(); var items = []; each(products, function(product){ var track = new Track({ properties: product }); items.push({ category: track.category(), quantity: track.quantity(), price: track.price(), name: track.name(), }); }) push('transaction', track.orderId(), { revenue: track.total(), track: true }, items); }; /** * Push to `_gs.q`. * * @param {...} args * @api private */ function push(){ var _gs = window._gs = window._gs || function(){ (_gs.q = _gs.q || []).push(arguments); }; _gs.apply(null, arguments); } }, {"analytics.js-integration":89,"facade":133,"callback":95,"load-script":129,"on-body":130,"each":4,"is":92,"pick":176,"omit":177}], 176: [function(require, module, exports) { /** * Expose `pick`. */ module.exports = pick; /** * Pick keys from an `obj`. * * @param {Object} obj * @param {Strings} keys... * @return {Object} */ function pick(obj){ var keys = [].slice.call(arguments, 1); var ret = {}; for (var i = 0, key; key = keys[i]; i++) { if (key in obj) ret[key] = obj[key]; } return ret; } }, {}], 177: [function(require, module, exports) { /** * Expose `omit`. */ module.exports = omit; /** * Return a copy of the object without the specified keys. * * @param {Array} keys * @param {Object} object * @return {Object} */ function omit(keys, object){ var ret = {}; for (var item in object) { ret[item] = object[item]; } for (var i = 0; i < keys.length; i++) { delete ret[keys[i]]; } return ret; } }, {}], 41: [function(require, module, exports) { /** * Module dependencies. */ var integration = require('analytics.js-integration'); var alias = require('alias'); /** * Expose `Heap` integration. */ var Heap = module.exports = integration('Heap') .global('heap') .option('appId', '') .tag('<script src="//cdn.heapanalytics.com/js/heap-{{ appId }}.js">'); /** * Initialize. * * https://heapanalytics.com/docs/installation#web * * @param {Object} page */ Heap.prototype.initialize = function(page){ window.heap = window.heap || []; window.heap.load = function(appid, config){ window.heap.appid = appid; window.heap.config = config; var methodFactory = function(type){ return function(){ heap.push([type].concat(Array.prototype.slice.call(arguments, 0))); }; }; var methods = ['clearEventProperties', 'identify', 'setEventProperties', 'track', 'unsetEventProperty']; for (var i = 0; i < methods.length; i++) { heap[methods[i]] = methodFactory(methods[i]); } }; window.heap.load(this.options.appId); this.load(this.ready); }; /** * Loaded? * * @return {Boolean} */ Heap.prototype.loaded = function(){ return (window.heap && window.heap.appid); }; /** * Identify. * * https://heapanalytics.com/docs#identify * * @param {Identify} identify */ Heap.prototype.identify = function(identify){ var traits = identify.traits({ email: '_email' }); var id = identify.userId(); if (id) traits.handle = id; window.heap.identify(traits); }; /** * Track. * * https://heapanalytics.com/docs#track * * @param {Track} track */ Heap.prototype.track = function(track){ window.heap.track(track.event(), track.properties()); }; }, {"analytics.js-integration":89,"alias":163}], 42: [function(require, module, exports) { /** * Module dependencies. */ var integration = require('analytics.js-integration'); /** * Expose `hellobar.com` integration. */ var Hellobar = module.exports = integration('Hello Bar') .assumesPageview() .global('_hbq') .option('apiKey', '') .tag('<script src="//s3.amazonaws.com/scripts.hellobar.com/{{ apiKey }}.js">'); /** * Initialize. * * https://s3.amazonaws.com/scripts.hellobar.com/bb900665a3090a79ee1db98c3af21ea174bbc09f.js * * @param {Object} page */ Hellobar.prototype.initialize = function(page){ window._hbq = window._hbq || []; this.load(this.ready); }; /** * Loaded? * * @return {Boolean} */ Hellobar.prototype.loaded = function(){ return !! (window._hbq && window._hbq.push !== Array.prototype.push); }; }, {"analytics.js-integration":89}], 43: [function(require, module, exports) { /** * Module dependencies. */ var integration = require('analytics.js-integration'); var is = require('is'); /** * Expose `HitTail` integration. */ var HitTail = module.exports = integration('HitTail') .assumesPageview() .global('htk') .option('siteId', '') .tag('<script src="//{{ siteId }}.hittail.com/mlt.js">'); /** * Initialize. * * @param {Object} page */ HitTail.prototype.initialize = function(page){ this.load(this.ready); }; /** * Loaded? * * @return {Boolean} */ HitTail.prototype.loaded = function(){ return is.fn(window.htk); }; }, {"analytics.js-integration":89,"is":92}], 44: [function(require, module, exports) { /** * Module dependencies. */ var integration = require('analytics.js-integration'); var push = require('global-queue')('_hsq'); var convert = require('convert-dates'); /** * Expose `HubSpot` integration. */ var HubSpot = module.exports = integration('HubSpot') .assumesPageview() .global('_hsq') .option('portalId', null) .tag('<script id="hs-analytics" src="https://js.hs-analytics.net/analytics/{{ cache }}/{{ portalId }}.js">'); /** * Initialize. * * @param {Object} page */ HubSpot.prototype.initialize = function(page){ window._hsq = []; var cache = Math.ceil(new Date() / 300000) * 300000; this.load({ cache: cache }, this.ready); }; /** * Loaded? * * @return {Boolean} */ HubSpot.prototype.loaded = function(){ return !! (window._hsq && window._hsq.push !== Array.prototype.push); }; /** * Page. * * @param {String} category (optional) * @param {String} name (optional) * @param {Object} properties (optional) * @param {Object} options (optional) */ HubSpot.prototype.page = function(page){ push('trackPageView'); }; /** * Identify. * * @param {Identify} identify */ HubSpot.prototype.identify = function(identify){ if (!identify.email()) return; var traits = identify.traits(); traits = convertDates(traits); push('identify', traits); }; /** * Track. * * @param {Track} track */ HubSpot.prototype.track = function(track){ var props = track.properties(); props = convertDates(props); push('trackEvent', track.event(), props); }; /** * Convert all the dates in the HubSpot properties to millisecond times * * @param {Object} properties */ function convertDates(properties){ return convert(properties, function(date){ return date.getTime(); }); } }, {"analytics.js-integration":89,"global-queue":160,"convert-dates":164}], 45: [function(require, module, exports) { /** * Module dependencies. */ var integration = require('analytics.js-integration'); var alias = require('alias'); /** * Expose `Improvely` integration. */ var Improvely = module.exports = integration('Improvely') .assumesPageview() .global('_improvely') .global('improvely') .option('domain', '') .option('projectId', null) .tag('<script src="//{{ domain }}.iljmp.com/improvely.js">'); /** * Initialize. * * http://www.improvely.com/docs/landing-page-code * * @param {Object} page */ Improvely.prototype.initialize = function(page){ window._improvely = []; window.improvely = { init: function(e, t){ window._improvely.push(["init", e, t]); }, goal: function(e){ window._improvely.push(["goal", e]); }, label: function(e){ window._improvely.push(["label", e]); }}; var domain = this.options.domain; var id = this.options.projectId; window.improvely.init(domain, id); this.load(this.ready); }; /** * Loaded? * * @return {Boolean} */ Improvely.prototype.loaded = function(){ return !! (window.improvely && window.improvely.identify); }; /** * Identify. * * http://www.improvely.com/docs/labeling-visitors * * @param {Identify} identify */ Improvely.prototype.identify = function(identify){ var id = identify.userId(); if (id) window.improvely.label(id); }; /** * Track. * * http://www.improvely.com/docs/conversion-code * * @param {Track} track */ Improvely.prototype.track = function(track){ var props = track.properties({ revenue: 'amount' }); props.type = track.event(); window.improvely.goal(props); }; }, {"analytics.js-integration":89,"alias":163}], 46: [function(require, module, exports) { /** * Module dependencies. */ var integration = require('analytics.js-integration'); var push = require('global-queue')('_iva'); var Track = require('facade').Track; var each = require('each'); var is = require('is'); /** * HOP. */ var has = Object.prototype.hasOwnProperty; /** * Expose `InsideVault` integration. */ var InsideVault = module.exports = integration('InsideVault') .global('_iva') .option('clientId', '') .option('domain', '') .tag('<script src="//analytics.staticiv.com/iva.js">') .mapping('events'); /** * Initialize. * * @param page */ InsideVault.prototype.initialize = function(page){ var domain = this.options.domain; window._iva = window._iva || []; push('setClientId', this.options.clientId); var userId = this.analytics.user().anonymousId(); if (userId) push('setUserId', userId); if (domain) push('setDomain', domain); this.load(this.ready); }; /** * Loaded? * * @return {Boolean} */ InsideVault.prototype.loaded = function(){ return !! (window._iva && window._iva.push !== Array.prototype.push); }; /** * Identify. * * @param {Identify} identify */ InsideVault.prototype.identify = function(identify){ push('setUserId', identify.anonymousId()); }; /** * Page. * * @param {Page} page */ InsideVault.prototype.page = function(page){ // they want every landing page to send a "click" event. push('trackEvent', 'click'); }; /** * Track. * * Tracks everything except 'sale' events. * * @param {Track} track */ InsideVault.prototype.track = function(track){ var user = this.analytics.user(); var events = this.events(track.event()); var value = track.revenue() || track.value() || 0; var eventId = track.orderId() || user.anonymousId() || ''; each(events, function(event){ // 'sale' is a special event that will be routed to a table that is deprecated on InsideVault's end. // They don't want a generic 'sale' event to go to their deprecated table. if (event != 'sale') { push('trackEvent', event, value, eventId); } }); }; }, {"analytics.js-integration":89,"global-queue":160,"facade":133,"each":4,"is":92}], 47: [function(require, module, exports) { /** * Module dependencies. */ var integration = require('analytics.js-integration'); var push = require('global-queue')('__insp'); var alias = require('alias'); var clone = require('clone'); /** * Expose `Inspectlet` integration. */ var Inspectlet = module.exports = integration('Inspectlet') .assumesPageview() .global('__insp') .global('__insp_') .option('wid', '') .tag('<script src="//cdn.inspectlet.com/inspectlet.js">'); /** * Initialize. * * https://www.inspectlet.com/dashboard/embedcode/1492461759/initial * * @param {Object} page */ Inspectlet.prototype.initialize = function(page){ push('wid', this.options.wid); this.load(this.ready); }; /** * Loaded? * * @return {Boolean} */ Inspectlet.prototype.loaded = function(){ return !! (window.__insp_ && window.__insp); }; /** * Identify. * * http://www.inspectlet.com/docs#tagging * * @param {Identify} identify */ Inspectlet.prototype.identify = function(identify){ var traits = identify.traits({ id: 'userid' }); var email = identify.email(); if (email) push('identify', email); push('tagSession', traits); }; /** * Track. * * http://www.inspectlet.com/docs/tags * * @param {Track} track */ Inspectlet.prototype.track = function(track){ push('tagSession', track.event()); }; /** * Page. * * http://www.inspectlet.com/docs/tags * * @param {Track} track */ Inspectlet.prototype.page = function(){ push('virtualPage'); }; }, {"analytics.js-integration":89,"global-queue":160,"alias":163,"clone":96}], 48: [function(require, module, exports) { /** * Module dependencies. */ var integration = require('analytics.js-integration'); var convertDates = require('convert-dates'); var defaults = require('defaults'); var del = require('obj-case').del; var isEmail = require('is-email'); var load = require('load-script'); var empty = require('is-empty'); var alias = require('alias'); var each = require('each'); var is = require('is'); /** * Expose `Intercom` integration. */ var Intercom = module.exports = integration('Intercom') .global('Intercom') .option('activator', '#IntercomDefaultWidget') .option('appId', '') .tag('<script src="https://widget.intercom.io/widget/{{ appId }}">'); /** * Initialize. * * http://docs.intercom.io/ * http://docs.intercom.io/#IntercomJS * * @param {Object} page */ Intercom.prototype.initialize = function(page){ initialize(); this.load(this.ready); }; /** * Loaded? * * @return {Boolean} */ Intercom.prototype.loaded = function(){ return is.fn(window.Intercom); }; /** * Page. * * @param {Page} page */ Intercom.prototype.page = function(){ this.bootOrUpdate(); }; /** * Identify. * * http://docs.intercom.io/#IntercomJS * * @param {Identify} identify */ Intercom.prototype.identify = function(identify){ var traits = identify.traits({ userId: 'user_id' }); var opts = identify.options(this.name); var companyCreated = identify.companyCreated(); var created = identify.created(); var email = identify.email(); var name = identify.name(); var id = identify.userId(); var group = this.analytics.group(); if (!id && !traits.email) { return; } // intercom requires `company` to be an object. default it with group traits // so that we guarantee an `id` is there, since they require it if (traits.company !== null && !is.object(traits.company)) { delete traits.company; } if (traits.company) { defaults(traits.company, group.traits()); } // name if (name) traits.name = name; // handle dates if (created) { del(traits, 'created'); del(traits, 'createdAt'); traits.created_at = created; } if (companyCreated) { del(traits.company, 'created'); del(traits.company, 'createdAt'); traits.company.created_at = companyCreated; } // convert dates traits = convertDates(traits, formatDate); // handle options if (opts.increments) traits.increments = opts.increments; if (opts.userHash) traits.user_hash = opts.userHash; if (opts.user_hash) traits.user_hash = opts.user_hash; this.bootOrUpdate(traits); }; /** * Group. * * @param {Group} group */ Intercom.prototype.group = function(group){ var props = group.properties(); props = alias(props, { createdAt: 'created' }); props = alias(props, { created: 'created_at' }); var id = group.groupId(); if (id) props.id = id; api('update', { company: props }); }; /** * Track. * * @param {Track} track */ Intercom.prototype.track = function(track){ api('trackEvent', track.event(), track.properties()); }; /** * Boots or updates, as appropriate. * * @param {Object} options */ Intercom.prototype.bootOrUpdate = function(options){ options = options || {}; var method = this.booted === true ? 'update' : 'boot'; var activator = this.options.activator; options.app_id = this.options.appId; // Intercom, will force the widget to appear // if the selector is #IntercomDefaultWidget // so no need to check inbox, just need to check // that the selector isn't #IntercomDefaultWidget. if (activator !== '#IntercomDefaultWidget') { options.widget = { activator: activator }; } api(method, options); this.booted = true; }; /** * Format a date to Intercom's liking. * * @param {Date} date * @return {Number} */ function formatDate(date){ return Math.floor(date / 1000); } /** * Initialize the Intercom call queue. */ function initialize(){ window.Intercom = function(){ window.Intercom.q.push(arguments); }; window.Intercom.q = []; } /** * Push a call onto the queue. */ function api(){ window.Intercom.apply(window.Intercom, arguments); } }, {"analytics.js-integration":89,"convert-dates":164,"defaults":158,"obj-case":93,"is-email":155,"load-script":129,"is-empty":123,"alias":163,"each":4,"is":92}], 49: [function(require, module, exports) { /** * Module dependencies. */ var integration = require('analytics.js-integration'); var clone = require('clone'); /** * Expose `Keen IO` integration. */ var Keen = module.exports = integration('Keen IO') .global('Keen') .option('projectId', '') .option('readKey', '') .option('writeKey', '') .option('ipAddon', false) .option('uaAddon', false) .option('urlAddon', false) .option('referrerAddon', false) .option('trackNamedPages', true) .option('trackAllPages', false) .option('trackCategorizedPages', true) .tag('<script src="//d26b395fwzu5fz.cloudfront.net/3.0.7/{{ lib }}.min.js">'); /** * Initialize. * * https://keen.io/docs/ */ Keen.prototype.initialize = function(){ var options = this.options; !(function(a,b){ if (void 0===b[a]){ b["_"+a]={}, b[a]=function(c){ b["_"+a].clients=b["_"+a].clients||{}, b["_"+a].clients[c.projectId]=this, this._config=c }, b[a].ready=function(c){ b["_"+a].ready=b["_"+a].ready||[],b["_"+a].ready.push(c) }; for (var c=["addEvent","setGlobalProperties","trackExternalLink","on"],d=0;d<c.length;d++){ var e=c[d], f=function(a){ return function(){ return this["_"+a]=this["_"+a]||[],this["_"+a].push(arguments),this } }; b[a].prototype[e]=f(e) } } })("Keen",window); this.client = new window.Keen({ projectId: options.projectId, writeKey: options.writeKey, readKey: options.readKey }); // if you have a read-key, then load the full keen library var lib = this.options.readKey ? 'keen' : 'keen-tracker'; this.load({ lib: lib }, this.ready); }; /** * Loaded? * * @return {Boolean} */ Keen.prototype.loaded = function(){ return !!(window.Keen && window.Keen.prototype.configure); }; /** * Page. * * @param {Page} page */ Keen.prototype.page = function(page){ var category = page.category(); var props = page.properties(); var name = page.fullName(); var opts = this.options; // all pages if (opts.trackAllPages) { this.track(page.track()); } // named pages if (name && opts.trackNamedPages) { this.track(page.track(name)); } // categorized pages if (category && opts.trackCategorizedPages) { this.track(page.track(category)); } }; /** * Identify. * * TODO: migrate from old `userId` to simpler `id` * https://keen.io/docs/data-collection/data-enrichment/#add-ons * * Set up the Keen addons object. These must be specifically * enabled by the settings in order to include the plugins, or else * Keen will reject the request. * * @param {Identify} identify */ Keen.prototype.identify = function(identify){ var traits = identify.traits(); var id = identify.userId(); var user = {}; if (id) user.userId = id; if (traits) user.traits = traits; var props = { user: user }; this.addons(props, identify); this.client.setGlobalProperties(function(){ return clone(props); }); }; /** * Track. * * @param {Track} track */ Keen.prototype.track = function(track){ var props = track.properties(); this.addons(props, track); this.client.addEvent(track.event(), props); }; /** * Attach addons to `obj` with `msg`. * * @param {Object} obj * @param {Facade} msg */ Keen.prototype.addons = function(obj, msg){ var options = this.options; var addons = []; if (options.ipAddon) { addons.push({ name: 'keen:ip_to_geo', input: { ip: 'ip_address' }, output: 'ip_geo_info' }); obj.ip_address = '${keen.ip}'; } if (options.uaAddon) { addons.push({ name: 'keen:ua_parser', input: { ua_string: 'user_agent' }, output: 'parsed_user_agent' }); obj.user_agent = '${keen.user_agent}'; } if (options.urlAddon) { addons.push({ name: 'keen:url_parser', input: { url: 'page_url' }, output: 'parsed_page_url' }); obj.page_url = document.location.href; } if (options.referrerAddon) { addons.push({ name: 'keen:referrer_parser', input: { referrer_url: 'referrer_url', page_url: 'page_url' }, output: 'referrer_info' }); obj.referrer_url = document.referrer; obj.page_url = document.location.href; } obj.keen = { timestamp: msg.timestamp(), addons: addons }; }; }, {"analytics.js-integration":89,"clone":96}], 50: [function(require, module, exports) { /** * Module dependencies. */ var integration = require('analytics.js-integration'); var indexof = require('indexof'); var is = require('is'); /** * Expose `Kenshoo` integration. */ var Kenshoo = module.exports = integration('Kenshoo') .global('k_trackevent') .option('cid', '') .option('subdomain', '') .option('events', []) .tag('<script src="//{{ subdomain }}.xg4ken.com/media/getpx.php?cid={{ cid }}">'); /** * Initialize. * * See https://gist.github.com/justinboyle/7875832 * * @param {Object} page */ Kenshoo.prototype.initialize = function(page){ this.load(this.ready); }; /** * Loaded? (checks if the tracking function is set) * * @return {Boolean} */ Kenshoo.prototype.loaded = function(){ return is.fn(window.k_trackevent); }; /** * Track. * * Only tracks events if they are listed in the events array option. * We've asked for docs a few times but no go :/ * * https://github.com/jorgegorka/the_tracker/blob/master/lib/the_tracker/trackers/kenshoo.rb * * @param {Track} event */ Kenshoo.prototype.track = function(track){ var events = this.options.events; var traits = track.traits(); var event = track.event(); var revenue = track.revenue() || 0; if (!~indexof(events, event)) return; var params = [ 'id=' + this.options.cid, 'type=conv', 'val=' + revenue, 'orderId=' + track.orderId(), 'promoCode=' + track.coupon(), 'valueCurrency=' + track.currency(), // Live tracking fields. Ignored for now (until we get documentation). 'GCID=', 'kw=', 'product=' ]; window.k_trackevent(params, this.options.subdomain); }; }, {"analytics.js-integration":89,"indexof":117,"is":92}], 51: [function(require, module, exports) { /** * Module dependencies. */ var integration = require('analytics.js-integration'); var push = require('global-queue')('_kmq'); var Track = require('facade').Track; var alias = require('alias'); var each = require('each'); var is = require('is'); /** * Expose `KISSmetrics` integration. */ var KISSmetrics = module.exports = integration('KISSmetrics') .assumesPageview() .global('_kmq') .global('KM') .global('_kmil') .option('apiKey', '') .option('trackNamedPages', true) .option('trackCategorizedPages', true) .option('prefixProperties', true) .tag('library', '<script src="//scripts.kissmetrics.com/{{ apiKey }}.2.js">'); /** * Check if browser is mobile, for kissmetrics. * * http://support.kissmetrics.com/how-tos/browser-detection.html#mobile-vs-non-mobile */ exports.isMobile = navigator.userAgent.match(/Android/i) || navigator.userAgent.match(/BlackBerry/i) || navigator.userAgent.match(/iPhone|iPod/i) || navigator.userAgent.match(/iPad/i) || navigator.userAgent.match(/Opera Mini/i) || navigator.userAgent.match(/IEMobile/i); /** * Initialize. * * http://support.kissmetrics.com/apis/javascript * * @param {Object} page */ KISSmetrics.prototype.initialize = function(page){ var self = this; window._kmq = []; if (exports.isMobile) push('set', { 'Mobile Session': 'Yes' }); this.load('library', function(){ self.trackPage(page); self.ready(); }); }; /** * Loaded? * * @return {Boolean} */ KISSmetrics.prototype.loaded = function(){ return is.object(window.KM); }; /** * Page. * * @param {Page} page */ KISSmetrics.prototype.page = function(page){ if (!window.KM_SKIP_PAGE_VIEW) window.KM.pageView(); this.trackPage(page); }; /** * Track page. * * @param {Page} page */ KISSmetrics.prototype.trackPage = function(page){ var category = page.category(); var name = page.fullName(); var opts = this.options; // named pages if (name && opts.trackNamedPages) { this.track(page.track(name)); } // categorized pages if (category && opts.trackCategorizedPages) { this.track(page.track(category)); } }; /** * Identify. * * @param {Identify} identify */ KISSmetrics.prototype.identify = function(identify){ var traits = identify.traits(); var id = identify.userId(); if (id) push('identify', id); if (traits) push('set', traits); }; /** * Track. * * @param {Track} track */ KISSmetrics.prototype.track = function(track){ var mapping = { revenue: 'Billing Amount' }; var event = track.event(); var properties = track.properties(mapping); if (this.options.prefixProperties) properties = prefix(event, properties); push('record', event, properties); }; /** * Alias. * * @param {Alias} to */ KISSmetrics.prototype.alias = function(alias){ push('alias', alias.to(), alias.from()); }; /** * Completed order. * * @param {Track} track * @api private */ KISSmetrics.prototype.completedOrder = function(track){ var products = track.products(); var event = track.event(); // transaction push('record', event, prefix(event, track.properties())); // items window._kmq.push(function(){ var km = window.KM; each(products, function(product, i){ var item = prefix(event, product); item._t = km.ts() + i; item._d = 1; km.set(item); }); }); }; /** * Prefix properties with the event name. * * @param {String} event * @param {Object} properties * @return {Object} prefixed * @api private */ function prefix(event, properties){ var prefixed = {}; each(properties, function(key, val){ if (key === 'Billing Amount') { prefixed[key] = val; } else { prefixed[event + ' - ' + key] = val; } }); return prefixed; } }, {"analytics.js-integration":89,"global-queue":160,"facade":133,"alias":163,"each":4,"is":92}], 52: [function(require, module, exports) { /** * Module dependencies. */ var integration = require('analytics.js-integration'); var push = require('global-queue')('_learnq'); var tick = require('next-tick'); var alias = require('alias'); /** * Trait aliases. */ var aliases = { id: '$id', email: '$email', firstName: '$first_name', lastName: '$last_name', phone: '$phone_number', title: '$title' }; /** * Expose `Klaviyo` integration. */ var Klaviyo = module.exports = integration('Klaviyo') .assumesPageview() .global('_learnq') .option('apiKey', '') .tag('<script src="//a.klaviyo.com/media/js/learnmarklet.js">'); /** * Initialize. * * https://www.klaviyo.com/docs/getting-started * * @param {Object} page */ Klaviyo.prototype.initialize = function(page){ var self = this; push('account', this.options.apiKey); this.load(function(){ tick(self.ready); }); }; /** * Loaded? * * @return {Boolean} */ Klaviyo.prototype.loaded = function(){ return !! (window._learnq && window._learnq.push !== Array.prototype.push); }; /** * Identify. * * @param {Identify} identify */ Klaviyo.prototype.identify = function(identify){ var traits = identify.traits(aliases); if (!traits.$id && !traits.$email) return; push('identify', traits); }; /** * Group. * * @param {Group} group */ Klaviyo.prototype.group = function(group){ var props = group.properties(); if (!props.name) return; push('identify', { $organization: props.name }); }; /** * Track. * * @param {Track} track */ Klaviyo.prototype.track = function(track){ push('track', track.event(), track.properties({ revenue: '$value' })); }; }, {"analytics.js-integration":89,"global-queue":160,"next-tick":104,"alias":163}], 53: [function(require, module, exports) { /** * Module dependencies. */ var integration = require('analytics.js-integration'); var clone = require('clone'); var each = require('each'); var Identify = require('facade').Identify; var when = require('when'); var tick = require('next-tick'); /** * Expose `LiveChat` integration. */ var LiveChat = module.exports = integration('LiveChat') .assumesPageview() .global('__lc') .global('__lc_inited') .global('LC_API') .global('LC_Invite') .option('group', 0) .option('license', '') .option('listen', false) .tag('<script src="//cdn.livechatinc.com/tracking.js">'); /** * The context for this integration. */ var integration = { name: 'livechat', version: '1.0.0' }; /** * Initialize. * * http://www.livechatinc.com/api/javascript-api * * @param {Object} page */ LiveChat.prototype.initialize = function(page){ var self = this; var user = this.analytics.user(); var identify = new Identify({ userId: user.id(), traits: user.traits() }); window.__lc = clone(this.options); window.__lc.visitor = { name: identify.name(), email: identify.email() }; // listen is not an option we need from clone delete window.__lc.listen; this.load(function(){ when(function(){ return self.loaded(); }, function(){ if (self.options.listen) self.attachListeners(); tick(self.ready); }); }); }; /** * Loaded? * * @return {Boolean} */ LiveChat.prototype.loaded = function(){ return !!(window.LC_API && window.LC_Invite); }; /** * Listen for chat events. */ LiveChat.prototype.attachListeners = function(){ var self = this; window.LC_API = window.LC_API || {}; window.LC_API.on_chat_started = function(data){ self.analytics.track( 'Live Chat Conversation Started', { agentName: data.agent_name }, { context: { integration: integration } }); }; window.LC_API.on_message = function(data){ if (data.user_type === 'visitor') { self.analytics.track( 'Live Chat Message Sent', {}, { context: { integration: integration } }); } else { self.analytics.track( 'Live Chat Message Received', { agentName: data.agent_name, agentUsername: data.agent_login }, { context: { integration: integration } }); } }; window.LC_API.on_chat_ended = function(){ self.analytics.track('Live Chat Conversation Ended'); }; }; /** * Identify. * * @param {Identify} identify */ LiveChat.prototype.identify = function(identify){ var traits = identify.traits({ userId: 'User ID' }); window.LC_API.set_custom_variables(convert(traits)); }; /** * Convert a traits object into the format LiveChat requires. * * @param {Object} traits * @return {Array} */ function convert(traits){ var arr = []; each(traits, function(key, value){ arr.push({ name: key, value: value }); }); return arr; } }, {"analytics.js-integration":89,"clone":96,"each":4,"facade":133,"when":132,"next-tick":104}], 54: [function(require, module, exports) { /** * Module dependencies. */ var integration = require('analytics.js-integration'); var Identify = require('facade').Identify; var useHttps = require('use-https'); /** * Expose `LuckyOrange` integration. */ var LuckyOrange = module.exports = integration('Lucky Orange') .assumesPageview() .global('_loq') .global('__wtw_watcher_added') .global('__wtw_lucky_site_id') .global('__wtw_lucky_is_segment_io') .global('__wtw_custom_user_data') .option('siteId', null) .tag('http', '<script src="http://www.luckyorange.com/w.js?{{ cache }}">') .tag('https', '<script src="https://ssl.luckyorange.com/w.js?{{ cache }}">'); /** * Initialize. * * @param {Object} page */ LuckyOrange.prototype.initialize = function(page){ var user = this.analytics.user(); window._loq || (window._loq = []); window.__wtw_lucky_site_id = this.options.siteId; this.identify(new Identify({ traits: user.traits(), userId: user.id() })); var cache = Math.floor(new Date().getTime() / 60000); var name = useHttps() ? 'https' : 'http'; this.load(name, { cache: cache }, this.ready); }; /** * Loaded? * * @return {Boolean} */ LuckyOrange.prototype.loaded = function(){ return !! window.__wtw_watcher_added; }; /** * Identify. * * @param {Identify} identify */ LuckyOrange.prototype.identify = function(identify){ var traits = identify.traits(); var email = identify.email(); var name = identify.name(); if (name) traits.name = name; if (email) traits.email = email; window.__wtw_custom_user_data = traits; }; }, {"analytics.js-integration":89,"facade":133,"use-https":91}], 55: [function(require, module, exports) { /** * Module dependencies. */ var integration = require('analytics.js-integration'); var alias = require('alias'); /** * Expose `Lytics` integration. */ var Lytics = module.exports = integration('Lytics') .global('jstag') .option('cid', '') .option('cookie', 'seerid') .option('delay', 2000) .option('sessionTimeout', 1800) .option('url', '//c.lytics.io') .tag('<script src="//c.lytics.io/static/io.min.js">'); /** * Options aliases. */ var aliases = { sessionTimeout: 'sessecs' }; /** * Initialize. * * http://admin.lytics.io/doc#jstag * * @param {Object} page */ Lytics.prototype.initialize = function(page){ var options = alias(this.options, aliases); window.jstag = (function(){var t = { _q: [], _c: options, ts: (new Date()).getTime() }; t.send = function(){this._q.push(['ready', 'send', Array.prototype.slice.call(arguments)]); return this; }; return t; })(); this.load(this.ready); }; /** * Loaded? * * @return {Boolean} */ Lytics.prototype.loaded = function(){ return !! (window.jstag && window.jstag.bind); }; /** * Page. * * @param {Page} page */ Lytics.prototype.page = function(page){ window.jstag.send(page.properties()); }; /** * Idenfity. * * @param {Identify} identify */ Lytics.prototype.identify = function(identify){ var traits = identify.traits({ userId: '_uid' }); window.jstag.send(traits); }; /** * Track. * * @param {String} event * @param {Object} properties (optional) * @param {Object} options (optional) */ Lytics.prototype.track = function(track){ var props = track.properties(); props._e = track.event(); window.jstag.send(props); }; }, {"analytics.js-integration":89,"alias":163}], 56: [function(require, module, exports) { /** * Module dependencies. */ var alias = require('alias'); var clone = require('clone'); var dates = require('convert-dates'); var integration = require('analytics.js-integration'); var is = require('is'); var iso = require('to-iso-string'); var indexof = require('indexof'); var del = require('obj-case').del; var some = require('some'); /** * Expose `Mixpanel` integration. */ var Mixpanel = module.exports = integration('Mixpanel') .global('mixpanel') .option('increments', []) .option('cookieName', '') .option('crossSubdomainCookie', false) .option('secureCookie', false) .option('nameTag', true) .option('pageview', false) .option('people', false) .option('token', '') .option('trackAllPages', false) .option('trackNamedPages', true) .option('trackCategorizedPages', true) .tag('<script src="//cdn.mxpnl.com/libs/mixpanel-2-latest.min.js">'); /** * Options aliases. */ var optionsAliases = { cookieName: 'cookie_name', crossSubdomainCookie: 'cross_subdomain_cookie', secureCookie: 'secure_cookie' }; /** * Initialize. * * https://mixpanel.com/help/reference/javascript#installing * https://mixpanel.com/help/reference/javascript-full-api-reference#mixpanel.init */ Mixpanel.prototype.initialize = function(){ (function(c, a){window.mixpanel = a; var b, d, h, e; a._i = []; a.init = function(b, c, f){function d(a, b){var c = b.split('.'); 2 == c.length && (a = a[c[0]], b = c[1]); a[b] = function(){a.push([b].concat(Array.prototype.slice.call(arguments, 0))); }; } var g = a; 'undefined' !== typeof f ? g = a[f] = [] : f = 'mixpanel'; g.people = g.people || []; h = ['disable', 'track', 'track_pageview', 'track_links', 'track_forms', 'register', 'register_once', 'unregister', 'identify', 'alias', 'name_tag', 'set_config', 'people.set', 'people.increment', 'people.track_charge', 'people.append']; for (e = 0; e < h.length; e++) d(g, h[e]); a._i.push([b, c, f]); }; a.__SV = 1.2; })(document, window.mixpanel || []); this.options.increments = lowercase(this.options.increments); var options = alias(this.options, optionsAliases); window.mixpanel.init(options.token, options); this.load(this.ready); }; /** * Loaded? * * @return {Boolean} */ Mixpanel.prototype.loaded = function(){ return !! (window.mixpanel && window.mixpanel.config); }; /** * Page. * * https://mixpanel.com/help/reference/javascript-full-api-reference#mixpanel.track_pageview * * @param {String} category (optional) * @param {String} name (optional) * @param {Object} properties (optional) * @param {Object} options (optional) */ Mixpanel.prototype.page = function(page){ var category = page.category(); var name = page.fullName(); var opts = this.options; // all pages if (opts.trackAllPages) { this.track(page.track()); } // categorized pages if (category && opts.trackCategorizedPages) { this.track(page.track(category)); } // named pages if (name && opts.trackNamedPages) { this.track(page.track(name)); } }; /** * Trait aliases. */ var traitAliases = { created: '$created', email: '$email', firstName: '$first_name', lastName: '$last_name', lastSeen: '$last_seen', name: '$name', username: '$username', phone: '$phone' }; /** * Identify. * * https://mixpanel.com/help/reference/javascript#super-properties * https://mixpanel.com/help/reference/javascript#user-identity * https://mixpanel.com/help/reference/javascript#storing-user-profiles * * @param {Identify} identify */ Mixpanel.prototype.identify = function(identify){ var username = identify.username(); var email = identify.email(); var id = identify.userId(); // id if (id) window.mixpanel.identify(id); // name tag var nametag = email || username || id; if (nametag) window.mixpanel.name_tag(nametag); // traits var traits = identify.traits(traitAliases); if (traits.$created) del(traits, 'createdAt'); window.mixpanel.register(dates(traits, iso)); if (this.options.people) window.mixpanel.people.set(traits); }; /** * Track. * * https://mixpanel.com/help/reference/javascript#sending-events * https://mixpanel.com/help/reference/javascript#tracking-revenue * * @param {Track} track */ Mixpanel.prototype.track = function(track){ var increments = this.options.increments; var increment = track.event().toLowerCase(); var people = this.options.people; var props = track.properties(); var revenue = track.revenue(); // delete mixpanel's reserved properties, so they don't conflict delete props.distinct_id; delete props.ip; delete props.mp_name_tag; delete props.mp_note; delete props.token; // convert arrays of objects to length, since mixpanel doesn't support object arrays for (var key in props) { var val = props[key]; if (is.array(val) && some(val, is.object)) props[key] = val.length; } // increment properties in mixpanel people if (people && ~indexof(increments, increment)) { window.mixpanel.people.increment(track.event()); window.mixpanel.people.set('Last ' + track.event(), new Date); } // track the event props = dates(props, iso); window.mixpanel.track(track.event(), props); // track revenue specifically if (revenue && people) { window.mixpanel.people.track_charge(revenue); } }; /** * Alias. * * https://mixpanel.com/help/reference/javascript#user-identity * https://mixpanel.com/help/reference/javascript-full-api-reference#mixpanel.alias * * @param {Alias} alias */ Mixpanel.prototype.alias = function(alias){ var mp = window.mixpanel; var to = alias.to(); if (mp.get_distinct_id && mp.get_distinct_id() === to) return; // HACK: internal mixpanel API to ensure we don't overwrite if (mp.get_property && mp.get_property('$people_distinct_id') === to) return; // although undocumented, mixpanel takes an optional original id mp.alias(to, alias.from()); }; /** * Lowercase the given `arr`. * * @param {Array} arr * @return {Array} * @api private */ function lowercase(arr){ var ret = new Array(arr.length); for (var i = 0; i < arr.length; ++i) { ret[i] = String(arr[i]).toLowerCase(); } return ret; } }, {"alias":163,"clone":96,"convert-dates":164,"analytics.js-integration":89,"is":92,"to-iso-string":162,"indexof":117,"obj-case":93,"some":178}], 178: [function(require, module, exports) { /** * some */ var some = [].some; /** * test whether some elements in * the array pass the test implemented * by `fn`. * * example: * * some([1, 'foo', 'bar'], function (el, i) { * return 'string' == typeof el; * }); * // > true * * @param {Array} arr * @param {Function} fn * @return {bool} */ module.exports = function (arr, fn) { if (some) return some.call(arr, fn); for (var i = 0, l = arr.length; i < l; ++i) { if (fn(arr[i], i)) return true; } return false; }; }, {}], 57: [function(require, module, exports) { /** * Module dependencies. */ var integration = require('analytics.js-integration'); var bind = require('bind'); var when = require('when'); var is = require('is'); /** * Expose `Mojn` */ var Mojn = module.exports = integration('Mojn') .option('customerCode', '') .global('_mojnTrack') .tag('<script src="https://track.idtargeting.com/{{ customerCode }}/track.js">'); /** * Initialize. * * @param {Object} page */ Mojn.prototype.initialize = function(){ window._mojnTrack = window._mojnTrack || []; window._mojnTrack.push({ cid: this.options.customerCode }); var loaded = bind(this, this.loaded); var ready = this.ready; this.load(function(){ when(loaded, ready); }); }; /** * Loaded? * * @return {Boolean} */ Mojn.prototype.loaded = function(){ return is.object(window._mojnTrack); }; /** * Identify. * * @param {Identify} identify */ Mojn.prototype.identify = function(identify){ var email = identify.email(); if (!email) return; var img = new Image(); img.src = '//matcher.idtargeting.com/identify.gif?cid=' + this.options.customerCode + '&_mjnctid='+email; img.width = 1; img.height = 1; return img; }; /** * Track. * * @param {Track} event */ Mojn.prototype.track = function(track){ var properties = track.properties(); var revenue = properties.revenue; var currency = properties.currency || ''; var conv = currency + revenue; if (!revenue) return; window._mojnTrack.push({ conv: conv }); return conv; }; }, {"analytics.js-integration":89,"bind":102,"when":132,"is":92}], 58: [function(require, module, exports) { /** * Module dependencies. */ var push = require('global-queue')('_mfq'); var integration = require('analytics.js-integration'); var each = require('each'); /** * Expose `Mouseflow`. */ var Mouseflow = module.exports = integration('Mouseflow') .assumesPageview() .global('mouseflow') .global('_mfq') .option('apiKey', '') .option('mouseflowHtmlDelay', 0) .tag('<script src="//cdn.mouseflow.com/projects/{{ apiKey }}.js">'); /** * Initalize. * * @param {Object} page */ Mouseflow.prototype.initialize = function(page){ window.mouseflowHtmlDelay = this.options.mouseflowHtmlDelay; this.load(this.ready); }; /** * Loaded? * * @return {Boolean} */ Mouseflow.prototype.loaded = function(){ return !! window.mouseflow; }; /** * Page. * * http://mouseflow.zendesk.com/entries/22528817-Single-page-websites * * @param {Page} page */ Mouseflow.prototype.page = function(page){ if (!window.mouseflow) return; if ('function' != typeof mouseflow.newPageView) return; mouseflow.newPageView(); }; /** * Identify. * * http://mouseflow.zendesk.com/entries/24643603-Custom-Variables-Tagging * * @param {Identify} identify */ Mouseflow.prototype.identify = function(identify){ set(identify.traits()); }; /** * Track. * * http://mouseflow.zendesk.com/entries/24643603-Custom-Variables-Tagging * * @param {Track} track */ Mouseflow.prototype.track = function(track){ var props = track.properties(); props.event = track.event(); set(props); }; /** * Push each key and value in the given `obj` onto the queue. * * @param {Object} obj */ function set(obj){ each(obj, function(key, value){ push('setVariable', key, value); }); } }, {"global-queue":160,"analytics.js-integration":89,"each":4}], 59: [function(require, module, exports) { /** * Module dependencies. */ var integration = require('analytics.js-integration'); var useHttps = require('use-https'); var each = require('each'); var is = require('is'); /** * Expose `MouseStats` integration. */ var MouseStats = module.exports = integration('MouseStats') .assumesPageview() .global('msaa') .global('MouseStatsVisitorPlaybacks') .option('accountNumber', '') .tag('http', '<script src="http://www2.mousestats.com/js/{{ path }}.js?{{ cache }}">') .tag('https', '<script src="https://ssl.mousestats.com/js/{{ path }}.js?{{ cache }}">'); /** * Initialize. * * http://www.mousestats.com/docs/pages/allpages * * @param {Object} page */ MouseStats.prototype.initialize = function(page){ var number = this.options.accountNumber; var path = number.slice(0,1) + '/' + number.slice(1,2) + '/' + number; var cache = Math.floor(new Date().getTime() / 60000); var name = useHttps() ? 'https' : 'http'; this.load(name, { path: path, cache: cache }, this.ready); }; /** * Loaded? * * @return {Boolean} */ MouseStats.prototype.loaded = function(){ return is.array(window.MouseStatsVisitorPlaybacks); }; /** * Identify. * * http://www.mousestats.com/docs/wiki/7/how-to-add-custom-data-to-visitor-playbacks * * @param {Identify} identify */ MouseStats.prototype.identify = function(identify){ each(identify.traits(), function(key, value){ window.MouseStatsVisitorPlaybacks.customVariable(key, value); }); }; }, {"analytics.js-integration":89,"use-https":91,"each":4,"is":92}], 60: [function(require, module, exports) { /** * Module dependencies. */ var integration = require('analytics.js-integration'); var push = require('global-queue')('__nls'); /** * Expose `Navilytics` integration. */ var Navilytics = module.exports = integration('Navilytics') .assumesPageview() .global('__nls') .option('memberId', '') .option('projectId', '') .tag('<script src="//www.navilytics.com/nls.js?mid={{ memberId }}&pid={{ projectId }}">'); /** * Initialize. * * https://www.navilytics.com/member/code_settings * * @param {Object} page */ Navilytics.prototype.initialize = function(page){ window.__nls = window.__nls || []; this.load(this.ready); }; /** * Loaded? * * @return {Boolean} */ Navilytics.prototype.loaded = function(){ return !! (window.__nls && [].push != window.__nls.push); }; /** * Track. * * https://www.navilytics.com/docs#tags * * @param {Track} track */ Navilytics.prototype.track = function(track){ push('tagRecording', track.event()); }; }, {"analytics.js-integration":89,"global-queue":160}], 61: [function(require, module, exports) { var integration = require('analytics.js-integration'); var alias = require('alias'); var Identify = require('facade').Identify; /** * Expose `plugin`. */ /*module.exports = exports = function(analytics){ analytics.addIntegration(Nudgespot); };*/ /** * Expose `Nudgespot` integration. */ var Nudgespot = module.exports = integration('Nudgespot') .assumesPageview() .option('apiKey', '') .global('nudgespot') .tag('<script id="nudgespot" src="//cdn.nudgespot.com/nudgespot.js">'); /** * Initialize Nudgespot. */ Nudgespot.prototype.initialize = function(page){ window.nudgespot = window.nudgespot || []; window.nudgespot.init = function(n, t){function f(n,m){var a=m.split('.');2==a.length&&(n=n[a[0]],m=a[1]);n[m]=function(){n.push([m].concat(Array.prototype.slice.call(arguments,0)))}}n._version=0.1;n._globals=[t];n.people=n.people||[];n.params=n.params||[];m="track register unregister identify set_config people.delete people.create people.update people.create_property people.tag people.remove_Tag".split(" ");for (var i=0;i<m.length;i++)f(n,m[i])}; window.nudgespot.init(window.nudgespot, this.options.apiKey); this.load(this.ready); }; /** * Has the Nudgespot library been loaded yet? */ Nudgespot.prototype.loaded = function(){ return (!! window.nudgespot) && (window.nudgespot.push !== Array.prototype.push); }; /** * Identify a user. */ Nudgespot.prototype.identify = function(identify){ if (!identify.userId()) return this.debug('user id required'); var traits = identify.traits({ createdAt: 'created' }); traits = alias(traits, { created: 'created_at' }); window.nudgespot.identify(identify.userId(), traits); }; /** * Track an event. */ Nudgespot.prototype.track = function(track){ var properties = track.properties(); window.nudgespot.track(track.event(), properties); }; }, {"analytics.js-integration":89,"alias":163,"facade":133}], 62: [function(require, module, exports) { /** * Module dependencies. */ var integration = require('analytics.js-integration'); var https = require('use-https'); var tick = require('next-tick'); /** * Expose `Olark` integration. */ var Olark = module.exports = integration('Olark') .assumesPageview() .global('olark') .option('identify', true) .option('page', true) .option('siteId', '') .option('groupId', '') .option('listen', false) .option('track', false); /** * The context for this integration. */ var integration = { name: 'olark', version: '1.0.0' }; /** * Initialize. * * http://www.olark.com/documentation * https://www.olark.com/documentation/javascript/api.chat.setOperatorGroup * * @param {Facade} page */ Olark.prototype.initialize = function(page){ var self = this; this.load(function(){ tick(self.ready); }); // assign chat to a specific site var groupId = this.options.groupId; if (groupId) api('chat.setOperatorGroup', { group: groupId }); // keep track of the widget's open state api('box.onExpand', function(){ self._open = true; }); api('box.onShrink', function(){ self._open = false; }); // record events if (this.options.listen) this.attachListeners(); }; /** * Loaded? * * @return {Boolean} */ Olark.prototype.loaded = function(){ return !! window.olark; }; /** * Listen for events. */ Olark.prototype.attachListeners = function(){ var self = this; api('chat.onBeginConversation', function(){ self.analytics.track( 'Live Chat Conversation Started', {}, { context: { integration: integration }} ); }); api('chat.onMessageToOperator', function(event){ self.analytics.track( 'Live Chat Message Sent', {}, { context: { integration: integration }} ); }); api('chat.onMessageToVisitor', function(event){ self.analytics.track( 'Live Chat Message Received', {}, { context: { integration: integration }} ); }); }; /** * Load. * * @param {Function} callback */ Olark.prototype.load = function(callback){ var el = document.getElementById('olark'); window.olark||(function(c){var f=window,d=document,l=https()?"https:":"http:",z=c.name,r="load";var nt=function(){f[z]=function(){(a.s=a.s||[]).push(arguments)};var a=f[z]._={},q=c.methods.length;while (q--) {(function(n){f[z][n]=function(){f[z]("call",n,arguments)}})(c.methods[q])}a.l=c.loader;a.i=nt;a.p={ 0:+new Date() };a.P=function(u){a.p[u]=new Date()-a.p[0]};function s(){a.P(r);f[z](r)}f.addEventListener?f.addEventListener(r,s,false):f.attachEvent("on"+r,s);var ld=function(){function p(hd){hd="head";return ["<",hd,"></",hd,"><",i,' onl' + 'oad="var d=',g,";d.getElementsByTagName('head')[0].",j,"(d.",h,"('script')).",k,"='",l,"//",a.l,"'",'"',"></",i,">"].join("")}var i="body",m=d[i];if (!m) {return setTimeout(ld,100)}a.P(1);var j="appendChild",h="createElement",k="src",n=d[h]("div"),v=n[j](d[h](z)),b=d[h]("iframe"),g="document",e="domain",o;n.style.display="none";m.insertBefore(n,m.firstChild).id=z;b.frameBorder="0";b.id=z+"-loader";if (/MSIE[ ]+6/.test(navigator.userAgent)) {b.src="javascript:false"}b.allowTransparency="true";v[j](b);try {b.contentWindow[g].open()}catch (w) {c[e]=d[e];o="javascript:var d="+g+".open();d.domain='"+d.domain+"';";b[k]=o+"void(0);"}try {var t=b.contentWindow[g];t.write(p());t.close()}catch (x) {b[k]=o+'d.write("'+p().replace(/"/g,String.fromCharCode(92)+'"')+'");d.close();'}a.P(2)};ld()};nt()})({ loader: "static.olark.com/jsclient/loader0.js", name:"olark", methods:["configure","extend","declare","identify"] }); window.olark.identify(this.options.siteId); callback(); }; /** * Page. * * @param {Facade} page */ Olark.prototype.page = function(page){ if (!this.options.page) return; var props = page.properties(); var name = page.fullName(); if (!name && !props.url) return; name = name ? name + ' page' : props.url; this.notify('looking at ' + name); }; /** * Identify. * * @param {Facade} identify */ Olark.prototype.identify = function(identify){ if (!this.options.identify) return; var username = identify.username(); var traits = identify.traits(); var id = identify.userId(); var email = identify.email(); var phone = identify.phone(); var name = identify.name() || identify.firstName(); if (traits) api('visitor.updateCustomFields', traits); if (email) api('visitor.updateEmailAddress', { emailAddress: email }); if (phone) api('visitor.updatePhoneNumber', { phoneNumber: phone }); if (name) api('visitor.updateFullName', { fullName: name }); // figure out best nickname var nickname = name || email || username || id; if (name && email) nickname += ' (' + email + ')'; if (nickname) api('chat.updateVisitorNickname', { snippet: nickname }); }; /** * Track. * * @param {Facade} track */ Olark.prototype.track = function(track){ if (!this.options.track) return; this.notify('visitor triggered "' + track.event() + '"'); }; /** * Send a notification `message` to the operator, only when a chat is active and * when the chat is open. * * @param {String} message */ Olark.prototype.notify = function(message){ if (!this._open) return; // lowercase since olark does message = message.toLowerCase(); api('visitor.getDetails', function(data){ if (!data || !data.isConversing) return; api('chat.sendNotificationToOperator', { body: message }); }); }; /** * Helper for Olark API calls. * * @param {String} action * @param {Object} value */ function api(action, value) { window.olark('api.' + action, value); } }, {"analytics.js-integration":89,"use-https":91,"next-tick":104}], 63: [function(require, module, exports) { /** * Module dependencies. */ var integration = require('analytics.js-integration'); var push = require('global-queue')('optimizely'); var callback = require('callback'); var tick = require('next-tick'); var bind = require('bind'); var each = require('each'); var isEmpty = require('is-empty'); var foldl = require('foldl'); /** * Expose `Optimizely` integration. */ var Optimizely = module.exports = integration('Optimizely') .option('variations', true) .option('listen', false) .option('trackNamedPages', true) .option('trackCategorizedPages', true); /** * The name and version for this integration. */ var integration = { name: 'optimizely', version: '1.0.0' }; /** * Initialize. * * https://www.optimizely.com/docs/api#function-calls */ Optimizely.prototype.initialize = function(){ var self = this; if (this.options.variations) { tick(function(){ self.replay(); }); } if (this.options.listen) { tick(function(){ self.roots(); }); } this.ready(); }; /** * Track. * * https://www.optimizely.com/docs/api#track-event * * @param {Track} track */ Optimizely.prototype.track = function(track){ var props = track.properties(); if (props.revenue) props.revenue *= 100; push('trackEvent', track.event(), props); }; /** * Page. * * https://www.optimizely.com/docs/api#track-event * * @param {Page} page */ Optimizely.prototype.page = function(page){ var category = page.category(); var name = page.fullName(); var opts = this.options; // categorized pages if (category && opts.trackCategorizedPages) { this.track(page.track(category)); } // named pages if (name && opts.trackNamedPages) { this.track(page.track(name)); } }; /** * Send experiment data as track events to Segment * * https://www.optimizely.com/docs/api#data-object */ Optimizely.prototype.roots = function(){ if (!window.optimizely) return; // in case the snippet isnt on the page var data = window.optimizely.data; if (!data) return; var allExperiments = data.experiments; if (!data || !data.state || !allExperiments) return; var variationNamesMap = data.state.variationNamesMap; var variationIdsMap = data.state.variationIdsMap; var activeExperimentIds = data.state.activeExperiments; var activeExperiments = getExperiments(activeExperimentIds, variationNamesMap, variationIdsMap, allExperiments); var self = this; each(activeExperiments, function(props){ self.analytics.track( 'Experiment Viewed', props, { context: { integration: integration } } ); }); }; /** * Retrieves active experiments * * @param {Object} state * @param {Object} allExperiments */ function getExperiments(activeExperimentIds, variationNamesMap, variationIdsMap, allExperiments) { return foldl(function(results, experimentId){ var experiment = allExperiments[experimentId]; if (experiment) { results.push({ variationName: variationNamesMap[experimentId], variationId: variationIdsMap[experimentId], experimentId: experimentId, experimentName: experiment.name }); } return results; }, [], activeExperimentIds); }; /** * Replay experiment data as traits to other enabled providers. * * https://www.optimizely.com/docs/api#data-object */ Optimizely.prototype.replay = function(){ if (!window.optimizely) return; // in case the snippet isnt on the page var data = window.optimizely.data; if (!data || !data.experiments || !data.state) return; var experiments = data.experiments; var map = data.state.variationNamesMap; var traits = {}; each(map, function(experimentId, variation){ var experiment = experiments[experimentId].name; traits['Experiment: ' + experiment] = variation; }); this.analytics.identify(traits); }; }, {"analytics.js-integration":89,"global-queue":160,"callback":95,"next-tick":104,"bind":102,"each":4,"is-empty":123,"foldl":167}], 64: [function(require, module, exports) { var integration = require('analytics.js-integration'); var omit = require('omit'); var Outbound = module.exports = integration('Outbound') .global('outbound') .option('publicApiKey', '') .tag('<script src="//cdn.outbound.io/{{ publicApiKey }}.js">'); Outbound.prototype.initialize = function(page){ window.outbound = window.outbound || []; window.outbound.methods = ['identify', 'track', 'registerApnsToken', 'registerGcmToken', 'disableApnsToken', 'disableGcmToken']; window.outbound.factory = function(method){ return function(){ var args = Array.prototype.slice.call(arguments); args.unshift(method); window.outbound.push(args); return window.outbound; }; }; for (var i = 0; i < window.outbound.methods.length; i++) { var key = window.outbound.methods[i]; window.outbound[key] = window.outbound.factory(key); } this.load(this.ready); }; Outbound.prototype.loaded = function(){ return window.outbound; }; Outbound.prototype.identify = function(identify){ var traitsToOmit = [ 'id', 'userId', 'email', 'phone', 'firstName', 'lastName' ]; var userId = identify.userId(); var attributes = { attributes: omit(traitsToOmit, identify.traits()), email: identify.email(), phoneNumber: identify.phone(), firstName: identify.firstName(), lastName: identify.lastName() }; outbound.identify(userId, attributes); }; Outbound.prototype.track = function(track){ window.outbound.track(track.event(), track.properties()); }; }, {"analytics.js-integration":89,"omit":177}], 65: [function(require, module, exports) { /** * Module dependencies. */ var integration = require('analytics.js-integration'); var push = require('global-queue')('_pq'); /** * Expose `PerfectAudience` integration. */ var PerfectAudience = module.exports = integration('Perfect Audience') .assumesPageview() .global('_pq') .option('siteId', '') .tag('<script src="//tag.perfectaudience.com/serve/{{ siteId }}.js">'); /** * Initialize. * * http://support.perfectaudience.com/knowledgebase/articles/212490-visitor-tracking-api * * @param {Object} page */ PerfectAudience.prototype.initialize = function(page){ window._pq = window._pq || []; this.load(this.ready); }; /** * Loaded? * * @return {Boolean} */ PerfectAudience.prototype.loaded = function(){ return !! (window._pq && window._pq.push); }; /** * Track. * * http://support.perfectaudience.com/knowledgebase/articles/212490-visitor-tracking-api * * @param {Track} event */ PerfectAudience.prototype.track = function(track){ var total = track.total() || track.revenue(); var orderId = track.orderId(); var props = {}; var sendProps = false; if (total) { props.revenue = total; sendProps = true; } if (orderId) { props.orderId = orderId; sendProps = true; } if (!sendProps) return push('track', track.event()); return push('track', track.event(), props); }; /** * Viewed Product. * * http://support.perfectaudience.com/knowledgebase/articles/212490-visitor-tracking-api * * @param {Track} event */ PerfectAudience.prototype.viewedProduct = function(track){ var product = track.id() || track.sku(); push('track', track.event()); push('trackProduct', product); }; /** * Completed Purchase. * * http://support.perfectaudience.com/knowledgebase/articles/212490-visitor-tracking-api * * @param {Track} event */ PerfectAudience.prototype.completedOrder = function(track){ var total = track.total() || track.revenue(); var orderId = track.orderId(); var props = {}; if (total) props.revenue = total; if (orderId) props.orderId = orderId; push('track', track.event(), props); }; }, {"analytics.js-integration":89,"global-queue":160}], 66: [function(require, module, exports) { /** * Module dependencies. */ var integration = require('analytics.js-integration'); var push = require('global-queue')('_prum'); var date = require('load-date'); /** * Expose `Pingdom` integration. */ var Pingdom = module.exports = integration('Pingdom') .assumesPageview() .global('_prum') .global('PRUM_EPISODES') .option('id', '') .tag('<script src="//rum-static.pingdom.net/prum.min.js">'); /** * Initialize. * * @param {Object} page */ Pingdom.prototype.initialize = function(page){ window._prum = window._prum || []; push('id', this.options.id); push('mark', 'firstbyte', date.getTime()); var self = this; this.load(this.ready); }; /** * Loaded? * * @return {Boolean} */ Pingdom.prototype.loaded = function(){ return !! (window._prum && window._prum.push !== Array.prototype.push); }; }, {"analytics.js-integration":89,"global-queue":160,"load-date":159}], 67: [function(require, module, exports) { /** * Module dependencies. */ var integration = require('analytics.js-integration'); var push = require('global-queue')('_paq'); var each = require('each'); var is = require('is'); /** * Expose `Piwik` integration. */ var Piwik = module.exports = integration('Piwik') .global('_paq') .option('url', null) .option('siteId', '') .option('customVariableLimit', 5) .mapping('goals') .tag('<script src="{{ url }}/piwik.js">'); /** * Initialize. * * http://piwik.org/docs/javascript-tracking/#toc-asynchronous-tracking */ Piwik.prototype.initialize = function(){ window._paq = window._paq || []; push('setSiteId', this.options.siteId); push('setTrackerUrl', this.options.url + '/piwik.php'); push('enableLinkTracking'); this.load(this.ready); }; /** * Check if Piwik is loaded */ Piwik.prototype.loaded = function(){ return !! (window._paq && window._paq.push != [].push); }; /** * Page * * @param {Page} page */ Piwik.prototype.page = function(page){ push('trackPageView'); }; /** * Track. * * @param {Track} track */ Piwik.prototype.track = function(track){ var goals = this.goals(track.event()); var revenue = track.revenue(); var category = track.category() || 'All'; var action = track.event(); var name = track.proxy('properties.name') || track.proxy('properties.label'); var value = track.value() || track.revenue(); var options = track.options('Piwik'); var customVariables = options.customVars || options.cvar; if (!is.object(customVariables)) { customVariables = {}; } for (var i = 1; i <= this.options.customVariableLimit; i += 1){ if (customVariables[i]) { push('setCustomVariable', i.toString(), customVariables[i][0], customVariables[i][1], 'page'); } } each(goals, function(goal){ push('trackGoal', goal, revenue); }); push('trackEvent', category, action, name, value); }; }, {"analytics.js-integration":89,"global-queue":160,"each":4,"is":92}], 68: [function(require, module, exports) { /** * Module dependencies. */ var integration = require('analytics.js-integration'); var convertDates = require('convert-dates'); var push = require('global-queue')('_preactq'); var alias = require('alias'); /** * Expose `Preact` integration. */ var Preact = module.exports = integration('Preact') .assumesPageview() .global('_preactq') .global('_lnq') .option('projectCode', '') .tag('<script src="//d2bbvl6dq48fa6.cloudfront.net/js/preact-4.1.min.js">'); /** * Initialize. * * http://www.preact.io/api/javascript * * @param {Object} page */ Preact.prototype.initialize = function(page){ window._preactq = window._preactq || []; window._lnq = window._lnq || []; push('_setCode', this.options.projectCode); this.load(this.ready); }; /** * Loaded? * * @return {Boolean} */ Preact.prototype.loaded = function(){ return !! (window._preactq && window._preactq.push !== Array.prototype.push); }; /** * Identify. * * @param {Identify} identify */ Preact.prototype.identify = function(identify){ if (!identify.userId()) return; var traits = identify.traits({ created: 'created_at' }); traits = convertDates(traits, convertDate); push('_setPersonData', { name: identify.name(), email: identify.email(), uid: identify.userId(), properties: traits }); }; /** * Group. * * @param {String} id * @param {Object} properties (optional) * @param {Object} options (optional) */ Preact.prototype.group = function(group){ if (!group.groupId()) return; push('_setAccount', group.traits()); }; /** * Track. * * @param {Track} track */ Preact.prototype.track = function(track){ var props = track.properties(); var revenue = track.revenue(); var event = track.event(); var special = { name: event }; if (revenue) { special.revenue = revenue * 100; delete props.revenue; } if (props.note) { special.note = props.note; delete props.note; } push('_logEvent', special, props); }; /** * Convert a `date` to a format Preact supports. * * @param {Date} date * @return {Number} */ function convertDate(date){ return Math.floor(date / 1000); } }, {"analytics.js-integration":89,"convert-dates":164,"global-queue":160,"alias":163}], 69: [function(require, module, exports) { /** * Module dependencies. */ var integration = require('analytics.js-integration'); var push = require('global-queue')('_kiq'); var Facade = require('facade'); var Identify = Facade.Identify; var bind = require('bind'); var when = require('when'); /** * Expose `Qualaroo` integration. */ var Qualaroo = module.exports = integration('Qualaroo') .assumesPageview() .global('_kiq') .option('customerId', '') .option('siteToken', '') .option('track', false) .tag('<script src="//s3.amazonaws.com/ki.js/{{ customerId }}/{{ siteToken }}.js">'); /** * Initialize. * * @param {Object} page */ Qualaroo.prototype.initialize = function(page){ window._kiq = window._kiq || []; var loaded = bind(this, this.loaded); var ready = this.ready; this.load(function(){ when(loaded, ready); }); }; /** * Loaded? * * @return {Boolean} */ Qualaroo.prototype.loaded = function(){ return !! (window._kiq && window._kiq.push !== Array.prototype.push); }; /** * Identify. * * http://help.qualaroo.com/customer/portal/articles/731085-identify-survey-nudge-takers * http://help.qualaroo.com/customer/portal/articles/731091-set-additional-user-properties * * @param {Identify} identify */ Qualaroo.prototype.identify = function(identify){ var traits = identify.traits(); var id = identify.userId(); var email = identify.email(); if (email) id = email; if (id) push('identify', id); if (traits) push('set', traits); }; /** * Track. * * @param {String} event * @param {Object} properties (optional) * @param {Object} options (optional) */ Qualaroo.prototype.track = function(track){ if (!this.options.track) return; var event = track.event(); var traits = {}; traits['Triggered: ' + event] = true; this.identify(new Identify({ traits: traits })); }; }, {"analytics.js-integration":89,"global-queue":160,"facade":133,"bind":102,"when":132}], 70: [function(require, module, exports) { /** * Module dependencies. */ var push = require('global-queue')('_qevents', { wrap: false }); var integration = require('analytics.js-integration'); var useHttps = require('use-https'); var is = require('is'); var reduce = require('reduce'); /** * Expose `Quantcast` integration. */ var Quantcast = module.exports = integration('Quantcast') .assumesPageview() .global('_qevents') .global('__qc') .option('pCode', null) .option('advertise', false) .tag('http', '<script src="http://edge.quantserve.com/quant.js">') .tag('https', '<script src="https://secure.quantserve.com/quant.js">'); /** * Initialize. * * https://www.quantcast.com/learning-center/guides/using-the-quantcast-asynchronous-tag/ * https://www.quantcast.com/help/cross-platform-audience-measurement-guide/ * * @param {Page} page */ Quantcast.prototype.initialize = function(page){ window._qevents = window._qevents || []; var opts = this.options; var settings = { qacct: opts.pCode }; var user = this.analytics.user(); if (user.id()) settings.uid = user.id(); if (page) { settings.labels = this._labels('page', page.category(), page.name()); } push(settings); var name = useHttps() ? 'https' : 'http'; this.load(name, this.ready); }; /** * Loaded? * * @return {Boolean} */ Quantcast.prototype.loaded = function(){ return !! window.__qc; }; /** * Page. * * https://cloudup.com/cBRRFAfq6mf * * @param {Page} page */ Quantcast.prototype.page = function(page){ var category = page.category(); var name = page.name(); var customLabels = page.proxy('properties.label') var labels = this._labels('page', category, name, customLabels); var settings = { event: 'refresh', labels: labels, qacct: this.options.pCode, }; var user = this.analytics.user(); if (user.id()) settings.uid = user.id(); push(settings); }; /** * Identify. * * https://www.quantcast.com/help/cross-platform-audience-measurement-guide/ * * @param {String} id (optional) */ Quantcast.prototype.identify = function(identify){ // edit the initial quantcast settings // TODO: could be done in a cleaner way var id = identify.userId(); if (id) { window._qevents[0] = window._qevents[0] || {}; window._qevents[0].uid = id; } }; /** * Track. * * https://cloudup.com/cBRRFAfq6mf * * @param {Track} track */ Quantcast.prototype.track = function(track){ var name = track.event(); var revenue = track.revenue(); var orderId = track.orderId(); var customLabels = track.proxy('properties.label'); var labels = this._labels('event', name, customLabels); var settings = { event: 'click', labels: labels, qacct: this.options.pCode }; var user = this.analytics.user(); if (null != revenue) settings.revenue = (revenue+''); // convert to string if (orderId) settings.orderid = orderId; if (user.id()) settings.uid = user.id(); push(settings); }; /** * Completed Order. * * @param {Track} track * @api private */ Quantcast.prototype.completedOrder = function(track){ var name = track.event(); var revenue = track.total(); var customLabels = track.proxy('properties.label') var labels = this._labels('event', name, customLabels); var category = track.category(); var repeat = track.proxy('properties.repeat'); if (this.options.advertise && category) { labels += ',' + this._labels('pcat', category); } if ('boolean' == typeof repeat) { labels += ',_fp.customer.' + (repeat ? 'repeat' : 'new'); } var settings = { event: 'refresh', // the example Quantcast sent has completed order send refresh not click labels: labels, revenue: (revenue+''), // convert to string orderid: track.orderId(), qacct: this.options.pCode }; push(settings); }; /** * Generate quantcast labels. * * Example: * * options.advertise = false; * labels('event', 'my event'); * // => "event.my event" * * options.advertise = true; * labels('event', 'my event'); * // => "_fp.event.my event" * * @param {String} type * @param {String} ... * @return {String} * @api private */ Quantcast.prototype._labels = function(type){ var args = Array.prototype.slice.call(arguments, 1); var advertise = this.options.advertise; if (advertise && 'page' == type) type = 'event'; if (advertise) type = '_fp.' + type; var separator = advertise ? ' ' : '.'; var ret = reduce(args, function(ret, arg){ if (arg != null) { ret.push(String(arg).replace(/, /g, ',')); } return ret; }, []).join(separator); return [type, ret].join('.'); }; }, {"global-queue":160,"analytics.js-integration":89,"use-https":91,"is":92,"reduce":179}], 179: [function(require, module, exports) { /** * Reduce `arr` with `fn`. * * @param {Array} arr * @param {Function} fn * @param {Mixed} initial * * TODO: combatible error handling? */ module.exports = function(arr, fn, initial){ var idx = 0; var len = arr.length; var curr = arguments.length == 3 ? initial : arr[idx++]; while (idx < len) { curr = fn.call(null, curr, arr[idx], ++idx, arr); } return curr; }; }, {}], 71: [function(require, module, exports) { /** * Module dependencies. */ var integration = require('analytics.js-integration'); var extend = require('extend'); var is = require('is'); /** * Expose `Rollbar` integration. */ var RollbarIntegration = module.exports = integration('Rollbar') .global('Rollbar') .option('identify', true) .option('accessToken', '') .option('environment', 'unknown') .option('captureUncaught', true); /** * Initialize. * * @param {Object} page */ RollbarIntegration.prototype.initialize = function(page){ var _rollbarConfig = this.config = { accessToken: this.options.accessToken, captureUncaught: this.options.captureUncaught, payload: { environment: this.options.environment } }; // jscs:disable (function(a,b){function c(b){this.shimId=++h,this.notifier=null,this.parentShim=b,this.logger=function(){},a.console&&void 0===a.console.shimId&&(this.logger=a.console.log)}function d(b,c,d){a._rollbarWrappedError&&(d[4]||(d[4]=a._rollbarWrappedError),d[5]||(d[5]=a._rollbarWrappedError._rollbarContext),a._rollbarWrappedError=null),b.uncaughtError.apply(b,d),c&&c.apply(a,d)}function e(b){var d=c;return g(function(){if(this.notifier)return this.notifier[b].apply(this.notifier,arguments);var c=this,e="scope"===b;e&&(c=new d(this));var f=Array.prototype.slice.call(arguments,0),g={shim:c,method:b,args:f,ts:new Date};return a._rollbarShimQueue.push(g),e?c:void 0})}function f(a,b){if(b.hasOwnProperty&&b.hasOwnProperty("addEventListener")){var c=b.addEventListener;b.addEventListener=function(b,d,e){c.call(this,b,a.wrap(d),e)};var d=b.removeEventListener;b.removeEventListener=function(a,b,c){d.call(this,a,b&&b._wrapped?b._wrapped:b,c)}}}function g(a,b){return b=b||this.logger,function(){try{return a.apply(this,arguments)}catch(c){b("Rollbar internal error:",c)}}}var h=0;c.init=function(a,b){var e=b.globalAlias||"Rollbar";if("object"==typeof a[e])return a[e];a._rollbarShimQueue=[],a._rollbarWrappedError=null,b=b||{};var h=new c;return g(function(){if(h.configure(b),b.captureUncaught){var c=a.onerror;a.onerror=function(){var a=Array.prototype.slice.call(arguments,0);d(h,c,a)};var g,i,j="EventTarget,Window,Node,ApplicationCache,AudioTrackList,ChannelMergerNode,CryptoOperation,EventSource,FileReader,HTMLUnknownElement,IDBDatabase,IDBRequest,IDBTransaction,KeyOperation,MediaController,MessagePort,ModalWindow,Notification,SVGElementInstance,Screen,TextTrack,TextTrackCue,TextTrackList,WebSocket,WebSocketWorker,Worker,XMLHttpRequest,XMLHttpRequestEventTarget,XMLHttpRequestUpload".split(",");for(g=0;g<j.length;++g)i=j[g],a[i]&&a[i].prototype&&f(h,a[i].prototype)}return a[e]=h,h},h.logger)()},c.prototype.loadFull=function(a,b,c,d,e){var f=g(function(){var a=b.createElement("script"),e=b.getElementsByTagName("script")[0];a.src=d.rollbarJsUrl,a.async=!c,a.onload=h,e.parentNode.insertBefore(a,e)},this.logger),h=g(function(){var b;if(void 0===a._rollbarPayloadQueue){var c,d,f,g;for(b=new Error("rollbar.js did not load");c=a._rollbarShimQueue.shift();)for(f=c.args,g=0;g<f.length;++g)if(d=f[g],"function"==typeof d){d(b);break}}"function"==typeof e&&e(b)},this.logger);g(function(){c?f():a.addEventListener?a.addEventListener("load",f,!1):a.attachEvent("onload",f)},this.logger)()},c.prototype.wrap=function(b,c){try{var d;if(d="function"==typeof c?c:function(){return c||{}},"function"!=typeof b)return b;if(b._isWrap)return b;if(!b._wrapped){b._wrapped=function(){try{return b.apply(this,arguments)}catch(c){throw c._rollbarContext=d(),c._rollbarContext._wrappedSource=b.toString(),a._rollbarWrappedError=c,c}},b._wrapped._isWrap=!0;for(var e in b)b.hasOwnProperty(e)&&(b._wrapped[e]=b[e])}return b._wrapped}catch(f){return b}};for(var i="log,debug,info,warn,warning,error,critical,global,configure,scope,uncaughtError".split(","),j=0;j<i.length;++j)c.prototype[i[j]]=e(i[j]);var k="//d37gvrvc0wt4s1.cloudfront.net/js/v1.1/rollbar.min.js";_rollbarConfig.rollbarJsUrl=_rollbarConfig.rollbarJsUrl||k;var l=c.init(a,_rollbarConfig);})(window,document); // jscs:enable this.load(this.ready); }; /** * Loaded? * * @return {Boolean} */ RollbarIntegration.prototype.loaded = function(){ return is.object(window.Rollbar) && null == window.Rollbar.shimId; }; /** * Load. * * @param {Function} callback */ RollbarIntegration.prototype.load = function(callback){ window.Rollbar.loadFull(window, document, true, this.config, callback); }; /** * Identify. * * @param {Identify} identify */ RollbarIntegration.prototype.identify = function(identify){ // do stuff with `id` or `traits` if (!this.options.identify) return; // Don't allow identify without a user id var uid = identify.userId(); if (uid === null || uid === undefined) return; var rollbar = window.Rollbar; var person = { id: uid }; extend(person, identify.traits()); rollbar.configure({ payload: { person: person }}); }; }, {"analytics.js-integration":89,"extend":131,"is":92}], 72: [function(require, module, exports) { /** * Module dependencies. */ var integration = require('analytics.js-integration'); /** * Expose `SaaSquatch` integration. */ var SaaSquatch = module.exports = integration('SaaSquatch') .option('tenantAlias', '') .option('referralImage', '') .global('_sqh') .tag('<script src="//d2rcp9ak152ke1.cloudfront.net/assets/javascripts/squatch.min.js">'); /** * Initialize. * * @param {Page} page */ SaaSquatch.prototype.initialize = function(page){ window._sqh = window._sqh || []; this.load(this.ready); }; /** * Loaded? * * @return {Boolean} */ SaaSquatch.prototype.loaded = function(){ return window._sqh && window._sqh.push != [].push; }; /** * Identify. * * @param {Facade} identify */ SaaSquatch.prototype.identify = function(identify){ var sqh = window._sqh; var accountId = identify.proxy('traits.accountId'); var paymentProviderId = identify.proxy('traits.paymentProviderId'); var accountStatus = identify.proxy('traits.accountStatus'); var referralCode = identify.proxy('traits.referralCode'); var image = identify.proxy('traits.referralImage') || this.options.referralImage; var opts = identify.options(this.name); var id = identify.userId(); var email = identify.email(); if (!(id || email)) return; if (this.called) return; var init = { tenant_alias: this.options.tenantAlias, first_name: identify.firstName(), last_name: identify.lastName(), user_image: identify.avatar(), email: email, user_id: id, }; if (accountId) init.account_id = accountId; if (paymentProviderId) init.payment_provider_id = paymentProviderId; if (init.payment_provider_id == "null") init.payment_provider_id = null; if (accountStatus) init.account_status = accountStatus; if (referralCode) init.referral_code = referralCode; if (opts.checksum) init.checksum = opts.checksum; if (image) init.fb_share_image = image; sqh.push(['init', init]); this.called = true; this.load(); }; /** * Group. * * @param {Group} group */ SaaSquatch.prototype.group = function(group){ var sqh = window._sqh; var props = group.properties(); var id = group.groupId(); var image = group.proxy('traits.referralImage') || this.options.referralImage; var opts = group.options(this.name); // tenant_alias is required. if (this.called) return; var init = { tenant_alias: this.options.tenantAlias, account_id: id }; if (opts.checksum) init.checksum = opts.checksum; if (image) init.fb_share_image = image; sqh.push(['init', init]); this.called = true; this.load(); }; }, {"analytics.js-integration":89}], 73: [function(require, module, exports) { /** * Module dependencies. */ var integration = require('analytics.js-integration'); var when = require('when'); /** * Expose `SatisMeter` integration. */ var SatisMeter = module.exports = integration('SatisMeter') .global('satismeter') .option('token', '') .tag('<script src="https://app.satismeter.com/satismeter.js">'); /** * Initialize. * * @param {Object} page */ SatisMeter.prototype.initialize = function(page){ var self = this; this.load(function(){ when(function(){ return self.loaded(); }, self.ready); }); }; /** * Loaded? * * @return {Boolean} */ SatisMeter.prototype.loaded = function(){ return !!window.satismeter; }; /** * Identify. * * @param {Identify} identify */ SatisMeter.prototype.identify = function(identify){ var traits = identify.traits(); traits.token = this.options.token; traits.user = { id: identify.userId() }; if (identify.name()) { traits.user.name = identify.name(); } if (identify.email()) { traits.user.email = identify.email(); } if (identify.created()) { traits.user.signUpDate = identify.created().toISOString(); } // Remove traits that are already passed in user object delete traits.id; delete traits.email; delete traits.name; delete traits.created; window.satismeter(traits); }; }, {"analytics.js-integration":89,"when":132}], 74: [function(require, module, exports) { /** * Module dependencies. */ var integration = require('analytics.js-integration'); var localstorage = require('store'); var protocol = require('protocol'); var utm = require('utm-params'); var ads = require('ad-params'); var send = require('send-json'); var cookie = require('cookie'); var clone = require('clone'); var uuid = require('uuid'); var top = require('top-domain'); var extend = require('extend'); var json = require('segmentio/[email protected]'); /** * Cookie options */ var options = { maxage: 31536000000, // 1y secure: false, path: '/' }; /** * Expose `Segment` integration. */ var Segment = exports = module.exports = integration('Segment.io') .option('apiKey', ''); /** * Get the store. * * @return {Function} */ exports.storage = function(){ return 'file:' == protocol() || 'chrome-extension:' == protocol() ? localstorage : cookie; }; /** * Expose global for testing. */ exports.global = window; /** * Initialize. * * https://github.com/segmentio/segmentio/blob/master/modules/segmentjs/segment.js/v1/segment.js * * @param {Object} page */ Segment.prototype.initialize = function(page){ var self = this; this.ready(); this.analytics.on('invoke', function(msg){ var action = msg.action(); var listener = 'on' + msg.action(); self.debug('%s %o', action, msg); if (self[listener]) self[listener](msg); self.ready(); }); }; /** * Loaded. * * @return {Boolean} */ Segment.prototype.loaded = function(){ return true; }; /** * Page. * * @param {Page} page */ Segment.prototype.onpage = function(page){ this.send('/p', page.json()); }; /** * Identify. * * @param {Identify} identify */ Segment.prototype.onidentify = function(identify){ this.send('/i', identify.json()); }; /** * Group. * * @param {Group} group */ Segment.prototype.ongroup = function(group){ this.send('/g', group.json()); }; /** * Track. * * @param {Track} track */ Segment.prototype.ontrack = function(track){ var json = track.json(); delete json.traits; // TODO: figure out why we need traits. this.send('/t', json); }; /** * Alias. * * @param {Alias} alias */ Segment.prototype.onalias = function(alias){ var json = alias.json(); var user = this.analytics.user(); json.previousId = json.previousId || json.from || user.id() || user.anonymousId(); json.userId = json.userId || json.to; delete json.from; delete json.to; this.send('/a', json); }; /** * Normalize the given `msg`. * * @param {Object} msg * @api private */ Segment.prototype.normalize = function(msg){ this.debug('normalize %o', msg); var user = this.analytics.user(); var global = exports.global; var query = global.location.search; var ctx = msg.context = msg.context || msg.options || {}; delete msg.options; msg.writeKey = this.options.apiKey; ctx.userAgent = navigator.userAgent; if (!ctx.library) ctx.library = { name: 'analytics.js', version: this.analytics.VERSION }; if (query) ctx.campaign = utm(query); this.referrerId(query, ctx); msg.userId = msg.userId || user.id(); msg.anonymousId = user.anonymousId(); msg.messageId = uuid(); msg.sentAt = new Date(); this.debug('normalized %o', msg); return msg; }; /** * Send `obj` to `path`. * * @param {String} path * @param {Object} obj * @param {Function} fn * @api private */ Segment.prototype.send = function(path, msg, fn){ var url = scheme() + '//api.segment.io/v1' + path; var headers = { 'Content-Type': 'text/plain' }; var fn = fn || noop; var self = this; // msg msg = this.normalize(msg); // send send(url, msg, headers, function(err, res){ self.debug('sent %O, received %O', msg, arguments); if (err) return fn(err); res.url = url; fn(null, res); }); }; /** * Gets/sets cookies on the appropriate domain. * * @param {String} name * @param {Mixed} val */ Segment.prototype.cookie = function(name, val){ var store = Segment.storage(); if (arguments.length === 1) return store(name); var global = exports.global; var href = global.location.href; var domain = '.' + top(href); if ('.' == domain) domain = ''; this.debug('store domain %s -> %s', href, domain); var opts = clone(options); opts.domain = domain; this.debug('store %s, %s, %o', name, val, opts); store(name, val, opts); if (store(name)) return; delete opts.domain; this.debug('fallback store %s, %s, %o', name, val, opts); store(name, val, opts); }; /** * Add referrerId to context. * * TODO: remove. * * @param {Object} query * @param {Object} ctx * @api private */ Segment.prototype.referrerId = function(query, ctx){ var stored = this.cookie('s:context.referrer'); var ad; if (stored) stored = json.parse(stored); if (query) ad = ads(query); ad = ad || stored; if (!ad) return; ctx.referrer = extend(ctx.referrer || {}, ad); this.cookie('s:context.referrer', json.stringify(ad)); } /** * Get the scheme. * * The function returns `http:` * if the protocol is `http:` and * `https:` for other protocols. * * @return {String} */ function scheme(){ return 'http:' == protocol() ? 'http:' : 'https:'; } /** * Noop */ function noop(){} }, {"analytics.js-integration":89,"store":180,"protocol":181,"utm-params":124,"ad-params":182,"send-json":183,"cookie":184,"clone":96,"uuid":185,"top-domain":125,"extend":131,"segmentio/[email protected]":165}], 180: [function(require, module, exports) { /** * dependencies. */ var unserialize = require('unserialize'); var each = require('each'); var storage; /** * Safari throws when a user * blocks access to cookies / localstorage. */ try { storage = window.localStorage; } catch (e) { storage = null; } /** * Expose `store` */ module.exports = store; /** * Store the given `key`, `val`. * * @param {String|Object} key * @param {Mixed} value * @return {Mixed} * @api public */ function store(key, value){ var length = arguments.length; if (0 == length) return all(); if (2 <= length) return set(key, value); if (1 != length) return; if (null == key) return storage.clear(); if ('string' == typeof key) return get(key); if ('object' == typeof key) return each(key, set); } /** * supported flag. */ store.supported = !! storage; /** * Set `key` to `val`. * * @param {String} key * @param {Mixed} val */ function set(key, val){ return null == val ? storage.removeItem(key) : storage.setItem(key, JSON.stringify(val)); } /** * Get `key`. * * @param {String} key * @return {Mixed} */ function get(key){ return unserialize(storage.getItem(key)); } /** * Get all. * * @return {Object} */ function all(){ var len = storage.length; var ret = {}; var key; while (0 <= --len) { key = storage.key(len); ret[key] = get(key); } return ret; } }, {"unserialize":186,"each":113}], 186: [function(require, module, exports) { /** * Unserialize the given "stringified" javascript. * * @param {String} val * @return {Mixed} */ module.exports = function(val){ try { return JSON.parse(val); } catch (e) { return val || undefined; } }; }, {}], 181: [function(require, module, exports) { /** * Convenience alias */ var define = Object.defineProperty; /** * The base protocol */ var initialProtocol = window.location.protocol; /** * Fallback mocked protocol in case Object.defineProperty doesn't exist. */ var mockedProtocol; module.exports = function (protocol) { if (arguments.length === 0) return get(); else return set(protocol); }; /** * Sets the protocol to be http: */ module.exports.http = function () { set('http:'); }; /** * Sets the protocol to be https: */ module.exports.https = function () { set('https:'); }; /** * Reset to the initial protocol. */ module.exports.reset = function () { set(initialProtocol); }; /** * Gets the current protocol, using the fallback and then the native protocol. * * @return {String} protocol */ function get () { return mockedProtocol || window.location.protocol; } /** * Sets the protocol * * @param {String} protocol */ function set (protocol) { try { define(window.location, 'protocol', { get: function () { return protocol; } }); } catch (err) { mockedProtocol = protocol; } } }, {}], 182: [function(require, module, exports) { /** * Module dependencies. */ var parse = require('querystring').parse; /** * Expose `ads` */ module.exports = ads; /** * All the ad query params we look for. */ var QUERYIDS = { 'btid' : 'dataxu', 'urid' : 'millennial-media' }; /** * Get all ads info from the given `querystring` * * @param {String} query * @return {Object} * @api private */ function ads(query){ var params = parse(query); for (var key in params) { for (var id in QUERYIDS) { if (key === id) { return { id : params[key], type : QUERYIDS[id] }; } } } } }, {"querystring":126}], 183: [function(require, module, exports) { /** * Module dependencies. */ var encode = require('base64-encode'); var cors = require('has-cors'); var jsonp = require('jsonp'); var JSON = require('json'); /** * Expose `send` */ exports = module.exports = cors ? json : base64; /** * Expose `callback` */ exports.callback = 'callback'; /** * Expose `prefix` */ exports.prefix = 'data'; /** * Expose `json`. */ exports.json = json; /** * Expose `base64`. */ exports.base64 = base64; /** * Expose `type` */ exports.type = cors ? 'xhr' : 'jsonp'; /** * Send the given `obj` to `url` with `fn(err, req)`. * * @param {String} url * @param {Object} obj * @param {Object} headers * @param {Function} fn * @api private */ function json(url, obj, headers, fn){ if (3 == arguments.length) fn = headers, headers = {}; var req = new XMLHttpRequest; req.onerror = fn; req.onreadystatechange = done; req.open('POST', url, true); for (var k in headers) req.setRequestHeader(k, headers[k]); req.send(JSON.stringify(obj)); function done(){ if (4 == req.readyState) return fn(null, req); } } /** * Send the given `obj` to `url` with `fn(err, req)`. * * @param {String} url * @param {Object} obj * @param {Function} fn * @api private */ function base64(url, obj, _, fn){ if (3 == arguments.length) fn = _; var prefix = exports.prefix; obj = encode(JSON.stringify(obj)); obj = encodeURIComponent(obj); url += '?' + prefix + '=' + obj; jsonp(url, { param: exports.callback }, function(err, obj){ if (err) return fn(err); fn(null, { url: url, body: obj }); }); } }, {"base64-encode":187,"has-cors":188,"jsonp":189,"json":165}], 187: [function(require, module, exports) { var utf8Encode = require('utf8-encode'); var keyStr = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/='; module.exports = encode; function encode(input) { var output = ""; var chr1, chr2, chr3, enc1, enc2, enc3, enc4; var i = 0; input = utf8Encode(input); while (i < input.length) { chr1 = input.charCodeAt(i++); chr2 = input.charCodeAt(i++); chr3 = input.charCodeAt(i++); enc1 = chr1 >> 2; enc2 = ((chr1 & 3) << 4) | (chr2 >> 4); enc3 = ((chr2 & 15) << 2) | (chr3 >> 6); enc4 = chr3 & 63; if (isNaN(chr2)) { enc3 = enc4 = 64; } else if (isNaN(chr3)) { enc4 = 64; } output = output + keyStr.charAt(enc1) + keyStr.charAt(enc2) + keyStr.charAt(enc3) + keyStr.charAt(enc4); } return output; } }, {"utf8-encode":190}], 190: [function(require, module, exports) { module.exports = encode; function encode(string) { string = string.replace(/\r\n/g, "\n"); var utftext = ""; for (var n = 0; n < string.length; n++) { var c = string.charCodeAt(n); if (c < 128) { utftext += String.fromCharCode(c); } else if ((c > 127) && (c < 2048)) { utftext += String.fromCharCode((c >> 6) | 192); utftext += String.fromCharCode((c & 63) | 128); } else { utftext += String.fromCharCode((c >> 12) | 224); utftext += String.fromCharCode(((c >> 6) & 63) | 128); utftext += String.fromCharCode((c & 63) | 128); } } return utftext; } }, {}], 188: [function(require, module, exports) { /** * Module exports. * * Logic borrowed from Modernizr: * * - https://github.com/Modernizr/Modernizr/blob/master/feature-detects/cors.js */ try { module.exports = typeof XMLHttpRequest !== 'undefined' && 'withCredentials' in new XMLHttpRequest(); } catch (err) { // if XMLHttp support is disabled in IE then it will throw // when trying to create module.exports = false; } }, {}], 189: [function(require, module, exports) { /** * Module dependencies */ var debug = require('debug')('jsonp'); /** * Module exports. */ module.exports = jsonp; /** * Callback index. */ var count = 0; /** * Noop function. */ function noop(){} /** * JSONP handler * * Options: * - param {String} qs parameter (`callback`) * - timeout {Number} how long after a timeout error is emitted (`60000`) * * @param {String} url * @param {Object|Function} optional options / callback * @param {Function} optional callback */ function jsonp(url, opts, fn){ if ('function' == typeof opts) { fn = opts; opts = {}; } if (!opts) opts = {}; var prefix = opts.prefix || '__jp'; var param = opts.param || 'callback'; var timeout = null != opts.timeout ? opts.timeout : 60000; var enc = encodeURIComponent; var target = document.getElementsByTagName('script')[0] || document.head; var script; var timer; // generate a unique id for this request var id = prefix + (count++); if (timeout) { timer = setTimeout(function(){ cleanup(); if (fn) fn(new Error('Timeout')); }, timeout); } function cleanup(){ script.parentNode.removeChild(script); window[id] = noop; } window[id] = function(data){ debug('jsonp got', data); if (timer) clearTimeout(timer); cleanup(); if (fn) fn(null, data); }; // add qs component url += (~url.indexOf('?') ? '&' : '?') + param + '=' + enc(id); url = url.replace('?&', '?'); debug('jsonp req "%s"', url); // create script script = document.createElement('script'); script.src = url; target.parentNode.insertBefore(script, target); } }, {"debug":191}], 191: [function(require, module, exports) { if ('undefined' == typeof window) { module.exports = require('./lib/debug'); } else { module.exports = require('./debug'); } }, {"./lib/debug":192,"./debug":193}], 192: [function(require, module, exports) { /** * Module dependencies. */ var tty = require('tty'); /** * Expose `debug()` as the module. */ module.exports = debug; /** * Enabled debuggers. */ var names = [] , skips = []; (process.env.DEBUG || '') .split(/[\s,]+/) .forEach(function(name){ name = name.replace('*', '.*?'); if (name[0] === '-') { skips.push(new RegExp('^' + name.substr(1) + '$')); } else { names.push(new RegExp('^' + name + '$')); } }); /** * Colors. */ var colors = [6, 2, 3, 4, 5, 1]; /** * Previous debug() call. */ var prev = {}; /** * Previously assigned color. */ var prevColor = 0; /** * Is stdout a TTY? Colored output is disabled when `true`. */ var isatty = tty.isatty(2); /** * Select a color. * * @return {Number} * @api private */ function color() { return colors[prevColor++ % colors.length]; } /** * Humanize the given `ms`. * * @param {Number} m * @return {String} * @api private */ function humanize(ms) { var sec = 1000 , min = 60 * 1000 , hour = 60 * min; if (ms >= hour) return (ms / hour).toFixed(1) + 'h'; if (ms >= min) return (ms / min).toFixed(1) + 'm'; if (ms >= sec) return (ms / sec | 0) + 's'; return ms + 'ms'; } /** * Create a debugger with the given `name`. * * @param {String} name * @return {Type} * @api public */ function debug(name) { function disabled(){} disabled.enabled = false; var match = skips.some(function(re){ return re.test(name); }); if (match) return disabled; match = names.some(function(re){ return re.test(name); }); if (!match) return disabled; var c = color(); function colored(fmt) { fmt = coerce(fmt); var curr = new Date; var ms = curr - (prev[name] || curr); prev[name] = curr; fmt = ' \u001b[9' + c + 'm' + name + ' ' + '\u001b[3' + c + 'm\u001b[90m' + fmt + '\u001b[3' + c + 'm' + ' +' + humanize(ms) + '\u001b[0m'; console.error.apply(this, arguments); } function plain(fmt) { fmt = coerce(fmt); fmt = new Date().toUTCString() + ' ' + name + ' ' + fmt; console.error.apply(this, arguments); } colored.enabled = plain.enabled = true; return isatty || process.env.DEBUG_COLORS ? colored : plain; } /** * Coerce `val`. */ function coerce(val) { if (val instanceof Error) return val.stack || val.message; return val; } }, {}], 193: [function(require, module, exports) { /** * Expose `debug()` as the module. */ module.exports = debug; /** * Create a debugger with the given `name`. * * @param {String} name * @return {Type} * @api public */ function debug(name) { if (!debug.enabled(name)) return function(){}; return function(fmt){ fmt = coerce(fmt); var curr = new Date; var ms = curr - (debug[name] || curr); debug[name] = curr; fmt = name + ' ' + fmt + ' +' + debug.humanize(ms); // This hackery is required for IE8 // where `console.log` doesn't have 'apply' window.console && console.log && Function.prototype.apply.call(console.log, console, arguments); } } /** * The currently active debug mode names. */ debug.names = []; debug.skips = []; /** * Enables a debug mode by name. This can include modes * separated by a colon and wildcards. * * @param {String} name * @api public */ debug.enable = function(name) { try { localStorage.debug = name; } catch(e){} var split = (name || '').split(/[\s,]+/) , len = split.length; for (var i = 0; i < len; i++) { name = split[i].replace('*', '.*?'); if (name[0] === '-') { debug.skips.push(new RegExp('^' + name.substr(1) + '$')); } else { debug.names.push(new RegExp('^' + name + '$')); } } }; /** * Disable debug output. * * @api public */ debug.disable = function(){ debug.enable(''); }; /** * Humanize the given `ms`. * * @param {Number} m * @return {String} * @api private */ debug.humanize = function(ms) { var sec = 1000 , min = 60 * 1000 , hour = 60 * min; if (ms >= hour) return (ms / hour).toFixed(1) + 'h'; if (ms >= min) return (ms / min).toFixed(1) + 'm'; if (ms >= sec) return (ms / sec | 0) + 's'; return ms + 'ms'; }; /** * Returns true if the given mode name is enabled, false otherwise. * * @param {String} name * @return {Boolean} * @api public */ debug.enabled = function(name) { for (var i = 0, len = debug.skips.length; i < len; i++) { if (debug.skips[i].test(name)) { return false; } } for (var i = 0, len = debug.names.length; i < len; i++) { if (debug.names[i].test(name)) { return true; } } return false; }; /** * Coerce `val`. */ function coerce(val) { if (val instanceof Error) return val.stack || val.message; return val; } // persist try { if (window.localStorage) debug.enable(localStorage.debug); } catch(e){} }, {}], 184: [function(require, module, exports) { /** * Module dependencies. */ var debug = require('debug')('cookie'); /** * Set or get cookie `name` with `value` and `options` object. * * @param {String} name * @param {String} value * @param {Object} options * @return {Mixed} * @api public */ module.exports = function(name, value, options){ switch (arguments.length) { case 3: case 2: return set(name, value, options); case 1: return get(name); default: return all(); } }; /** * Set cookie `name` to `value`. * * @param {String} name * @param {String} value * @param {Object} options * @api private */ function set(name, value, options) { options = options || {}; var str = encode(name) + '=' + encode(value); if (null == value) options.maxage = -1; if (options.maxage) { options.expires = new Date(+new Date + options.maxage); } if (options.path) str += '; path=' + options.path; if (options.domain) str += '; domain=' + options.domain; if (options.expires) str += '; expires=' + options.expires.toUTCString(); if (options.secure) str += '; secure'; document.cookie = str; } /** * Return all cookies. * * @return {Object} * @api private */ function all() { return parse(document.cookie); } /** * Get cookie `name`. * * @param {String} name * @return {String} * @api private */ function get(name) { return all()[name]; } /** * Parse cookie `str`. * * @param {String} str * @return {Object} * @api private */ function parse(str) { var obj = {}; var pairs = str.split(/ *; */); var pair; if ('' == pairs[0]) return obj; for (var i = 0; i < pairs.length; ++i) { pair = pairs[i].split('='); obj[decode(pair[0])] = decode(pair[1]); } return obj; } /** * Encode. */ function encode(value){ try { return encodeURIComponent(value); } catch (e) { debug('error `encode(%o)` - %o', value, e) } } /** * Decode. */ function decode(value) { try { return decodeURIComponent(value); } catch (e) { debug('error `decode(%o)` - %o', value, e) } } }, {"debug":191}], 185: [function(require, module, exports) { /** * Taken straight from jed's gist: https://gist.github.com/982883 * * Returns a random v4 UUID of the form xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx, * where each x is replaced with a random hexadecimal digit from 0 to f, and * y is replaced with a random hexadecimal digit from 8 to b. */ module.exports = function uuid(a){ return a // if the placeholder was passed, return ? ( // a random number from 0 to 15 a ^ // unless b is 8, Math.random() // in which case * 16 // a random number from >> a/4 // 8 to 11 ).toString(16) // in hexadecimal : ( // or otherwise a concatenated string: [1e7] + // 10000000 + -1e3 + // -1000 + -4e3 + // -4000 + -8e3 + // -80000000 + -1e11 // -100000000000, ).replace( // replacing /[018]/g, // zeroes, ones, and eights with uuid // random hex digits ) }; }, {}], 75: [function(require, module, exports) { /** * Module dependencies. */ var integration = require('analytics.js-integration'); var is = require('is'); /** * Expose `Sentry` integration. */ var Sentry = module.exports = integration('Sentry') .global('Raven') .option('config', '') .tag('<script src="//cdn.ravenjs.com/1.1.16/native/raven.min.js">'); /** * Initialize. * * http://raven-js.readthedocs.org/en/latest/config/index.html * https://github.com/getsentry/raven-js/blob/1.1.16/src/raven.js#L734-L741 */ Sentry.prototype.initialize = function(){ var dsn = this.options.config; window.RavenConfig = { dsn: dsn }; this.load(this.ready); }; /** * Loaded? * * @return {Boolean} */ Sentry.prototype.loaded = function(){ return is.object(window.Raven); }; /** * Identify. * * @param {Identify} identify */ Sentry.prototype.identify = function(identify){ window.Raven.setUser(identify.traits()); }; }, {"analytics.js-integration":89,"is":92}], 76: [function(require, module, exports) { /** * Module dependencies. */ var integration = require('analytics.js-integration'); var is = require('is'); var tick = require('next-tick'); /** * Expose `SnapEngage` integration. */ var SnapEngage = module.exports = integration('SnapEngage') .assumesPageview() .global('SnapABug') .global('SnapEngage') .option('apiKey', '') .option('listen', false) .tag('<script src="//www.snapengage.com/cdn/js/{{ apiKey }}.js">'); /** * Integration object for root events. */ var integration = { name: 'snapengage', version: '1.0.0' }; /** * Initialize. * * http://help.snapengage.com/installation-guide-getting-started-in-a-snap/ * * @param {Object} page */ SnapEngage.prototype.initialize = function(page){ var self = this; this.load(function(){ if (self.options.listen) self.attachListeners(); tick(self.ready); }); }; /** * Loaded? * * @return {Boolean} */ SnapEngage.prototype.loaded = function(){ return is.object(window.SnapABug) && is.object(window.SnapEngage); }; /** * Listen for events. */ SnapEngage.prototype.attachListeners = function(){ var self = this; window.SnapEngage.setCallback('StartChat', function(email, message, type){ self.analytics.track('Live Chat Conversation Started', {}, { context: { integration: integration } }); }); window.SnapEngage.setCallback('ChatMessageReceived', function(agent, message){ self.analytics.track('Live Chat Message Received', { agentUsername: agent }, { context: { integration: integration } }); }); window.SnapEngage.setCallback('ChatMessageSent', function(message){ self.analytics.track('Live Chat Message Sent', {}, { context: { integration: integration }}); }); window.SnapEngage.setCallback('Close', function(type, status){ self.analytics.track('Live Chat Conversation Ended', {}, { context: { integration: integration }}); }); }; /** * Identify. * * @param {Identify} identify */ SnapEngage.prototype.identify = function(identify){ var email = identify.email(); if (!email) return; window.SnapABug.setUserEmail(email); }; }, {"analytics.js-integration":89,"is":92,"next-tick":104}], 77: [function(require, module, exports) { /** * Module dependencies. */ var integration = require('analytics.js-integration'); var bind = require('bind'); var when = require('when'); /** * Expose `Spinnakr` integration. */ var Spinnakr = module.exports = integration('Spinnakr') .assumesPageview() .global('_spinnakr_site_id') .global('_spinnakr') .option('siteId', '') .tag('<script src="//d3ojzyhbolvoi5.cloudfront.net/js/so.js">'); /** * Initialize. * * @param {Object} page */ Spinnakr.prototype.initialize = function(page){ window._spinnakr_site_id = this.options.siteId; var loaded = bind(this, this.loaded); var ready = this.ready; this.load(function(){ when(loaded, ready); }); }; /** * Loaded? * * @return {Boolean} */ Spinnakr.prototype.loaded = function(){ return !! window._spinnakr; }; }, {"analytics.js-integration":89,"bind":102,"when":132}], 78: [function(require, module, exports) { /** * Module dependencies. */ var integration = require('analytics.js-integration'); /** * Expose `SupportHero` integration. */ var SupportHero = module.exports = integration('SupportHero') .assumesPageview() .global('supportHeroWidget') .option('token', '') .option('track', false) .tag('<script src="https://d29l98y0pmei9d.cloudfront.net/js/widget.min.js?k={{ token }}">'); /** * Initialize Support Hero. * * @param {Facade} page */ SupportHero.prototype.initialize = function(page){ window.supportHeroWidget = {}; window.supportHeroWidget.setUserId = window.supportHeroWidget.setUserId || function(){}; window.supportHeroWidget.setUserTraits = window.supportHeroWidget.setUserTraits || function(){}; this.load(this.ready); }; /** * Has the Support Hero library been loaded yet? * * @return {Boolean} */ SupportHero.prototype.loaded = function(){ return !! window.supportHeroWidget; }; /** * Identify a user. * * @param {Facade} identify */ SupportHero.prototype.identify = function(identify){ var id = identify.userId(); var traits = identify.traits(); if (id) { window.supportHeroWidget.setUserId(id); } if (traits) { window.supportHeroWidget.setUserTraits(traits); } }; }, {"analytics.js-integration":89}], 79: [function(require, module, exports) { /** * Module dependencies. */ var integration = require('analytics.js-integration'); var slug = require('slug'); var push = require('global-queue')('_tsq'); /** * Expose `Tapstream` integration. */ var Tapstream = module.exports = integration('Tapstream') .assumesPageview() .global('_tsq') .option('accountName', '') .option('trackAllPages', true) .option('trackNamedPages', true) .option('trackCategorizedPages', true) .tag('<script src="//cdn.tapstream.com/static/js/tapstream.js">'); /** * Initialize. * * @param {Object} page */ Tapstream.prototype.initialize = function(page){ window._tsq = window._tsq || []; push('setAccountName', this.options.accountName); this.load(this.ready); }; /** * Loaded? * * @return {Boolean} */ Tapstream.prototype.loaded = function(){ return !! (window._tsq && window._tsq.push !== Array.prototype.push); }; /** * Page. * * @param {Page} page */ Tapstream.prototype.page = function(page){ var category = page.category(); var opts = this.options; var name = page.fullName(); // all pages if (opts.trackAllPages) { this.track(page.track()); } // named pages if (name && opts.trackNamedPages) { this.track(page.track(name)); } // categorized pages if (category && opts.trackCategorizedPages) { this.track(page.track(category)); } }; /** * Track. * * @param {Track} track */ Tapstream.prototype.track = function(track){ var props = track.properties(); push('fireHit', slug(track.event()), [props.url]); // needs events as slugs }; }, {"analytics.js-integration":89,"slug":100,"global-queue":160}], 80: [function(require, module, exports) { /** * Module dependencies. */ var integration = require('analytics.js-integration'); var alias = require('alias'); var clone = require('clone'); /** * Expose `Trakio` integration. */ var Trakio = module.exports = integration('trak.io') .assumesPageview() .global('trak') .option('token', '') .option('trackNamedPages', true) .option('trackCategorizedPages', true) .tag('<script src="//d29p64779x43zo.cloudfront.net/v1/trak.io.min.js">'); /** * Options aliases. */ var optionsAliases = { initialPageview: 'auto_track_page_view' }; /** * Initialize. * * https://docs.trak.io * * @param {Object} page */ Trakio.prototype.initialize = function(page){ var options = this.options; window.trak = window.trak || []; window.trak.io = window.trak.io || {}; window.trak.push = window.trak.push || function(){}; window.trak.io.load = window.trak.io.load || function(e){var r = function(e){return function(){window.trak.push([e].concat(Array.prototype.slice.call(arguments,0))); }; } ,i=["initialize","identify","track","alias","channel","source","host","protocol","page_view"]; for (var s=0;s<i.length;s++) window.trak.io[i[s]]=r(i[s]); window.trak.io.initialize.apply(window.trak.io,arguments); }; window.trak.io.load(options.token, alias(options, optionsAliases)); this.load(this.ready); }; /** * Loaded? * * @return {Boolean} */ Trakio.prototype.loaded = function(){ return !! (window.trak && window.trak.loaded); }; /** * Page. * * @param {Page} page */ Trakio.prototype.page = function(page){ var category = page.category(); var props = page.properties(); var name = page.fullName(); window.trak.io.page_view(props.path, name || props.title); if (category) window.trak.io.channel('category'); // named pages if (name && this.options.trackNamedPages) { this.track(page.track(name)); } // categorized pages if (category && this.options.trackCategorizedPages) { this.track(page.track(category)); } }; /** * Trait aliases. * * http://docs.trak.io/properties.html#special */ var traitAliases = { avatar: 'avatar_url', firstName: 'first_name', lastName: 'last_name' }; /** * Identify. * * @param {Identify} identify */ Trakio.prototype.identify = function(identify){ var traits = identify.traits(traitAliases); var id = identify.userId(); if (id) { window.trak.io.identify(id, traits); } else { window.trak.io.identify(traits); } }; /** * Group. * * @param {String} id (optional) * @param {Object} properties (optional) * @param {Object} options (optional) * * TODO: add group * TODO: add `trait.company/organization` from trak.io docs http://docs.trak.io/properties.html#special */ /** * Track. * * @param {Track} track */ Trakio.prototype.track = function(track){ var properties = track.properties(); var channel = track.proxy('properties.channel'); if (channel) { delete properties.channel; window.trak.io.track(track.event(), channel, properties); } else { window.trak.io.track(track.event(), properties); } }; /** * Alias. * * @param {Alias} alias */ Trakio.prototype.alias = function(alias){ if (!window.trak.io.distinct_id) return; var from = alias.from(); var to = alias.to(); if (to === window.trak.io.distinct_id()) return; if (from) { window.trak.io.alias(from, to); } else { window.trak.io.alias(to); } }; }, {"analytics.js-integration":89,"alias":163,"clone":96}], 81: [function(require, module, exports) { /** * Module dependencies. */ var integration = require('analytics.js-integration'); var each = require('each'); /** * HOP. */ var has = Object.prototype.hasOwnProperty; /** * Expose `TwitterAds`. */ var TwitterAds = module.exports = integration('Twitter Ads') .option('page', '') .tag('<img src="//analytics.twitter.com/i/adsct?txn_id={{ pixelId }}&p_id=Twitter"/>') .mapping('events'); /** * Initialize. * * @param {Object} page */ TwitterAds.prototype.initialize = function(){ this.ready(); }; /** * Page. * * @param {Page} page */ TwitterAds.prototype.page = function(page){ if (this.options.page) { this.load({ pixelId: this.options.page }); } }; /** * Track. * * @param {Track} track */ TwitterAds.prototype.track = function(track){ var events = this.events(track.event()); var self = this; each(events, function(pixelId){ self.load({ pixelId: pixelId }); }); }; }, {"analytics.js-integration":89,"each":4}], 82: [function(require, module, exports) { /** * Module dependencies. */ var integration = require('analytics.js-integration'); var Identify = require('facade').Identify; var clone = require('clone'); /** * Expose Userlike integration. */ var Userlike = module.exports = integration('Userlike') .assumesPageview() .global('userlikeConfig') .global('userlikeData') .option('secretKey', '') .option('listen', false) .tag('<script src="//userlike-cdn-widgets.s3-eu-west-1.amazonaws.com/{{ secretKey }}.js">'); /** * The context for this integration. */ var integration = { name: 'userlike', version: '1.0.0' }; /** * Initialize. * * @param {Object} page */ Userlike.prototype.initialize = function(page){ var self = this; var user = this.analytics.user(); var identify = new Identify({ userId: user.id(), traits: user.traits() }); segment_base_info = clone(this.options); segment_base_info.visitor = { name: identify.name(), email: identify.email() }; if (!window.userlikeData) window.userlikeData = { custom: {} }; window.userlikeData.custom.segmentio = segment_base_info; this.load(function(){ if (self.options.listen) self.attachListeners(); self.ready(); }); }; /** * Loaded? * * @return {Boolean} */ Userlike.prototype.loaded = function(){ return !! (window.userlikeConfig && window.userlikeData); }; /** * Listen for chat events. * * TODO: As of 4/17/2015, Userlike doesn't give access to the message body in events. * Revisit this/send it when they do. * */ Userlike.prototype.attachListeners = function(){ var self = this; window.userlikeTrackingEvent = function(eventName, globalCtx, sessionCtx){ if (eventName === 'chat_started') { self.analytics.track( 'Live Chat Conversation Started', { agentId: sessionCtx.operator_id, agentName: sessionCtx.operator_name }, { context: { integration: integration } }); } if (eventName === 'message_operator_terminating') { self.analytics.track( 'Live Chat Message Sent', { agentId: sessionCtx.operator_id, agentName: sessionCtx.operator_name }, { context: { integration: integration } }); } if (eventName === 'message_client_terminating') { self.analytics.track( 'Live Chat Message Received', { agentId: sessionCtx.operator_id, agentName: sessionCtx.operator_name }, { context: { integration: integration } }); } if (eventName === 'chat_quit') { self.analytics.track( 'Live Chat Conversation Ended', { agentId: sessionCtx.operator_id, agentName: sessionCtx.operator_name }, { context: { integration: integration } }); } }; }; }, {"analytics.js-integration":89,"facade":133,"clone":96}], 83: [function(require, module, exports) { /** * Module dependencies. */ var integration = require('analytics.js-integration'); var push = require('global-queue')('UserVoice'); var convertDates = require('convert-dates'); var unix = require('to-unix-timestamp'); var alias = require('alias'); var clone = require('clone'); /** * Expose `UserVoice` integration. */ var UserVoice = module.exports = integration('UserVoice') .assumesPageview() .global('UserVoice') .global('showClassicWidget') .option('apiKey', '') .option('classic', false) .option('forumId', null) .option('showWidget', true) .option('mode', 'contact') .option('accentColor', '#448dd6') .option('screenshotEnabled', true) .option('smartvote', true) .option('trigger', null) .option('triggerPosition', 'bottom-right') .option('triggerColor', '#ffffff') .option('triggerBackgroundColor', 'rgba(46, 49, 51, 0.6)') // BACKWARDS COMPATIBILITY: classic options .option('classicMode', 'full') .option('primaryColor', '#cc6d00') .option('linkColor', '#007dbf') .option('defaultMode', 'support') .option('tabLabel', 'Feedback & Support') .option('tabColor', '#cc6d00') .option('tabPosition', 'middle-right') .option('tabInverted', false) .option('customTicketFields', {}) .tag('<script src="//widget.uservoice.com/{{ apiKey }}.js">'); /** * When in "classic" mode, on `construct` swap all of the method to point to * their classic counterparts. */ UserVoice.on('construct', function(integration){ if (!integration.options.classic) return; integration.group = undefined; integration.identify = integration.identifyClassic; integration.initialize = integration.initializeClassic; }); /** * Initialize. * * @param {Object} page */ UserVoice.prototype.initialize = function(page){ var options = this.options; var opts = formatOptions(options); push('set', opts); push('autoprompt', {}); if (options.showWidget) { options.trigger ? push('addTrigger', options.trigger, opts) : push('addTrigger', opts); } this.load(this.ready); }; /** * Loaded? * * @return {Boolean} */ UserVoice.prototype.loaded = function(){ return !! (window.UserVoice && window.UserVoice.push !== Array.prototype.push); }; /** * Identify. * * @param {Identify} identify */ UserVoice.prototype.identify = function(identify){ var traits = identify.traits({ created: 'created_at' }); traits = convertDates(traits, unix); push('identify', traits); }; /** * Group. * * @param {Group} group */ UserVoice.prototype.group = function(group){ var traits = group.traits({ created: 'created_at' }); traits = convertDates(traits, unix); push('identify', { account: traits }); }; /** * Initialize (classic). * * @param {Object} options * @param {Function} ready */ UserVoice.prototype.initializeClassic = function(){ var options = this.options; window.showClassicWidget = showClassicWidget; // part of public api if (options.showWidget) showClassicWidget('showTab', formatClassicOptions(options)); this.load(this.ready); }; /** * Identify (classic). * * @param {Identify} identify */ UserVoice.prototype.identifyClassic = function(identify){ push('setCustomFields', identify.traits()); }; /** * Format the options for UserVoice. * * @param {Object} options * @return {Object} */ function formatOptions(options){ return alias(options, { forumId: 'forum_id', accentColor: 'accent_color', smartvote: 'smartvote_enabled', triggerColor: 'trigger_color', triggerBackgroundColor: 'trigger_background_color', triggerPosition: 'trigger_position', screenshotEnabled: 'screenshot_enabled', customTicketFields: 'ticket_custom_fields' }); } /** * Format the classic options for UserVoice. * * @param {Object} options * @return {Object} */ function formatClassicOptions(options){ return alias(options, { forumId: 'forum_id', classicMode: 'mode', primaryColor: 'primary_color', tabPosition: 'tab_position', tabColor: 'tab_color', linkColor: 'link_color', defaultMode: 'default_mode', tabLabel: 'tab_label', tabInverted: 'tab_inverted' }); } /** * Show the classic version of the UserVoice widget. This method is usually part * of UserVoice classic's public API. * * @param {String} type ('showTab' or 'showLightbox') * @param {Object} options (optional) */ function showClassicWidget(type, options){ type = type || 'showLightbox'; push(type, 'classic_widget', options); } }, {"analytics.js-integration":89,"global-queue":160,"convert-dates":164,"to-unix-timestamp":194,"alias":163,"clone":96}], 194: [function(require, module, exports) { /** * Expose `toUnixTimestamp`. */ module.exports = toUnixTimestamp; /** * Convert a `date` into a Unix timestamp. * * @param {Date} * @return {Number} */ function toUnixTimestamp (date) { return Math.floor(date.getTime() / 1000); } }, {}], 84: [function(require, module, exports) { /** * Module dependencies. */ var integration = require('analytics.js-integration'); var push = require('global-queue')('_veroq'); var cookie = require('component/cookie'); var objCase = require('obj-case'); /** * Expose `Vero` integration. */ var Vero = module.exports = integration('Vero') .global('_veroq') .option('apiKey', '') .tag('<script src="//d3qxef4rp70elm.cloudfront.net/m.js">'); /** * Initialize. * * https://github.com/getvero/vero-api/blob/master/sections/js.md * * @param {Object} page */ Vero.prototype.initialize = function(page){ // clear default cookie so vero parses correctly. // this is for the tests. // basically, they have window.addEventListener('unload') // which then saves their "command_store", which is an array. // so we just want to create that initially so we can reload the tests. if (!cookie('__veroc4')) cookie('__veroc4', '[]'); push('init', { api_key: this.options.apiKey }); this.load(this.ready); }; /** * Loaded? * * @return {Boolean} */ Vero.prototype.loaded = function(){ return !! (window._veroq && window._veroq.push !== Array.prototype.push); }; /** * Page. * * https://www.getvero.com/knowledge-base#/questions/71768-Does-Vero-track-pageviews * * @param {Page} page */ Vero.prototype.page = function(page){ push('trackPageview'); }; /** * Identify. * * https://github.com/getvero/vero-api/blob/master/sections/js.md#user-identification * * @param {Identify} identify */ Vero.prototype.identify = function(identify){ var traits = identify.traits(); var email = identify.email(); var id = identify.userId(); if (!id || !email) return; // both required push('user', traits); }; /** * Track. * * https://github.com/getvero/vero-api/blob/master/sections/js.md#tracking-events * * @param {Track} track */ Vero.prototype.track = function(track){ var regex = /[uU]nsubscribe/; if (track.event().match(regex)) { push('unsubscribe', { id: track.properties().id }); } else { push('track', track.event(), track.properties()); } }; Vero.prototype.alias = function(alias){ var to = alias.to(); if (alias.from()) { push('reidentify', to, alias.from()); } else { push('reidentify', to); } }; }, {"analytics.js-integration":89,"global-queue":160,"component/cookie":184,"obj-case":93}], 85: [function(require, module, exports) { /** * Module dependencies. */ var integration = require('analytics.js-integration'); var tick = require('next-tick'); var each = require('each'); /** * Expose `VWO` integration. */ var VWO = module.exports = integration('Visual Website Optimizer') .option('replay', true) .option('listen', false); /** * The context for this integration. */ var integration = { name: 'visual-website-optimizer', version: '1.0.0' }; /** * Initialize. * * http://v2.visualwebsiteoptimizer.com/tools/get_tracking_code.php */ VWO.prototype.initialize = function(){ var self = this; if (this.options.replay) { tick(function(){ self.replay(); }); } if (this.options.listen) { tick(function(){ self.roots(); }); } this.ready(); }; /** * Completed Purchase. * * https://vwo.com/knowledge/vwo-revenue-tracking-goal */ VWO.prototype.completedOrder = function(track){ var total = track.total() || track.revenue() || 0; enqueue(function(){ _vis_opt_revenue_conversion(total); }); }; /** * Replay the experiments the user has seen as traits to all other integrations. * Wait for the next tick to replay so that the `analytics` object and all of * the integrations are fully initialized. */ VWO.prototype.replay = function(){ var analytics = this.analytics; experiments(function(err, traits){ if (traits) analytics.identify(traits); }); }; /** * Replay the experiments the user has seen as traits to all other integrations. * Wait for the next tick to replay so that the `analytics` object and all of * the integrations are fully initialized. */ VWO.prototype.roots = function(){ var analytics = this.analytics; rootExperiments(function(err, data){ each(data, function(experimentId, variationName){ analytics.track( 'Experiment Viewed', { experimentId: experimentId, variationName: variationName }, { context: { integration: integration }} ); }); }); }; /** * Get dictionary of experiment keys and variations. * * http://visualwebsiteoptimizer.com/knowledge/integration-of-vwo-with-kissmetrics/ * * @param {Function} fn * @return {Object} */ function rootExperiments(fn){ enqueue(function(){ var data = {}; var experimentIds = window._vwo_exp_ids; if (!experimentIds) return fn(); each(experimentIds, function(experimentId){ var variationName = variation(experimentId); if (variationName) data[experimentId] = variationName; }); fn(null, data); }); } /** * Get dictionary of experiment keys and variations. * * http://visualwebsiteoptimizer.com/knowledge/integration-of-vwo-with-kissmetrics/ * * @param {Function} fn * @return {Object} */ function experiments(fn){ enqueue(function(){ var data = {}; var ids = window._vwo_exp_ids; if (!ids) return fn(); each(ids, function(id){ var name = variation(id); if (name) data['Experiment: ' + id] = name; }); fn(null, data); }); } /** * Add a `fn` to the VWO queue, creating one if it doesn't exist. * * @param {Function} fn */ function enqueue(fn){ window._vis_opt_queue = window._vis_opt_queue || []; window._vis_opt_queue.push(fn); } /** * Get the chosen variation's name from an experiment `id`. * * http://visualwebsiteoptimizer.com/knowledge/integration-of-vwo-with-kissmetrics/ * * @param {String} id * @return {String} */ function variation(id){ var experiments = window._vwo_exp; if (!experiments) return null; var experiment = experiments[id]; var variationId = experiment.combination_chosen; return variationId ? experiment.comb_n[variationId] : null; } }, {"analytics.js-integration":89,"next-tick":104,"each":4}], 86: [function(require, module, exports) { /** * Module dependencies. */ var integration = require('analytics.js-integration'); var useHttps = require('use-https'); /** * Expose `WebEngage` integration. */ var WebEngage = module.exports = integration('WebEngage') .assumesPageview() .global('_weq') .global('webengage') .option('widgetVersion', '4.0') .option('licenseCode', '') .tag('http', '<script src="http://cdn.widgets.webengage.com/js/widget/webengage-min-v-4.0.js">') .tag('https', '<script src="https://ssl.widgets.webengage.com/js/widget/webengage-min-v-4.0.js">'); /** * Initialize. * * @param {Object} page */ WebEngage.prototype.initialize = function(page){ var _weq = window._weq = window._weq || {}; _weq['webengage.licenseCode'] = this.options.licenseCode; _weq['webengage.widgetVersion'] = this.options.widgetVersion; var name = useHttps() ? 'https' : 'http'; this.load(name, this.ready); }; /** * Loaded? * * @return {Boolean} */ WebEngage.prototype.loaded = function(){ return !! window.webengage; }; }, {"analytics.js-integration":89,"use-https":91}], 87: [function(require, module, exports) { /** * Module dependencies. */ var integration = require('analytics.js-integration'); var snake = require('to-snake-case'); var isEmail = require('is-email'); var extend = require('extend'); var each = require('each'); var type = require('type'); /** * Expose `Woopra` integration. */ var Woopra = module.exports = integration('Woopra') .global('woopra') .option('domain', '') .option('cookieName', 'wooTracker') .option('cookieDomain', null) .option('cookiePath', '/') .option('ping', true) .option('pingInterval', 12000) .option('idleTimeout', 300000) .option('downloadTracking', true) .option('outgoingTracking', true) .option('outgoingIgnoreSubdomain', true) .option('downloadPause', 200) .option('outgoingPause', 400) .option('ignoreQueryUrl', true) .option('hideCampaign', false) .tag('<script src="//static.woopra.com/js/w.js">'); /** * Initialize. * * http://www.woopra.com/docs/setup/javascript-tracking/ * * @param {Object} page */ Woopra.prototype.initialize = function(page){ (function(){var i, s, z, w = window, d = document, a = arguments, q = 'script', f = ['config', 'track', 'identify', 'visit', 'push', 'call'], c = function(){var i, self = this; self._e = []; for (i = 0; i < f.length; i++){(function(f){self[f] = function(){self._e.push([f].concat(Array.prototype.slice.call(arguments, 0))); return self; }; })(f[i]); } }; w._w = w._w || {}; for (i = 0; i < a.length; i++){ w._w[a[i]] = w[a[i]] = w[a[i]] || new c(); } })('woopra'); this.load(this.ready); each(this.options, function(key, value){ key = snake(key); if (null == value) return; if ('' === value) return; window.woopra.config(key, value); }); }; /** * Loaded? * * @return {Boolean} */ Woopra.prototype.loaded = function(){ return !! (window.woopra && window.woopra.loaded); }; /** * Page. * * @param {String} category (optional) */ Woopra.prototype.page = function(page){ var props = page.properties(); var name = page.fullName(); if (name) props.title = name; window.woopra.track('pv', props); }; /** * Identify. * * @param {Identify} identify */ Woopra.prototype.identify = function(identify){ var traits = identify.traits(); if (identify.name()) traits.name = identify.name(); window.woopra.identify(traits).push(); // `push` sends it off async }; /** * Track. * * @param {Track} track */ Woopra.prototype.track = function(track){ window.woopra.track(track.event(), track.properties()); }; }, {"analytics.js-integration":89,"to-snake-case":90,"is-email":155,"extend":131,"each":4,"type":114}], 88: [function(require, module, exports) { /** * Module dependencies. */ var integration = require('analytics.js-integration'); var tick = require('next-tick'); var bind = require('bind'); var when = require('when'); /** * Expose `Yandex` integration. */ var Yandex = module.exports = integration('Yandex Metrica') .assumesPageview() .global('yandex_metrika_callbacks') .global('Ya') .option('counterId', null) .option('clickmap', false) .option('webvisor', false) .tag('<script src="//mc.yandex.ru/metrika/watch.js">'); /** * Initialize. * * http://api.yandex.com/metrika/ * https://metrica.yandex.com/22522351?step=2#tab=code * * @param {Object} page */ Yandex.prototype.initialize = function(page){ var id = this.options.counterId; var clickmap = this.options.clickmap; var webvisor = this.options.webvisor; push(function(){ window['yaCounter' + id] = new window.Ya.Metrika({ id: id, clickmap: clickmap, webvisor: webvisor }); }); var loaded = bind(this, this.loaded); var ready = this.ready; this.load(function(){ when(loaded, function(){ tick(ready); }); }); }; /** * Loaded? * * @return {Boolean} */ Yandex.prototype.loaded = function(){ return !! (window.Ya && window.Ya.Metrika); }; /** * Push a new callback on the global Yandex queue. * * @param {Function} callback */ function push(callback){ window.yandex_metrika_callbacks = window.yandex_metrika_callbacks || []; window.yandex_metrika_callbacks.push(callback); } }, {"analytics.js-integration":89,"next-tick":104,"bind":102,"when":132}], 3: [function(require, module, exports) { var _analytics = window.analytics; var after = require('after'); var bind = require('bind'); var callback = require('callback'); var clone = require('clone'); var cookie = require('./cookie'); var debug = require('debug'); var defaults = require('defaults'); var each = require('each'); var Emitter = require('emitter'); var group = require('./group'); var is = require('is'); var isEmail = require('is-email'); var isMeta = require('is-meta'); var newDate = require('new-date'); var on = require('event').bind; var pageDefaults = require('./pageDefaults'); var pick = require('pick'); var prevent = require('prevent'); var querystring = require('querystring'); var normalize = require('./normalize'); var size = require('object').length; var keys = require('object').keys; var memory = require('./memory'); var store = require('./store'); var user = require('./user'); var Facade = require('facade'); var Identify = Facade.Identify; var Group = Facade.Group; var Alias = Facade.Alias; var Track = Facade.Track; var Page = Facade.Page; /** * Expose `Analytics`. */ exports = module.exports = Analytics; /** * Expose storage. */ exports.cookie = cookie; exports.store = store; exports.memory = memory; /** * Initialize a new `Analytics` instance. */ function Analytics () { this._options({}); this.Integrations = {}; this._integrations = {}; this._readied = false; this._timeout = 300; this._user = user; // BACKWARDS COMPATIBILITY this.log = debug('analytics.js'); bind.all(this); var self = this; this.on('initialize', function(settings, options){ if (options.initialPageview) self.page(); self._parseQuery(); }); } /** * Event Emitter. */ Emitter(Analytics.prototype); /** * Use a `plugin`. * * @param {Function} plugin * @return {Analytics} */ Analytics.prototype.use = function (plugin) { plugin(this); return this; }; /** * Define a new `Integration`. * * @param {Function} Integration * @return {Analytics} */ Analytics.prototype.addIntegration = function (Integration) { var name = Integration.prototype.name; if (!name) throw new TypeError('attempted to add an invalid integration'); this.Integrations[name] = Integration; return this; }; /** * Initialize with the given integration `settings` and `options`. Aliased to * `init` for convenience. * * @param {Object} settings * @param {Object} options (optional) * @return {Analytics} */ Analytics.prototype.init = Analytics.prototype.initialize = function (settings, options) { settings = settings || {}; options = options || {}; this._options(options); this._readied = false; // clean unknown integrations from settings var self = this; each(settings, function (name) { var Integration = self.Integrations[name]; if (!Integration) delete settings[name]; }); // add integrations each(settings, function (name, opts) { var Integration = self.Integrations[name]; var integration = new Integration(clone(opts)); self.log('initialize %o - %o', name, opts); self.add(integration); }); var integrations = this._integrations; // load user now that options are set user.load(); group.load(); // make ready callback var ready = after(size(integrations), function () { self._readied = true; self.emit('ready'); }); // initialize integrations, passing ready each(integrations, function (name, integration) { if (options.initialPageview && integration.options.initialPageview === false) { integration.page = after(2, integration.page); } integration.analytics = self; integration.once('ready', ready); integration.initialize(); }); // backwards compat with angular plugin. // TODO: remove this.initialized = true; this.emit('initialize', settings, options); return this; }; /** * Set the user's `id`. * * @param {Mixed} id */ Analytics.prototype.setAnonymousId = function(id){ this.user().anonymousId(id); return this; }; /** * Add an integration. * * @param {Integration} integration */ Analytics.prototype.add = function(integration){ this._integrations[integration.name] = integration; return this; }; /** * Identify a user by optional `id` and `traits`. * * @param {String} id (optional) * @param {Object} traits (optional) * @param {Object} options (optional) * @param {Function} fn (optional) * @return {Analytics} */ Analytics.prototype.identify = function (id, traits, options, fn) { if (is.fn(options)) fn = options, options = null; if (is.fn(traits)) fn = traits, options = null, traits = null; if (is.object(id)) options = traits, traits = id, id = user.id(); // clone traits before we manipulate so we don't do anything uncouth, and take // from `user` so that we carryover anonymous traits user.identify(id, traits); var msg = this.normalize({ options: options, traits: user.traits(), userId: user.id(), }); this._invoke('identify', new Identify(msg)); // emit this.emit('identify', id, traits, options); this._callback(fn); return this; }; /** * Return the current user. * * @return {Object} */ Analytics.prototype.user = function () { return user; }; /** * Identify a group by optional `id` and `traits`. Or, if no arguments are * supplied, return the current group. * * @param {String} id (optional) * @param {Object} traits (optional) * @param {Object} options (optional) * @param {Function} fn (optional) * @return {Analytics or Object} */ Analytics.prototype.group = function (id, traits, options, fn) { if (0 === arguments.length) return group; if (is.fn(options)) fn = options, options = null; if (is.fn(traits)) fn = traits, options = null, traits = null; if (is.object(id)) options = traits, traits = id, id = group.id(); // grab from group again to make sure we're taking from the source group.identify(id, traits); var msg = this.normalize({ options: options, traits: group.traits(), groupId: group.id() }); this._invoke('group', new Group(msg)); this.emit('group', id, traits, options); this._callback(fn); return this; }; /** * Track an `event` that a user has triggered with optional `properties`. * * @param {String} event * @param {Object} properties (optional) * @param {Object} options (optional) * @param {Function} fn (optional) * @return {Analytics} */ Analytics.prototype.track = function (event, properties, options, fn) { if (is.fn(options)) fn = options, options = null; if (is.fn(properties)) fn = properties, options = null, properties = null; // figure out if the event is archived. var plan = this.options.plan || {}; var events = plan.track || {}; // normalize var msg = this.normalize({ properties: properties, options: options, event: event }); // plan. if (plan = events[event]) { this.log('plan %o - %o', event, plan); if (false == plan.enabled) return this._callback(fn); defaults(msg.integrations, plan.integrations || {}); } this._invoke('track', new Track(msg)); this.emit('track', event, properties, options); this._callback(fn); return this; }; /** * Helper method to track an outbound link that would normally navigate away * from the page before the analytics calls were sent. * * BACKWARDS COMPATIBILITY: aliased to `trackClick`. * * @param {Element or Array} links * @param {String or Function} event * @param {Object or Function} properties (optional) * @return {Analytics} */ Analytics.prototype.trackClick = Analytics.prototype.trackLink = function (links, event, properties) { if (!links) return this; if (is.element(links)) links = [links]; // always arrays, handles jquery var self = this; each(links, function (el) { if (!is.element(el)) throw new TypeError('Must pass HTMLElement to `analytics.trackLink`.'); on(el, 'click', function (e) { var ev = is.fn(event) ? event(el) : event; var props = is.fn(properties) ? properties(el) : properties; var href = el.getAttribute('href') || el.getAttributeNS('http://www.w3.org/1999/xlink', 'href') || el.getAttribute('xlink:href'); self.track(ev, props); if (href && el.target !== '_blank' && !isMeta(e)) { prevent(e); self._callback(function () { window.location.href = href; }); } }); }); return this; }; /** * Helper method to track an outbound form that would normally navigate away * from the page before the analytics calls were sent. * * BACKWARDS COMPATIBILITY: aliased to `trackSubmit`. * * @param {Element or Array} forms * @param {String or Function} event * @param {Object or Function} properties (optional) * @return {Analytics} */ Analytics.prototype.trackSubmit = Analytics.prototype.trackForm = function (forms, event, properties) { if (!forms) return this; if (is.element(forms)) forms = [forms]; // always arrays, handles jquery var self = this; each(forms, function (el) { if (!is.element(el)) throw new TypeError('Must pass HTMLElement to `analytics.trackForm`.'); function handler (e) { prevent(e); var ev = is.fn(event) ? event(el) : event; var props = is.fn(properties) ? properties(el) : properties; self.track(ev, props); self._callback(function () { el.submit(); }); } // support the events happening through jQuery or Zepto instead of through // the normal DOM API, since `el.submit` doesn't bubble up events... var $ = window.jQuery || window.Zepto; if ($) { $(el).submit(handler); } else { on(el, 'submit', handler); } }); return this; }; /** * Trigger a pageview, labeling the current page with an optional `category`, * `name` and `properties`. * * @param {String} category (optional) * @param {String} name (optional) * @param {Object or String} properties (or path) (optional) * @param {Object} options (optional) * @param {Function} fn (optional) * @return {Analytics} */ Analytics.prototype.page = function (category, name, properties, options, fn) { if (is.fn(options)) fn = options, options = null; if (is.fn(properties)) fn = properties, options = properties = null; if (is.fn(name)) fn = name, options = properties = name = null; if (is.object(category)) options = name, properties = category, name = category = null; if (is.object(name)) options = properties, properties = name, name = null; if (is.string(category) && !is.string(name)) name = category, category = null; properties = clone(properties) || {}; if (name) properties.name = name; if (category) properties.category = category; // Ensure properties has baseline spec properties. // TODO: Eventually move these entirely to `options.context.page` var defs = pageDefaults(); defaults(properties, defs); // Mirror user overrides to `options.context.page` (but exclude custom properties) // (Any page defaults get applied in `this.normalize` for consistency.) // Weird, yeah--moving special props to `context.page` will fix this in the long term. var overrides = pick(keys(defs), properties); if (!is.empty(overrides)) { options = options || {}; options.context = options.context || {}; options.context.page = overrides; } var msg = this.normalize({ properties: properties, category: category, options: options, name: name }); this._invoke('page', new Page(msg)); this.emit('page', category, name, properties, options); this._callback(fn); return this; }; /** * BACKWARDS COMPATIBILITY: convert an old `pageview` to a `page` call. * * @param {String} url (optional) * @param {Object} options (optional) * @return {Analytics} * @api private */ Analytics.prototype.pageview = function (url, options) { var properties = {}; if (url) properties.path = url; this.page(properties); return this; }; /** * Merge two previously unassociated user identities. * * @param {String} to * @param {String} from (optional) * @param {Object} options (optional) * @param {Function} fn (optional) * @return {Analytics} */ Analytics.prototype.alias = function (to, from, options, fn) { if (is.fn(options)) fn = options, options = null; if (is.fn(from)) fn = from, options = null, from = null; if (is.object(from)) options = from, from = null; var msg = this.normalize({ options: options, previousId: from, userId: to }); this._invoke('alias', new Alias(msg)); this.emit('alias', to, from, options); this._callback(fn); return this; }; /** * Register a `fn` to be fired when all the analytics services are ready. * * @param {Function} fn * @return {Analytics} */ Analytics.prototype.ready = function (fn) { if (!is.fn(fn)) return this; this._readied ? callback.async(fn) : this.once('ready', fn); return this; }; /** * Set the `timeout` (in milliseconds) used for callbacks. * * @param {Number} timeout */ Analytics.prototype.timeout = function (timeout) { this._timeout = timeout; }; /** * Enable or disable debug. * * @param {String or Boolean} str */ Analytics.prototype.debug = function(str){ if (0 == arguments.length || str) { debug.enable('analytics:' + (str || '*')); } else { debug.disable(); } }; /** * Apply options. * * @param {Object} options * @return {Analytics} * @api private */ Analytics.prototype._options = function (options) { options = options || {}; this.options = options; cookie.options(options.cookie); store.options(options.localStorage); user.options(options.user); group.options(options.group); return this; }; /** * Callback a `fn` after our defined timeout period. * * @param {Function} fn * @return {Analytics} * @api private */ Analytics.prototype._callback = function (fn) { callback.async(fn, this._timeout); return this; }; /** * Call `method` with `facade` on all enabled integrations. * * @param {String} method * @param {Facade} facade * @return {Analytics} * @api private */ Analytics.prototype._invoke = function (method, facade) { var options = facade.options(); this.emit('invoke', facade); each(this._integrations, function (name, integration) { if (!facade.enabled(name)) return; integration.invoke.call(integration, method, facade); }); return this; }; /** * Push `args`. * * @param {Array} args * @api private */ Analytics.prototype.push = function(args){ var method = args.shift(); if (!this[method]) return; this[method].apply(this, args); }; /** * Reset group and user traits and id's. * * @api public */ Analytics.prototype.reset = function(){ this.user().logout(); this.group().logout(); }; /** * Parse the query string for callable methods. * * @return {Analytics} * @api private */ Analytics.prototype._parseQuery = function () { // Identify and track any `ajs_uid` and `ajs_event` parameters in the URL. var q = querystring.parse(window.location.search); if (q.ajs_uid) this.identify(q.ajs_uid); if (q.ajs_event) this.track(q.ajs_event); if (q.ajs_aid) user.anonymousId(q.ajs_aid); return this; }; /** * Normalize the given `msg`. * * @param {Object} msg * @return {Object} */ Analytics.prototype.normalize = function(msg){ msg = normalize(msg, keys(this._integrations)); if (msg.anonymousId) user.anonymousId(msg.anonymousId); msg.anonymousId = user.anonymousId(); // Ensure all outgoing requests include page data in their contexts. msg.context.page = defaults(msg.context.page || {}, pageDefaults()); return msg; }; /** * No conflict support. */ Analytics.prototype.noConflict = function(){ window.analytics = _analytics; return this; }; }, {"after":112,"bind":195,"callback":95,"clone":96,"./cookie":196,"debug":191,"defaults":98,"each":4,"emitter":111,"./group":197,"is":92,"is-email":155,"is-meta":198,"new-date":147,"event":199,"./pageDefaults":200,"pick":201,"prevent":202,"querystring":203,"./normalize":204,"object":171,"./memory":205,"./store":206,"./user":207,"facade":133}], 195: [function(require, module, exports) { try { var bind = require('bind'); } catch (e) { var bind = require('bind-component'); } var bindAll = require('bind-all'); /** * Expose `bind`. */ module.exports = exports = bind; /** * Expose `bindAll`. */ exports.all = bindAll; /** * Expose `bindMethods`. */ exports.methods = bindMethods; /** * Bind `methods` on `obj` to always be called with the `obj` as context. * * @param {Object} obj * @param {String} methods... */ function bindMethods (obj, methods) { methods = [].slice.call(arguments, 1); for (var i = 0, method; method = methods[i]; i++) { obj[method] = bind(obj, obj[method]); } return obj; } }, {"bind":102,"bind-all":103}], 196: [function(require, module, exports) { var debug = require('debug')('analytics.js:cookie'); var bind = require('bind'); var cookie = require('cookie'); var clone = require('clone'); var defaults = require('defaults'); var json = require('json'); var topDomain = require('top-domain'); /** * Initialize a new `Cookie` with `options`. * * @param {Object} options */ function Cookie (options) { this.options(options); } /** * Get or set the cookie options. * * @param {Object} options * @field {Number} maxage (1 year) * @field {String} domain * @field {String} path * @field {Boolean} secure */ Cookie.prototype.options = function (options) { if (arguments.length === 0) return this._options; options = options || {}; var domain = '.' + topDomain(window.location.href); if ('.' == domain) domain = null; this._options = defaults(options, { maxage: 31536000000, // default to a year path: '/', domain: domain }); // http://curl.haxx.se/rfc/cookie_spec.html // https://publicsuffix.org/list/effective_tld_names.dat // // try setting a dummy cookie with the options // if the cookie isn't set, it probably means // that the domain is on the public suffix list // like myapp.herokuapp.com or localhost / ip. this.set('ajs:test', true); if (!this.get('ajs:test')) { debug('fallback to domain=null'); this._options.domain = null; } this.remove('ajs:test'); }; /** * Set a `key` and `value` in our cookie. * * @param {String} key * @param {Object} value * @return {Boolean} saved */ Cookie.prototype.set = function (key, value) { try { value = json.stringify(value); cookie(key, value, clone(this._options)); return true; } catch (e) { return false; } }; /** * Get a value from our cookie by `key`. * * @param {String} key * @return {Object} value */ Cookie.prototype.get = function (key) { try { var value = cookie(key); value = value ? json.parse(value) : null; return value; } catch (e) { return null; } }; /** * Remove a value from our cookie by `key`. * * @param {String} key * @return {Boolean} removed */ Cookie.prototype.remove = function (key) { try { cookie(key, null, clone(this._options)); return true; } catch (e) { return false; } }; /** * Expose the cookie singleton. */ module.exports = bind.all(new Cookie()); /** * Expose the `Cookie` constructor. */ module.exports.Cookie = Cookie; }, {"debug":191,"bind":195,"cookie":184,"clone":96,"defaults":98,"json":165,"top-domain":208}], 208: [function(require, module, exports) { /** * Module dependencies. */ var parse = require('url').parse; var cookie = require('cookie'); /** * Expose `domain` */ exports = module.exports = domain; /** * Expose `cookie` for testing. */ exports.cookie = cookie; /** * Get the top domain. * * The function constructs the levels of domain * and attempts to set a global cookie on each one * when it succeeds it returns the top level domain. * * The method returns an empty string when the hostname * is an ip or `localhost`. * * Example levels: * * domain.levels('http://www.google.co.uk'); * // => ["co.uk", "google.co.uk", "www.google.co.uk"] * * Example: * * domain('http://localhost:3000/baz'); * // => '' * domain('http://dev:3000/baz'); * // => '' * domain('http://127.0.0.1:3000/baz'); * // => '' * domain('http://segment.io/baz'); * // => 'segment.io' * * @param {String} url * @return {String} * @api public */ function domain(url){ var cookie = exports.cookie; var levels = exports.levels(url); // Lookup the real top level one. for (var i = 0; i < levels.length; ++i) { var cname = '__tld__'; var domain = levels[i]; var opts = { domain: '.' + domain }; cookie(cname, 1, opts); if (cookie(cname)) { cookie(cname, null, opts); return domain } } return ''; }; /** * Levels returns all levels of the given url. * * @param {String} url * @return {Array} * @api public */ domain.levels = function(url){ var host = parse(url).hostname; var parts = host.split('.'); var last = parts[parts.length-1]; var levels = []; // Ip address. if (4 == parts.length && parseInt(last, 10) == last) { return levels; } // Localhost. if (1 >= parts.length) { return levels; } // Create levels. for (var i = parts.length-2; 0 <= i; --i) { levels.push(parts.slice(i).join('.')); } return levels; }; }, {"url":128,"cookie":209}], 209: [function(require, module, exports) { /** * Module dependencies. */ var debug = require('debug')('cookie'); /** * Set or get cookie `name` with `value` and `options` object. * * @param {String} name * @param {String} value * @param {Object} options * @return {Mixed} * @api public */ module.exports = function(name, value, options){ switch (arguments.length) { case 3: case 2: return set(name, value, options); case 1: return get(name); default: return all(); } }; /** * Set cookie `name` to `value`. * * @param {String} name * @param {String} value * @param {Object} options * @api private */ function set(name, value, options) { options = options || {}; var str = encode(name) + '=' + encode(value); if (null == value) options.maxage = -1; if (options.maxage) { options.expires = new Date(+new Date + options.maxage); } if (options.path) str += '; path=' + options.path; if (options.domain) str += '; domain=' + options.domain; if (options.expires) str += '; expires=' + options.expires.toUTCString(); if (options.secure) str += '; secure'; document.cookie = str; } /** * Return all cookies. * * @return {Object} * @api private */ function all() { var str; try { str = document.cookie; } catch (err) { if (typeof console !== 'undefined' && typeof console.error === 'function') { console.error(err.stack || err); } return {}; } return parse(str); } /** * Get cookie `name`. * * @param {String} name * @return {String} * @api private */ function get(name) { return all()[name]; } /** * Parse cookie `str`. * * @param {String} str * @return {Object} * @api private */ function parse(str) { var obj = {}; var pairs = str.split(/ *; */); var pair; if ('' == pairs[0]) return obj; for (var i = 0; i < pairs.length; ++i) { pair = pairs[i].split('='); obj[decode(pair[0])] = decode(pair[1]); } return obj; } /** * Encode. */ function encode(value){ try { return encodeURIComponent(value); } catch (e) { debug('error `encode(%o)` - %o', value, e) } } /** * Decode. */ function decode(value) { try { return decodeURIComponent(value); } catch (e) { debug('error `decode(%o)` - %o', value, e) } } }, {"debug":191}], 197: [function(require, module, exports) { var debug = require('debug')('analytics:group'); var Entity = require('./entity'); var inherit = require('inherit'); var bind = require('bind'); /** * Group defaults */ Group.defaults = { persist: true, cookie: { key: 'ajs_group_id' }, localStorage: { key: 'ajs_group_properties' } }; /** * Initialize a new `Group` with `options`. * * @param {Object} options */ function Group (options) { this.defaults = Group.defaults; this.debug = debug; Entity.call(this, options); } /** * Inherit `Entity` */ inherit(Group, Entity); /** * Expose the group singleton. */ module.exports = bind.all(new Group()); /** * Expose the `Group` constructor. */ module.exports.Group = Group; }, {"debug":191,"./entity":210,"inherit":211,"bind":195}], 210: [function(require, module, exports) { var debug = require('debug')('analytics:entity'); var traverse = require('isodate-traverse'); var defaults = require('defaults'); var memory = require('./memory'); var cookie = require('./cookie'); var store = require('./store'); var extend = require('extend'); var clone = require('clone'); /** * Expose `Entity` */ module.exports = Entity; /** * Initialize new `Entity` with `options`. * * @param {Object} options */ function Entity(options){ this.options(options); this.initialize(); } /** * Initialize picks the storage. * * Checks to see if cookies can be set * otherwise fallsback to localStorage. */ Entity.prototype.initialize = function(){ cookie.set('ajs:cookies', true); // cookies are enabled. if (cookie.get('ajs:cookies')) { cookie.remove('ajs:cookies'); this._storage = cookie; return; } // localStorage is enabled. if (store.enabled) { this._storage = store; return; } // fallback to memory storage. debug('warning using memory store both cookies and localStorage are disabled'); this._storage = memory; }; /** * Get the storage. */ Entity.prototype.storage = function(){ return this._storage; }; /** * Get or set storage `options`. * * @param {Object} options * @property {Object} cookie * @property {Object} localStorage * @property {Boolean} persist (default: `true`) */ Entity.prototype.options = function (options) { if (arguments.length === 0) return this._options; options || (options = {}); defaults(options, this.defaults || {}); this._options = options; }; /** * Get or set the entity's `id`. * * @param {String} id */ Entity.prototype.id = function (id) { switch (arguments.length) { case 0: return this._getId(); case 1: return this._setId(id); } }; /** * Get the entity's id. * * @return {String} */ Entity.prototype._getId = function () { var ret = this._options.persist ? this.storage().get(this._options.cookie.key) : this._id; return ret === undefined ? null : ret; }; /** * Set the entity's `id`. * * @param {String} id */ Entity.prototype._setId = function (id) { if (this._options.persist) { this.storage().set(this._options.cookie.key, id); } else { this._id = id; } }; /** * Get or set the entity's `traits`. * * BACKWARDS COMPATIBILITY: aliased to `properties` * * @param {Object} traits */ Entity.prototype.properties = Entity.prototype.traits = function (traits) { switch (arguments.length) { case 0: return this._getTraits(); case 1: return this._setTraits(traits); } }; /** * Get the entity's traits. Always convert ISO date strings into real dates, * since they aren't parsed back from local storage. * * @return {Object} */ Entity.prototype._getTraits = function () { var ret = this._options.persist ? store.get(this._options.localStorage.key) : this._traits; return ret ? traverse(clone(ret)) : {}; }; /** * Set the entity's `traits`. * * @param {Object} traits */ Entity.prototype._setTraits = function (traits) { traits || (traits = {}); if (this._options.persist) { store.set(this._options.localStorage.key, traits); } else { this._traits = traits; } }; /** * Identify the entity with an `id` and `traits`. If we it's the same entity, * extend the existing `traits` instead of overwriting. * * @param {String} id * @param {Object} traits */ Entity.prototype.identify = function (id, traits) { traits || (traits = {}); var current = this.id(); if (current === null || current === id) traits = extend(this.traits(), traits); if (id) this.id(id); this.debug('identify %o, %o', id, traits); this.traits(traits); this.save(); }; /** * Save the entity to local storage and the cookie. * * @return {Boolean} */ Entity.prototype.save = function () { if (!this._options.persist) return false; cookie.set(this._options.cookie.key, this.id()); store.set(this._options.localStorage.key, this.traits()); return true; }; /** * Log the entity out, reseting `id` and `traits` to defaults. */ Entity.prototype.logout = function () { this.id(null); this.traits({}); cookie.remove(this._options.cookie.key); store.remove(this._options.localStorage.key); }; /** * Reset all entity state, logging out and returning options to defaults. */ Entity.prototype.reset = function () { this.logout(); this.options({}); }; /** * Load saved entity `id` or `traits` from storage. */ Entity.prototype.load = function () { this.id(cookie.get(this._options.cookie.key)); this.traits(store.get(this._options.localStorage.key)); }; }, {"debug":191,"isodate-traverse":143,"defaults":98,"./memory":205,"./cookie":196,"./store":206,"extend":131,"clone":96}], 205: [function(require, module, exports) { /** * Module Dependencies. */ var clone = require('clone'); var bind = require('bind'); /** * HOP. */ var has = Object.prototype.hasOwnProperty; /** * Expose `Memory` */ module.exports = bind.all(new Memory); /** * Initialize `Memory` store */ function Memory(){ this.store = {}; } /** * Set a `key` and `value`. * * @param {String} key * @param {Mixed} value * @return {Boolean} */ Memory.prototype.set = function(key, value){ this.store[key] = clone(value); return true; }; /** * Get a `key`. * * @param {String} key */ Memory.prototype.get = function(key){ if (!has.call(this.store, key)) return; return clone(this.store[key]); }; /** * Remove a `key`. * * @param {String} key * @return {Boolean} */ Memory.prototype.remove = function(key){ delete this.store[key]; return true; }; }, {"clone":96,"bind":195}], 206: [function(require, module, exports) { var bind = require('bind'); var defaults = require('defaults'); var store = require('store.js'); /** * Initialize a new `Store` with `options`. * * @param {Object} options */ function Store (options) { this.options(options); } /** * Set the `options` for the store. * * @param {Object} options * @field {Boolean} enabled (true) */ Store.prototype.options = function (options) { if (arguments.length === 0) return this._options; options = options || {}; defaults(options, { enabled : true }); this.enabled = options.enabled && store.enabled; this._options = options; }; /** * Set a `key` and `value` in local storage. * * @param {String} key * @param {Object} value */ Store.prototype.set = function (key, value) { if (!this.enabled) return false; return store.set(key, value); }; /** * Get a value from local storage by `key`. * * @param {String} key * @return {Object} */ Store.prototype.get = function (key) { if (!this.enabled) return null; return store.get(key); }; /** * Remove a value from local storage by `key`. * * @param {String} key */ Store.prototype.remove = function (key) { if (!this.enabled) return false; return store.remove(key); }; /** * Expose the store singleton. */ module.exports = bind.all(new Store()); /** * Expose the `Store` constructor. */ module.exports.Store = Store; }, {"bind":195,"defaults":98,"store.js":212}], 212: [function(require, module, exports) { var json = require('json') , store = {} , win = window , doc = win.document , localStorageName = 'localStorage' , namespace = '__storejs__' , storage; store.disabled = false store.set = function(key, value) {} store.get = function(key) {} store.remove = function(key) {} store.clear = function() {} store.transact = function(key, defaultVal, transactionFn) { var val = store.get(key) if (transactionFn == null) { transactionFn = defaultVal defaultVal = null } if (typeof val == 'undefined') { val = defaultVal || {} } transactionFn(val) store.set(key, val) } store.getAll = function() {} store.serialize = function(value) { return json.stringify(value) } store.deserialize = function(value) { if (typeof value != 'string') { return undefined } try { return json.parse(value) } catch(e) { return value || undefined } } // Functions to encapsulate questionable FireFox 3.6.13 behavior // when about.config::dom.storage.enabled === false // See https://github.com/marcuswestin/store.js/issues#issue/13 function isLocalStorageNameSupported() { try { return (localStorageName in win && win[localStorageName]) } catch(err) { return false } } if (isLocalStorageNameSupported()) { storage = win[localStorageName] store.set = function(key, val) { if (val === undefined) { return store.remove(key) } storage.setItem(key, store.serialize(val)) return val } store.get = function(key) { return store.deserialize(storage.getItem(key)) } store.remove = function(key) { storage.removeItem(key) } store.clear = function() { storage.clear() } store.getAll = function() { var ret = {} for (var i=0; i<storage.length; ++i) { var key = storage.key(i) ret[key] = store.get(key) } return ret } } else if (doc.documentElement.addBehavior) { var storageOwner, storageContainer // Since #userData storage applies only to specific paths, we need to // somehow link our data to a specific path. We choose /favicon.ico // as a pretty safe option, since all browsers already make a request to // this URL anyway and being a 404 will not hurt us here. We wrap an // iframe pointing to the favicon in an ActiveXObject(htmlfile) object // (see: http://msdn.microsoft.com/en-us/library/aa752574(v=VS.85).aspx) // since the iframe access rules appear to allow direct access and // manipulation of the document element, even for a 404 page. This // document can be used instead of the current document (which would // have been limited to the current path) to perform #userData storage. try { storageContainer = new ActiveXObject('htmlfile') storageContainer.open() storageContainer.write('<s' + 'cript>document.w=window</s' + 'cript><iframe src="/favicon.ico"></iframe>') storageContainer.close() storageOwner = storageContainer.w.frames[0].document storage = storageOwner.createElement('div') } catch(e) { // somehow ActiveXObject instantiation failed (perhaps some special // security settings or otherwse), fall back to per-path storage storage = doc.createElement('div') storageOwner = doc.body } function withIEStorage(storeFunction) { return function() { var args = Array.prototype.slice.call(arguments, 0) args.unshift(storage) // See http://msdn.microsoft.com/en-us/library/ms531081(v=VS.85).aspx // and http://msdn.microsoft.com/en-us/library/ms531424(v=VS.85).aspx storageOwner.appendChild(storage) storage.addBehavior('#default#userData') storage.load(localStorageName) var result = storeFunction.apply(store, args) storageOwner.removeChild(storage) return result } } // In IE7, keys may not contain special chars. See all of https://github.com/marcuswestin/store.js/issues/40 var forbiddenCharsRegex = new RegExp("[!\"#$%&'()*+,/\\\\:;<=>?@[\\]^`{|}~]", "g") function ieKeyFix(key) { return key.replace(forbiddenCharsRegex, '___') } store.set = withIEStorage(function(storage, key, val) { key = ieKeyFix(key) if (val === undefined) { return store.remove(key) } storage.setAttribute(key, store.serialize(val)) storage.save(localStorageName) return val }) store.get = withIEStorage(function(storage, key) { key = ieKeyFix(key) return store.deserialize(storage.getAttribute(key)) }) store.remove = withIEStorage(function(storage, key) { key = ieKeyFix(key) storage.removeAttribute(key) storage.save(localStorageName) }) store.clear = withIEStorage(function(storage) { var attributes = storage.XMLDocument.documentElement.attributes storage.load(localStorageName) for (var i=0, attr; attr=attributes[i]; i++) { storage.removeAttribute(attr.name) } storage.save(localStorageName) }) store.getAll = withIEStorage(function(storage) { var attributes = storage.XMLDocument.documentElement.attributes var ret = {} for (var i=0, attr; attr=attributes[i]; ++i) { var key = ieKeyFix(attr.name) ret[attr.name] = store.deserialize(storage.getAttribute(key)) } return ret }) } try { store.set(namespace, namespace) if (store.get(namespace) != namespace) { store.disabled = true } store.remove(namespace) } catch(e) { store.disabled = true } store.enabled = !store.disabled module.exports = store; }, {"json":165}], 211: [function(require, module, exports) { module.exports = function(a, b){ var fn = function(){}; fn.prototype = b.prototype; a.prototype = new fn; a.prototype.constructor = a; }; }, {}], 198: [function(require, module, exports) { module.exports = function isMeta (e) { if (e.metaKey || e.altKey || e.ctrlKey || e.shiftKey) return true; // Logic that handles checks for the middle mouse button, based // on [jQuery](https://github.com/jquery/jquery/blob/master/src/event.js#L466). var which = e.which, button = e.button; if (!which && button !== undefined) { return (!button & 1) && (!button & 2) && (button & 4); } else if (which === 2) { return true; } return false; }; }, {}], 199: [function(require, module, exports) { /** * Bind `el` event `type` to `fn`. * * @param {Element} el * @param {String} type * @param {Function} fn * @param {Boolean} capture * @return {Function} * @api public */ exports.bind = function(el, type, fn, capture){ if (el.addEventListener) { el.addEventListener(type, fn, capture || false); } else { el.attachEvent('on' + type, fn); } return fn; }; /** * Unbind `el` event `type`'s callback `fn`. * * @param {Element} el * @param {String} type * @param {Function} fn * @param {Boolean} capture * @return {Function} * @api public */ exports.unbind = function(el, type, fn, capture){ if (el.removeEventListener) { el.removeEventListener(type, fn, capture || false); } else { el.detachEvent('on' + type, fn); } return fn; }; }, {}], 200: [function(require, module, exports) { /** * Module dependencies. */ var canonical = require('canonical'); var url = require('url'); /** * Return a default `options.context.page` object. * * https://segment.com/docs/spec/page/#properties * * @return {Object} */ function pageDefaults() { return { path: canonicalPath(), referrer: document.referrer, search: location.search, title: document.title, url: canonicalUrl(location.search) }; } /** * Return the canonical path for the page. * * @return {String} */ function canonicalPath () { var canon = canonical(); if (!canon) return window.location.pathname; var parsed = url.parse(canon); return parsed.pathname; } /** * Return the canonical URL for the page concat the given `search` * and strip the hash. * * @param {String} search * @return {String} */ function canonicalUrl (search) { var canon = canonical(); if (canon) return ~canon.indexOf('?') ? canon : canon + search; var url = window.location.href; var i = url.indexOf('#'); return -1 === i ? url : url.slice(0, i); } /** * Exports. */ module.exports = pageDefaults; }, {"canonical":172,"url":174}], 201: [function(require, module, exports) { 'use strict'; var objToString = Object.prototype.toString; // TODO: Move to lib var existy = function(val) { return val != null; }; // TODO: Move to lib var isArray = function(val) { return objToString.call(val) === '[object Array]'; }; // TODO: Move to lib var isString = function(val) { return typeof val === 'string' || objToString.call(val) === '[object String]'; }; // TODO: Move to lib var isObject = function(val) { return val != null && typeof val === 'object'; }; /** * Returns a copy of the new `object` containing only the specified properties. * * @name pick * @api public * @category Object * @see {@link omit} * @param {Array.<string>|string} props The property or properties to keep. * @param {Object} object The object to iterate over. * @return {Object} A new object containing only the specified properties from `object`. * @example * var person = { name: 'Tim', occupation: 'enchanter', fears: 'rabbits' }; * * pick('name', person); * //=> { name: 'Tim' } * * pick(['name', 'fears'], person); * //=> { name: 'Tim', fears: 'rabbits' } */ var pick = function pick(props, object) { if (!existy(object) || !isObject(object)) { return {}; } if (isString(props)) { props = [props]; } if (!isArray(props)) { props = []; } var result = {}; for (var i = 0; i < props.length; i += 1) { if (isString(props[i]) && props[i] in object) { result[props[i]] = object[props[i]]; } } return result; }; /** * Exports. */ module.exports = pick; }, {}], 202: [function(require, module, exports) { /** * prevent default on the given `e`. * * examples: * * anchor.onclick = prevent; * anchor.onclick = function(e){ * if (something) return prevent(e); * }; * * @param {Event} e */ module.exports = function(e){ e = e || window.event return e.preventDefault ? e.preventDefault() : e.returnValue = false; }; }, {}], 203: [function(require, module, exports) { /** * Module dependencies. */ var encode = encodeURIComponent; var decode = decodeURIComponent; var trim = require('trim'); var type = require('type'); /** * Parse the given query `str`. * * @param {String} str * @return {Object} * @api public */ exports.parse = function(str){ if ('string' != typeof str) return {}; str = trim(str); if ('' == str) return {}; if ('?' == str.charAt(0)) str = str.slice(1); var obj = {}; var pairs = str.split('&'); for (var i = 0; i < pairs.length; i++) { var parts = pairs[i].split('='); var key = decode(parts[0]); var m; if (m = /(\w+)\[(\d+)\]/.exec(key)) { obj[m[1]] = obj[m[1]] || []; obj[m[1]][m[2]] = decode(parts[1]); continue; } obj[parts[0]] = null == parts[1] ? '' : decode(parts[1]); } return obj; }; /** * Stringify the given `obj`. * * @param {Object} obj * @return {String} * @api public */ exports.stringify = function(obj){ if (!obj) return ''; var pairs = []; for (var key in obj) { var value = obj[key]; if ('array' == type(value)) { for (var i = 0; i < value.length; ++i) { pairs.push(encode(key + '[' + i + ']') + '=' + encode(value[i])); } continue; } pairs.push(encode(key) + '=' + encode(obj[key])); } return pairs.join('&'); }; }, {"trim":127,"type":7}], 204: [function(require, module, exports) { /** * Module Dependencies. */ var debug = require('debug')('analytics.js:normalize'); var indexof = require('component/indexof'); var defaults = require('defaults'); var map = require('component/map'); var each = require('each'); var is = require('is'); /** * HOP. */ var has = Object.prototype.hasOwnProperty; /** * Expose `normalize` */ module.exports = normalize; /** * Toplevel properties. */ var toplevel = [ 'integrations', 'anonymousId', 'timestamp', 'context' ]; /** * Normalize `msg` based on integrations `list`. * * @param {Object} msg * @param {Array} list * @return {Function} */ function normalize(msg, list){ var lower = map(list, function(s){ return s.toLowerCase(); }); var opts = msg.options || {}; var integrations = opts.integrations || {}; var providers = opts.providers || {}; var context = opts.context || {}; var ret = {}; debug('<-', msg); // integrations. each(opts, function(key, value){ if (!integration(key)) return; if (!has.call(integrations, key)) integrations[key] = value; delete opts[key]; }); // providers. delete opts.providers; each(providers, function(key, value){ if (!integration(key)) return; if (is.object(integrations[key])) return; if (has.call(integrations, key) && 'boolean' == typeof providers[key]) return; integrations[key] = value; }); // move all toplevel options to msg // and the rest to context. each(opts, function(key){ if (~indexof(toplevel, key)) { ret[key] = opts[key]; } else { context[key] = opts[key]; } }); // cleanup delete msg.options; ret.integrations = integrations; ret.context = context; ret = defaults(ret, msg); debug('->', ret); return ret; function integration(name){ return !! (~indexof(list, name) || 'all' == name.toLowerCase() || ~indexof(lower, name.toLowerCase())); } } }, {"debug":191,"component/indexof":117,"defaults":98,"component/map":213,"each":4,"is":92}], 213: [function(require, module, exports) { /** * Module dependencies. */ var toFunction = require('to-function'); /** * Map the given `arr` with callback `fn(val, i)`. * * @param {Array} arr * @param {Function} fn * @return {Array} * @api public */ module.exports = function(arr, fn){ var ret = []; fn = toFunction(fn); for (var i = 0; i < arr.length; ++i) { ret.push(fn(arr[i], i)); } return ret; }; }, {"to-function":175}], 207: [function(require, module, exports) { var debug = require('debug')('analytics:user'); var Entity = require('./entity'); var inherit = require('inherit'); var bind = require('bind'); var cookie = require('./cookie'); var uuid = require('uuid'); var rawCookie = require('cookie'); /** * User defaults */ User.defaults = { persist: true, cookie: { key: 'ajs_user_id', oldKey: 'ajs_user' }, localStorage: { key: 'ajs_user_traits' } }; /** * Initialize a new `User` with `options`. * * @param {Object} options */ function User (options) { this.defaults = User.defaults; this.debug = debug; Entity.call(this, options); } /** * Inherit `Entity` */ inherit(User, Entity); /** * Set / get the user id. * * When the user id changes, the method will * reset his anonymousId to a new one. * * Example: * * // didn't change because the user didn't have previous id. * anonId = user.anonymousId(); * user.id('foo'); * assert.equal(anonId, user.anonymousId()); * * // didn't change because the user id changed to null. * anonId = user.anonymousId(); * user.id('foo'); * user.id(null); * assert.equal(anonId, user.anonymousId()); * * // change because the user had previous id. * anonId = user.anonymousId(); * user.id('foo'); * user.id('baz'); // triggers change * user.id('baz'); // no change * assert.notEqual(anonId, user.anonymousId()); * * @param {String} id * @return {Mixed} */ User.prototype.id = function(id){ var prev = this._getId(); var ret = Entity.prototype.id.apply(this, arguments); if (null == prev) return ret; if (prev != id && id) this.anonymousId(null); return ret; }; /** * Set / get / remove anonymousId. * * @param {String} anonId * @return {String|User} */ User.prototype.anonymousId = function(anonId){ var store = this.storage(); // set / remove if (arguments.length) { store.set('ajs_anonymous_id', anonId); return this; } // new if (anonId = store.get('ajs_anonymous_id')) { return anonId; } // old - it is not stringified so we use the raw cookie. if (anonId = rawCookie('_sio')) { anonId = anonId.split('----')[0]; store.set('ajs_anonymous_id', anonId); store.remove('_sio'); return anonId; } // empty anonId = uuid(); store.set('ajs_anonymous_id', anonId); return store.get('ajs_anonymous_id'); }; /** * Remove anonymous id on logout too. */ User.prototype.logout = function(){ Entity.prototype.logout.call(this); this.anonymousId(null); }; /** * Load saved user `id` or `traits` from storage. */ User.prototype.load = function () { if (this._loadOldCookie()) return; Entity.prototype.load.call(this); }; /** * BACKWARDS COMPATIBILITY: Load the old user from the cookie. * * @return {Boolean} * @api private */ User.prototype._loadOldCookie = function () { var user = cookie.get(this._options.cookie.oldKey); if (!user) return false; this.id(user.id); this.traits(user.traits); cookie.remove(this._options.cookie.oldKey); return true; }; /** * Expose the user singleton. */ module.exports = bind.all(new User()); /** * Expose the `User` constructor. */ module.exports.User = User; }, {"debug":191,"./entity":210,"inherit":211,"bind":195,"./cookie":196,"uuid":185,"cookie":184}], 5: [function(require, module, exports) { module.exports = { "name": "analytics", "version": "2.8.18", "main": "analytics.js", "dependencies": {}, "devDependencies": {} } ; }, {}]}, {}, {"1":""}) );
packages/material-ui-icons/src/SignalWifi0BarOutlined.js
lgollut/material-ui
import React from 'react'; import createSvgIcon from './utils/createSvgIcon'; export default createSvgIcon( <path fillOpacity=".3" d="M12.01 21.49L23.64 7c-.45-.34-4.93-4-11.64-4C5.28 3 .81 6.66.36 7l11.63 14.49.01.01.01-.01z" /> , 'SignalWifi0BarOutlined');
src/svg-icons/av/not-interested.js
xmityaz/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let AvNotInterested = (props) => ( <SvgIcon {...props}> <path d="M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm0 18c-4.42 0-8-3.58-8-8 0-1.85.63-3.55 1.69-4.9L16.9 18.31C15.55 19.37 13.85 20 12 20zm6.31-3.1L7.1 5.69C8.45 4.63 10.15 4 12 4c4.42 0 8 3.58 8 8 0 1.85-.63 3.55-1.69 4.9z"/> </SvgIcon> ); AvNotInterested = pure(AvNotInterested); AvNotInterested.displayName = 'AvNotInterested'; AvNotInterested.muiName = 'SvgIcon'; export default AvNotInterested;
examples/03 Nesting/Drop Targets/index.js
tylercollier/react-dnd-demo
import React, { Component } from 'react'; import Container from './Container'; export default class NestingDropTargets extends Component { render() { return ( <div> <p> <b><a href='https://github.com/gaearon/react-dnd/tree/master/examples/03%20Nesting/Drop%20Targets'>Browse the Source</a></b> </p> <p> Drop targets can, too, be nested in one another. Unlike the drag sources, several drop targets may react to the same item being dragged. React DnD by design offers no means of stopping propagation. Instead, the drop targets may compare <code>monitor.isOver()</code> and <code>monitor.isOver({'{'} shallow: false {'}'})</code> to learn if just them, or their nested targets, are being hovered. They may also check <code>monitor.didDrop()</code> and <code>monitor.getDropResult()</code> to learn if a nested target has already handled the drop, and even return a different drop result. </p> <Container /> </div> ); } }
modules/gui/src/widget/buttonGroup.js
openforis/sepal
import {Widget} from './widget' import {compose} from 'compose' import {withContext} from 'context' import PropTypes from 'prop-types' import React from 'react' import withForwardedRef from 'ref' const Context = React.createContext() export const withButtonGroupContext = withContext(Context, 'buttonGroupContext') const _ButtonGroup = ({className, layout, alignment, spacing, framed, label, disabled, onMouseOver, onMouseOut, forwardedRef, children}) => { const mapChild = (child, index, childrenCount) => { const joinLeft = index !== 0 const joinRight = index !== childrenCount - 1 return ( <Context.Provider value={{joinLeft, joinRight}}> {child} </Context.Provider> ) } const mapChildren = children => React.Children.map(children, (child, index) => mapChild(child, index, children.length) ) return ( <Widget ref={forwardedRef} className={className} label={label} layout={layout} alignment={alignment} spacing={spacing} framed={framed} disabled={disabled} onMouseOver={onMouseOver} onMouseOut={onMouseOut}> {spacing === 'none' ? mapChildren(children) : children} </Widget> ) } export const ButtonGroup = compose( _ButtonGroup, withForwardedRef() ) ButtonGroup.propTypes = { alignment: PropTypes.any, children: PropTypes.any, className: PropTypes.string, disabled: PropTypes.any, framed: PropTypes.any, label: PropTypes.any, layout: PropTypes.any, spacing: PropTypes.any, onMouseOut: PropTypes.func, onMouseOver: PropTypes.func } ButtonGroup.defaultProps = { alignment: 'left', layout: 'horizontal', spacing: 'compact' }
actor-apps/app-web/src/app/components/activity/UserProfile.react.js
boyley/actor-platform
import React from 'react'; import { PureRenderMixin } from 'react/addons'; import ContactActionCreators from 'actions/ContactActionCreators'; import DialogActionCreators from 'actions/DialogActionCreators'; import PeerStore from 'stores/PeerStore'; import DialogStore from 'stores/DialogStore'; import AvatarItem from 'components/common/AvatarItem.react'; import UserProfileContactInfo from 'components/activity/UserProfileContactInfo.react'; const getStateFromStores = (userId) => { const thisPeer = PeerStore.getUserPeer(userId); return { thisPeer: thisPeer, isNotificationsEnabled: DialogStore.isNotificationsEnabled(thisPeer) }; }; var UserProfile = React.createClass({ propTypes: { user: React.PropTypes.object.isRequired }, mixins: [PureRenderMixin], getInitialState() { return getStateFromStores(this.props.user.id); }, componentWillMount() { DialogStore.addNotificationsListener(this.whenNotificationChanged); }, componentWillUnmount() { DialogStore.removeNotificationsListener(this.whenNotificationChanged); }, componentWillReceiveProps(newProps) { this.setState(getStateFromStores(newProps.user.id)); }, addToContacts() { ContactActionCreators.addContact(this.props.user.id); }, removeFromContacts() { ContactActionCreators.removeContact(this.props.user.id); }, onNotificationChange(event) { DialogActionCreators.changeNotificationsEnabled(this.state.thisPeer, event.target.checked); }, whenNotificationChanged() { this.setState(getStateFromStores(this.props.user.id)); }, render() { const user = this.props.user; const isNotificationsEnabled = this.state.isNotificationsEnabled; let addToContacts; if (user.isContact === false) { addToContacts = <a className="link__blue" onClick={this.addToContacts}>Add to contacts</a>; } else { addToContacts = <a className="link__red" onClick={this.removeFromContacts}>Remove from contacts</a>; } return ( <div className="activity__body profile"> <div className="profile__name"> <AvatarItem image={user.bigAvatar} placeholder={user.placeholder} size="medium" title={user.name}/> <h3>{user.name}</h3> </div> <div className="notifications"> <label htmlFor="notifications">Enable Notifications</label> <div className="switch pull-right"> <input checked={isNotificationsEnabled} id="notifications" onChange={this.onNotificationChange} type="checkbox"/> <label htmlFor="notifications"></label> </div> </div> <UserProfileContactInfo phones={user.phones}/> <ul className="profile__list profile__list--usercontrols"> <li className="profile__list__item"> {addToContacts} </li> </ul> </div> ); } }); export default UserProfile;
my-app/src/components/scaffold/MenuItem.js
sThig/jabbascrypt
import React from 'react'; import styled from 'styled-components'; import MediaQuery from '../helper/mediaQuery'; import { NavLink } from 'react-router-dom'; const MenuList = styled.li` a { display: block; color: rgba(255,255,255,0.3); padding: 14px 16px; text-decoration: none; ${MediaQuery.phone`flex:1 1 50%; background: #000;`} ${MediaQuery.tablet`background: #3E3E3E; flex: 3; background-color: #000;`} } a:hover { color: white; ${MediaQuery.phone`background-color: #240562; box-shadow: inset 0 0 0 0 ;`} transition: all 250ms; ${MediaQuery.tablet`box-shadow: inset 0 -1px 0 0 #000; `} ${MediaQuery.phone`box-shadow: inset 0 -1px 0 0 #000; `} box-shadow: inset 0 -1px 0 0 #61DAFB; } &.logo { flex-grow: 3; width: 100%; display: block; a { width: 100px; ${MediaQuery.desktop`width: 100%;`} ${MediaQuery.tablet`width: 100%; text-align: left;`} ${MediaQuery.phone`width: 100%; text-align: left;`} } align-self: flex-start; text-align: left; } &.open { background: red; } &.flexitems { flex-grow: 3; } `; class MenuItem extends React.Component { render() { return ( <MenuList onClick={this.props.onClick} className="flexitems"><NavLink to={`/${this.props.tagline}`}>{this.props.tagline}</NavLink></MenuList> ); } } export default MenuItem;
packages/react-vis/src/treemap/treemap-svg.js
uber/react-vis
// Copyright (c) 2016 - 2017 Uber Technologies, Inc. // // 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. import React from 'react'; import XYPlot from 'plot/xy-plot'; import PolygonSeries from 'plot/series/polygon-series'; import MarkSeries from 'plot/series/mark-series'; import LabelSeries from 'plot/series/label-series'; import {getCombinedClassName} from 'utils/styling-utils'; const MARGIN_ADJUST = 1.2; class TreemapSVG extends React.Component { getCircularNodes() { const { animation, hideRootNode, nodes, onLeafMouseOver, onLeafMouseOut, onLeafClick, scales, style } = this.props; const {rows, minY, maxY, minX, maxX} = nodes.reduce( (acc, node, index) => { if (!index && hideRootNode) { return acc; } const {x, y, r} = node; return { maxY: Math.max(y + r, acc.maxY), minY: Math.min(y - r, acc.minY), maxX: Math.max(x + MARGIN_ADJUST * r, acc.maxX), minX: Math.min(x - MARGIN_ADJUST * r, acc.minX), rows: acc.rows.concat([ { x, y, size: r, color: scales.color(node) } ]) }; }, { rows: [], maxY: -Infinity, minY: Infinity, maxX: -Infinity, minX: Infinity } ); return { updatedNodes: ( <MarkSeries animation={animation} className="rv-treemap__leaf rv-treemap__leaf--circle" onSeriesMouseEnter={onLeafMouseOver} onSeriesMouseLeave={onLeafMouseOut} onSeriesClick={onLeafClick} data={rows} colorType="literal" getColor={d => d.color} sizeType="literal" getSize={d => d.size} style={style} /> ), minY, maxY, minX, maxX }; } getNonCircularNodes() { const { animation, hideRootNode, nodes, onLeafMouseOver, onLeafMouseOut, onLeafClick, scales, style } = this.props; const {color} = scales; return nodes.reduce( (acc, node, index) => { if (!index && hideRootNode) { return acc; } const {x0, x1, y1, y0} = node; const x = x0; const y = y0; const nodeHeight = y1 - y0; const nodeWidth = x1 - x0; acc.maxY = Math.max(y + nodeHeight, acc.maxY); acc.minY = Math.min(y, acc.minY); acc.maxX = Math.max(x + nodeWidth, acc.maxX); acc.minX = Math.min(x, acc.minX); const data = [ {x, y}, {x, y: y + nodeHeight}, {x: x + nodeWidth, y: y + nodeHeight}, {x: x + nodeWidth, y} ]; acc.updatedNodes = acc.updatedNodes.concat([ <PolygonSeries animation={animation} className="rv-treemap__leaf" key={index} color={color(node)} type="literal" onSeriesMouseEnter={onLeafMouseOver} onSeriesMouseLeave={onLeafMouseOut} onSeriesClick={onLeafClick} data={data} style={{ ...style, ...node.style }} /> ]); return acc; }, { updatedNodes: [], maxY: -Infinity, minY: Infinity, maxX: -Infinity, minX: Infinity } ); } render() { const {className, height, mode, nodes, width} = this.props; const useCirclePacking = mode === 'circlePack'; const {minY, maxY, minX, maxX, updatedNodes} = useCirclePacking ? this.getCircularNodes() : this.getNonCircularNodes(); const labels = nodes.reduce((acc, node) => { if (!node.data.title) { return acc; } return acc.concat({ ...node.data, x: node.x0 || node.x, y: node.y0 || node.y, label: `${node.data.title}` }); }, []); return ( <XYPlot className={getCombinedClassName( 'rv-treemap', useCirclePacking && 'rv-treemap-circle-paked', className )} width={width} height={height} yDomain={[maxY, minY]} xDomain={[minX, maxX]} colorType="literal" hasTreeStructure {...this.props} > {updatedNodes} <LabelSeries data={labels} /> </XYPlot> ); } } TreemapSVG.displayName = 'TreemapSVG'; export default TreemapSVG;
src/screens/Characters/CharacterDetailScreen.js
rdonnelly/swd-team-builder
import React, { Component } from 'react'; import PropTypes from 'prop-types'; import { Image, ScrollView, StyleSheet, Text, TouchableOpacity, View, } from 'react-native'; import { connect } from 'react-redux'; import { validateSetCode } from '../../lib/SWDIconCodes'; import SWDIcon from '../../components/SWDIcon'; import { addCharacter, setCharacterAny, setCharacterRegular, setCharacterElite, removeCharacter, includeCharacter, excludeCharacter, } from '../../store/actions'; import { getCharacters } from '../../store/selectors/characterSelectors'; import { getDeckCharacters } from '../../store/selectors/deckSelectors'; import { characters } from '../../lib/Destiny'; import { cardBack, cardImages } from '../../lib/DestinyImages'; import { base as baseStyles, colors } from '../../styles'; const styles = StyleSheet.create({ container: { ...baseStyles.container, backgroundColor: colors.lightGray, }, details: { alignContent: 'center', paddingHorizontal: 16, width: '100%', }, detailsImageContainer: { alignItems: 'center', justifyContent: 'center', flex: 1, height: 388, paddingVertical: 16, }, detailsImage: { flex: 1, }, actionBar: { backgroundColor: colors.darkGrayTranslucent95, paddingBottom: 8, paddingHorizontal: 8, paddingTop: 16, width: '100%', }, message: { color: colors.white, fontSize: 13, fontWeight: '600', marginBottom: 8, textAlign: 'center', }, buttonView: { alignItems: 'center', flexDirection: 'row', justifyContent: 'center', paddingHorizontal: 8, }, button: { ...baseStyles.button, backgroundColor: colors.darkGrayDark, flex: 1, marginBottom: 8, }, buttonDisabled: { backgroundColor: colors.darkGrayDark, }, buttonGreen: { backgroundColor: colors.green, }, buttonOrange: { backgroundColor: colors.orange, }, buttonPurple: { backgroundColor: colors.purple, }, buttonLeft: { marginRight: 4, }, buttonMiddle: { marginHorizontal: 4, }, buttonRight: { marginLeft: 4, }, buttonIcon: { ...baseStyles.buttonText, fontSize: 18, marginHorizontal: 4, }, buttonText: { ...baseStyles.buttonText, }, buttonTextHighlight: { fontStyle: 'italic', fontWeight: '700', }, buttonTextIcon: { fontSize: 14, }, }); class CharacterDetailScreen extends Component { shouldComponentUpdate(nextProps) { if ( this.props.characterState !== nextProps.characterState || this.props.deckCharacters !== nextProps.deckCharacters ) { return true; } return false; } render() { const { characterState, deckCharacters } = this.props; const cardId = this.props.navigation.getParam('id'); const card = characters[cardId]; const characterObject = characterState.find( (character) => character.id === cardId, ); const deckCharacterObject = deckCharacters.find( (deckCharacter) => deckCharacter.id === cardId, ); const characterIsInDeck = deckCharacterObject !== undefined; const characterIsIncompatible = characterObject !== undefined && characterObject.isIncompatible; const characterIsExcluded = characterObject !== undefined && characterObject.isExcluded; const setIcon = validateSetCode(card.set) ? ( <SWDIcon type={card.set} style={styles.buttonTextIcon} /> ) : null; let deckMessageText = ''; if (characterIsInDeck) { deckMessageText = 'Character Selected for Team'; if (!card.isUnique && deckCharacterObject.count > 1) { deckMessageText += ` (x${deckCharacterObject.count})`; } } const deckMessage = deckMessageText ? ( <View style={styles.buttonView}> <Text style={styles.message}>{deckMessageText}</Text> </View> ) : null; let incompatibleMessageText = ''; if (characterIsIncompatible) { incompatibleMessageText = 'Character Incompatible with Selected Characters or Settings'; } const incompatibleMessage = incompatibleMessageText ? ( <View style={styles.buttonView}> <Text style={styles.message}>{incompatibleMessageText}</Text> </View> ) : null; const excludeButton = !characterIsExcluded && !characterIsInDeck && !characterIsIncompatible ? ( <TouchableOpacity onPress={() => this.props.excludeCharacter(card.id)} style={[styles.button, styles.buttonOrange]} > <Text style={styles.buttonText}> {'Exclude '} <Text style={styles.buttonTextHighlight}> {card.name} &nbsp;{setIcon} </Text> </Text> </TouchableOpacity> ) : null; const includeButton = characterIsExcluded && !characterIsInDeck && !characterIsIncompatible ? ( <TouchableOpacity onPress={() => this.props.includeCharacter(card.id)} style={[styles.button, styles.buttonOrange]} > <Text style={styles.buttonText}> {'Include '} <Text style={styles.buttonTextHighlight}> {card.name} &nbsp;{setIcon} </Text> </Text> </TouchableOpacity> ) : null; const addButton = (!characterIsInDeck || !card.isUnique) && !characterIsIncompatible && !characterIsExcluded ? ( <TouchableOpacity onPress={() => this.props.addCharacter(characterObject)} style={[styles.button, styles.buttonGreen]} > <Text style={styles.buttonText}> {!characterIsInDeck || card.isUnique ? 'Add ' : 'Add Another '} <Text style={styles.buttonTextHighlight}> {card.name} &nbsp;{setIcon} </Text> </Text> </TouchableOpacity> ) : null; const removeButton = characterIsInDeck ? ( <TouchableOpacity onPress={() => this.props.removeCharacter(characterObject)} style={[styles.button, styles.buttonOrange]} > <Text style={styles.buttonText}> {'Remove '} <Text style={styles.buttonTextHighlight}> {card.name} &nbsp;{setIcon} </Text> </Text> </TouchableOpacity> ) : null; const anyButton = characterIsInDeck && card.isUnique ? ( <TouchableOpacity disabled={deckCharacterObject.diceCount === 0} onPress={() => this.props.setCharacterAny(characterObject)} style={[ styles.button, styles.buttonPurple, styles.buttonLeft, deckCharacterObject.diceCount === 0 && styles.buttonDisabled, ]} > <Text style={styles.buttonText}>{'Any'}</Text> </TouchableOpacity> ) : null; const regularButton = characterIsInDeck && card.isUnique ? ( <TouchableOpacity disabled={deckCharacterObject.diceCount === 1} onPress={() => this.props.setCharacterRegular(characterObject)} style={[ styles.button, styles.buttonPurple, styles.buttonMiddle, deckCharacterObject.diceCount === 1 && styles.buttonDisabled, ]} > <SWDIcon type={'DIE'} style={styles.buttonIcon} /> </TouchableOpacity> ) : null; const eliteButton = characterIsInDeck && card.isUnique && card.pointsElite ? ( <TouchableOpacity disabled={deckCharacterObject.diceCount === 2} onPress={() => this.props.setCharacterElite(characterObject)} style={[ styles.button, styles.buttonPurple, styles.buttonRight, deckCharacterObject.diceCount === 2 && styles.buttonDisabled, ]} > <View> <SWDIcon type={'DIE'} style={styles.buttonIcon} /> </View> <View> <SWDIcon type={'DIE'} style={styles.buttonIcon} /> </View> </TouchableOpacity> ) : null; const imageSrc = cardImages[card.id] || cardBack; return ( <View style={styles.container}> <ScrollView style={styles.details}> <View style={styles.detailsImageContainer}> <Image style={styles.detailsImage} resizeMode="contain" source={imageSrc} /> </View> </ScrollView> <View style={styles.actionBar}> {incompatibleMessage} {deckMessage} <View style={styles.buttonView}> {anyButton} {regularButton} {eliteButton} </View> <View style={styles.buttonView}>{addButton}</View> <View style={styles.buttonView}>{removeButton}</View> <View style={styles.buttonView}>{excludeButton}</View> <View style={styles.buttonView}>{includeButton}</View> </View> </View> ); } } CharacterDetailScreen.propTypes = { navigation: PropTypes.object.isRequired, characterState: PropTypes.array.isRequired, deckCharacters: PropTypes.array.isRequired, addCharacter: PropTypes.func.isRequired, setCharacterAny: PropTypes.func.isRequired, setCharacterElite: PropTypes.func.isRequired, setCharacterRegular: PropTypes.func.isRequired, removeCharacter: PropTypes.func.isRequired, includeCharacter: PropTypes.func.isRequired, excludeCharacter: PropTypes.func.isRequired, }; const mapStateToProps = (state) => ({ characterState: getCharacters(state), deckCharacters: getDeckCharacters(state), }); const mapDispatchToProps = { addCharacter, setCharacterAny, setCharacterRegular, setCharacterElite, removeCharacter, includeCharacter, excludeCharacter, }; export default connect( mapStateToProps, mapDispatchToProps, )(CharacterDetailScreen);
docs/src/pages/customization/overrides/Classes.js
cherniavskii/material-ui
import React from 'react'; import PropTypes from 'prop-types'; import { withStyles } from 'material-ui/styles'; import Button from 'material-ui/Button'; const styles = { root: { background: 'linear-gradient(45deg, #FE6B8B 30%, #FF8E53 90%)', borderRadius: 3, border: 0, color: 'white', height: 48, padding: '0 30px', boxShadow: '0 3px 5px 2px rgba(255, 105, 135, .30)', }, label: { textTransform: 'capitalize', }, }; function Classes(props) { return ( <Button classes={{ root: props.classes.root, // class name, e.g. `classes-root-x` label: props.classes.label, // class name, e.g. `classes-label-x` }} > {props.children ? props.children : 'classes'} </Button> ); } Classes.propTypes = { children: PropTypes.node, classes: PropTypes.object.isRequired, }; export default withStyles(styles)(Classes);
ajax/libs/react-slick/0.10.0/react-slick.js
hare1039/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["Slider"] = factory(require("react"), require("react-dom")); else root["Slider"] = factory(root["React"], root["ReactDOM"]); })(this, function(__WEBPACK_EXTERNAL_MODULE_2__, __WEBPACK_EXTERNAL_MODULE_7__) { 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'; module.exports = __webpack_require__(1); /***/ }, /* 1 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } var _react = __webpack_require__(2); var _react2 = _interopRequireDefault(_react); var _innerSlider = __webpack_require__(3); var _objectAssign = __webpack_require__(11); var _objectAssign2 = _interopRequireDefault(_objectAssign); var _json2mq = __webpack_require__(18); var _json2mq2 = _interopRequireDefault(_json2mq); var _reactResponsiveMixin = __webpack_require__(20); var _reactResponsiveMixin2 = _interopRequireDefault(_reactResponsiveMixin); var _defaultProps = __webpack_require__(13); var _defaultProps2 = _interopRequireDefault(_defaultProps); var Slider = _react2['default'].createClass({ displayName: 'Slider', mixins: [_reactResponsiveMixin2['default']], getInitialState: function getInitialState() { return { breakpoint: null }; }, componentDidMount: function componentDidMount() { var _this = this; if (this.props.responsive) { var breakpoints = this.props.responsive.map(function (breakpt) { return breakpt.breakpoint; }); breakpoints.sort(function (x, y) { return x - y; }); breakpoints.forEach(function (breakpoint, index) { var bQuery; if (index === 0) { bQuery = (0, _json2mq2['default'])({ minWidth: 0, maxWidth: breakpoint }); } else { bQuery = (0, _json2mq2['default'])({ minWidth: breakpoints[index - 1], maxWidth: breakpoint }); } _this.media(bQuery, function () { _this.setState({ breakpoint: breakpoint }); }); }); // Register media query for full screen. Need to support resize from small to large var query = (0, _json2mq2['default'])({ minWidth: breakpoints.slice(-1)[0] }); this.media(query, function () { _this.setState({ breakpoint: null }); }); } }, render: function render() { var _this2 = this; var settings; var newProps; if (this.state.breakpoint) { newProps = this.props.responsive.filter(function (resp) { return resp.breakpoint === _this2.state.breakpoint; }); settings = newProps[0].settings === 'unslick' ? 'unslick' : (0, _objectAssign2['default'])({}, this.props, newProps[0].settings); } else { settings = (0, _objectAssign2['default'])({}, _defaultProps2['default'], this.props); } if (settings === 'unslick') { // if 'unslick' responsive breakpoint setting used, just return the <Slider> tag nested HTML return _react2['default'].createElement( 'div', null, this.props.children ); } else { return _react2['default'].createElement( _innerSlider.InnerSlider, settings, this.props.children ); } } }); module.exports = Slider; /***/ }, /* 2 */ /***/ function(module, exports) { module.exports = __WEBPACK_EXTERNAL_MODULE_2__; /***/ }, /* 3 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, '__esModule', { value: true }); var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } var _react = __webpack_require__(2); var _react2 = _interopRequireDefault(_react); var _mixinsEventHandlers = __webpack_require__(4); var _mixinsEventHandlers2 = _interopRequireDefault(_mixinsEventHandlers); var _mixinsHelpers = __webpack_require__(8); var _mixinsHelpers2 = _interopRequireDefault(_mixinsHelpers); var _initialState = __webpack_require__(12); var _initialState2 = _interopRequireDefault(_initialState); var _defaultProps = __webpack_require__(13); var _defaultProps2 = _interopRequireDefault(_defaultProps); var _classnames = __webpack_require__(14); var _classnames2 = _interopRequireDefault(_classnames); var _track = __webpack_require__(15); var _dots = __webpack_require__(16); var _arrows = __webpack_require__(17); var InnerSlider = _react2['default'].createClass({ displayName: 'InnerSlider', mixins: [_mixinsHelpers2['default'], _mixinsEventHandlers2['default']], getInitialState: function getInitialState() { return _initialState2['default']; }, getDefaultProps: function getDefaultProps() { return _defaultProps2['default']; }, componentWillMount: function componentWillMount() { if (this.props.init) { this.props.init(); } this.setState({ mounted: true }); var lazyLoadedList = []; for (var i = 0; i < this.props.children.length; i++) { if (i >= this.state.currentSlide && i < this.state.currentSlide + this.props.slidesToShow) { lazyLoadedList.push(i); } } if (this.props.lazyLoad && this.state.lazyLoadedList.length === 0) { this.setState({ lazyLoadedList: lazyLoadedList }); } }, componentDidMount: function componentDidMount() { // Hack for autoplay -- Inspect Later this.initialize(this.props); this.adaptHeight(); if (window.addEventListener) { window.addEventListener('resize', this.onWindowResized); } else { window.attachEvent('onresize', this.onWindowResized); } }, componentWillUnmount: function componentWillUnmount() { if (window.addEventListener) { window.removeEventListener('resize', this.onWindowResized); } else { window.detachEvent('onresize', this.onWindowResized); } if (this.state.autoPlayTimer) { window.clearTimeout(this.state.autoPlayTimer); } }, componentWillReceiveProps: function componentWillReceiveProps(nextProps) { if (this.props.slickGoTo != nextProps.slickGoTo) { this.changeSlide({ message: 'index', index: nextProps.slickGoTo, currentSlide: this.state.currentSlide }); } else { this.update(nextProps); } }, componentDidUpdate: function componentDidUpdate() { this.adaptHeight(); }, onWindowResized: function onWindowResized() { this.update(this.props); }, render: function render() { var className = (0, _classnames2['default'])('slick-initialized', 'slick-slider', this.props.className); var trackProps = { fade: this.props.fade, cssEase: this.props.cssEase, speed: this.props.speed, infinite: this.props.infinite, centerMode: this.props.centerMode, currentSlide: this.state.currentSlide, lazyLoad: this.props.lazyLoad, lazyLoadedList: this.state.lazyLoadedList, rtl: this.props.rtl, slideWidth: this.state.slideWidth, slidesToShow: this.props.slidesToShow, slideCount: this.state.slideCount, trackStyle: this.state.trackStyle, variableWidth: this.props.variableWidth }; var dots; if (this.props.dots === true && this.state.slideCount > this.props.slidesToShow) { var dotProps = { dotsClass: this.props.dotsClass, slideCount: this.state.slideCount, slidesToShow: this.props.slidesToShow, currentSlide: this.state.currentSlide, slidesToScroll: this.props.slidesToScroll, clickHandler: this.changeSlide }; dots = _react2['default'].createElement(_dots.Dots, dotProps); } var prevArrow, nextArrow; var arrowProps = { infinite: this.props.infinite, centerMode: this.props.centerMode, currentSlide: this.state.currentSlide, slideCount: this.state.slideCount, slidesToShow: this.props.slidesToShow, prevArrow: this.props.prevArrow, nextArrow: this.props.nextArrow, clickHandler: this.changeSlide }; if (this.props.arrows) { prevArrow = _react2['default'].createElement(_arrows.PrevArrow, arrowProps); nextArrow = _react2['default'].createElement(_arrows.NextArrow, arrowProps); } return _react2['default'].createElement( 'div', { className: className, onMouseEnter: this.onInnerSliderEnter, onMouseLeave: this.onInnerSliderLeave }, _react2['default'].createElement( 'div', { ref: 'list', className: 'slick-list', onMouseDown: this.swipeStart, onMouseMove: this.state.dragging ? this.swipeMove : null, onMouseUp: this.swipeEnd, onMouseLeave: this.state.dragging ? this.swipeEnd : null, onTouchStart: this.swipeStart, onTouchMove: this.state.dragging ? this.swipeMove : null, onTouchEnd: this.swipeEnd, onTouchCancel: this.state.dragging ? this.swipeEnd : null }, _react2['default'].createElement( _track.Track, _extends({ ref: 'track' }, trackProps), this.props.children ) ), prevArrow, nextArrow, dots ); } }); exports.InnerSlider = InnerSlider; /***/ }, /* 4 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, '__esModule', { value: true }); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } var _trackHelper = __webpack_require__(5); var _helpers = __webpack_require__(8); var _helpers2 = _interopRequireDefault(_helpers); var _objectAssign = __webpack_require__(11); var _objectAssign2 = _interopRequireDefault(_objectAssign); var EventHandlers = { // Event handler for previous and next changeSlide: function changeSlide(options) { var indexOffset, previousInt, slideOffset, unevenOffset, targetSlide; unevenOffset = this.state.slideCount % this.props.slidesToScroll !== 0; indexOffset = unevenOffset ? 0 : (this.state.slideCount - this.state.currentSlide) % this.props.slidesToScroll; if (options.message === 'previous') { slideOffset = indexOffset === 0 ? this.props.slidesToScroll : this.props.slidesToShow - indexOffset; previousInt = this.state.currentSlide - slideOffset; targetSlide = previousInt === -1 ? this.state.slideCount - 1 : previousInt; } else if (options.message === 'next') { slideOffset = indexOffset === 0 ? this.props.slidesToScroll : indexOffset; targetSlide = this.state.currentSlide + slideOffset; } else if (options.message === 'dots') { // Click on dots targetSlide = options.index * options.slidesToScroll; if (targetSlide === options.currentSlide) { return; } } else if (options.message === 'index') { targetSlide = options.index; if (targetSlide === options.currentSlide) { return; } } this.slideHandler(targetSlide); }, // Accessiblity handler for previous and next keyHandler: function keyHandler(e) {}, // Focus on selecting a slide (click handler on track) selectHandler: function selectHandler(e) {}, swipeStart: function swipeStart(e) { var touches, posX, posY; if (this.props.swipe === false || 'ontouchend' in document && this.props.swipe === false) { return; } else if (this.props.draggable === false && e.type.indexOf('mouse') !== -1) { return; } posX = e.touches !== undefined ? e.touches[0].pageX : e.clientX; posY = e.touches !== undefined ? e.touches[0].pageY : e.clientY; this.setState({ dragging: true, touchObject: { startX: posX, startY: posY, curX: posX, curY: posY } }); }, swipeMove: function swipeMove(e) { if (!this.state.dragging) { return; } if (this.state.animating) { return; } var swipeLeft; var curLeft, positionOffset; var touchObject = this.state.touchObject; curLeft = (0, _trackHelper.getTrackLeft)((0, _objectAssign2['default'])({ slideIndex: this.state.currentSlide, trackRef: this.refs.track }, this.props, this.state)); touchObject.curX = e.touches ? e.touches[0].pageX : e.clientX; touchObject.curY = e.touches ? e.touches[0].pageY : e.clientY; touchObject.swipeLength = Math.round(Math.sqrt(Math.pow(touchObject.curX - touchObject.startX, 2))); positionOffset = (this.props.rtl === false ? 1 : -1) * (touchObject.curX > touchObject.startX ? 1 : -1); var currentSlide = this.state.currentSlide; var dotCount = Math.ceil(this.state.slideCount / this.props.slidesToScroll); var swipeDirection = this.swipeDirection(this.state.touchObject); var touchSwipeLength = touchObject.swipeLength; if (this.props.infinite === false) { if (currentSlide === 0 && swipeDirection === 'right' || currentSlide + 1 >= dotCount && swipeDirection === 'left') { touchSwipeLength = touchObject.swipeLength * this.props.edgeFriction; if (this.state.edgeDragged === false && this.props.edgeEvent) { this.props.edgeEvent(swipeDirection); this.setState({ edgeDragged: true }); } } } if (this.state.swiped === false && this.props.swipeEvent) { this.props.swipeEvent(swipeDirection); this.setState({ swiped: true }); } swipeLeft = curLeft + touchSwipeLength * positionOffset; this.setState({ touchObject: touchObject, swipeLeft: swipeLeft, trackStyle: (0, _trackHelper.getTrackCSS)((0, _objectAssign2['default'])({ left: swipeLeft }, this.props, this.state)) }); if (Math.abs(touchObject.curX - touchObject.startX) < Math.abs(touchObject.curY - touchObject.startY) * 0.8) { return; } if (touchObject.swipeLength > 4) { e.preventDefault(); } }, swipeEnd: function swipeEnd(e) { if (!this.state.dragging) { return; } var touchObject = this.state.touchObject; var minSwipe = this.state.listWidth / this.props.touchThreshold; var swipeDirection = this.swipeDirection(touchObject); // reset the state of touch related state variables. this.setState({ dragging: false, edgeDragged: false, swiped: false, swipeLeft: null, touchObject: {} }); // Fix for #13 if (!touchObject.swipeLength) { return; } if (touchObject.swipeLength > minSwipe) { e.preventDefault(); if (swipeDirection === 'left') { this.slideHandler(this.state.currentSlide + this.props.slidesToScroll); } else if (swipeDirection === 'right') { this.slideHandler(this.state.currentSlide - this.props.slidesToScroll); } else { this.slideHandler(this.state.currentSlide); } } else { // Adjust the track back to it's original position. var currentLeft = (0, _trackHelper.getTrackLeft)((0, _objectAssign2['default'])({ slideIndex: this.state.currentSlide, trackRef: this.refs.track }, this.props, this.state)); this.setState({ trackStyle: (0, _trackHelper.getTrackAnimateCSS)((0, _objectAssign2['default'])({ left: currentLeft }, this.props, this.state)) }); } }, onInnerSliderEnter: function onInnerSliderEnter(e) { if (this.props.autoplay && this.props.pauseOnHover) { this.pause(); } }, onInnerSliderLeave: function onInnerSliderLeave(e) { if (this.props.autoplay && this.props.pauseOnHover) { this.autoPlay(); } } }; exports['default'] = EventHandlers; module.exports = exports['default']; /***/ }, /* 5 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, '__esModule', { value: true }); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } var _ReactDOM = __webpack_require__(6); var _ReactDOM2 = _interopRequireDefault(_ReactDOM); var checkSpecKeys = function checkSpecKeys(spec, keysArray) { return keysArray.reduce(function (value, key) { return value && spec.hasOwnProperty(key); }, true) ? null : console.error('Keys Missing', spec); }; var getTrackCSS = function getTrackCSS(spec) { checkSpecKeys(spec, ['left', 'variableWidth', 'slideCount', 'slidesToShow', 'slideWidth']); var trackWidth; if (spec.variableWidth) { trackWidth = (spec.slideCount + 2 * spec.slidesToShow) * spec.slideWidth; } else if (spec.centerMode) { trackWidth = (spec.slideCount + 2 * (spec.slidesToShow + 1)) * spec.slideWidth; } else { trackWidth = (spec.slideCount + 2 * spec.slidesToShow) * spec.slideWidth; } var style = { opacity: 1, width: trackWidth, WebkitTransform: 'translate3d(' + spec.left + 'px, 0px, 0px)', transform: 'translate3d(' + spec.left + 'px, 0px, 0px)', transition: '', WebkitTransition: '', msTransform: 'translateX(' + spec.left + 'px)' }; // Fallback for IE8 if (!window.addEventListener && window.attachEvent) { style.marginLeft = spec.left + 'px'; } return style; }; exports.getTrackCSS = getTrackCSS; var getTrackAnimateCSS = function getTrackAnimateCSS(spec) { checkSpecKeys(spec, ['left', 'variableWidth', 'slideCount', 'slidesToShow', 'slideWidth', 'speed', 'cssEase']); var style = getTrackCSS(spec); // useCSS is true by default so it can be undefined style.WebkitTransition = '-webkit-transform ' + spec.speed + 'ms ' + spec.cssEase; style.transition = 'transform ' + spec.speed + 'ms ' + spec.cssEase; return style; }; exports.getTrackAnimateCSS = getTrackAnimateCSS; var getTrackLeft = function getTrackLeft(spec) { checkSpecKeys(spec, ['slideIndex', 'trackRef', 'infinite', 'centerMode', 'slideCount', 'slidesToShow', 'slidesToScroll', 'slideWidth', 'listWidth', 'variableWidth']); var slideOffset = 0; var targetLeft; var targetSlide; if (spec.fade) { return 0; } if (spec.infinite) { if (spec.slideCount > spec.slidesToShow) { slideOffset = spec.slideWidth * spec.slidesToShow * -1; } if (spec.slideCount % spec.slidesToScroll !== 0) { if (spec.slideIndex + spec.slidesToScroll > spec.slideCount && spec.slideCount > spec.slidesToShow) { if (spec.slideIndex > spec.slideCount) { slideOffset = (spec.slidesToShow - (spec.slideIndex - spec.slideCount)) * spec.slideWidth * -1; } else { slideOffset = spec.slideCount % spec.slidesToScroll * spec.slideWidth * -1; } } } } if (spec.centerMode) { if (spec.infinite) { slideOffset += spec.slideWidth * Math.floor(spec.slidesToShow / 2); } else { slideOffset = spec.slideWidth * Math.floor(spec.slidesToShow / 2); } } targetLeft = spec.slideIndex * spec.slideWidth * -1 + slideOffset; if (spec.variableWidth === true) { var targetSlideIndex; if (spec.slideCount <= spec.slidesToShow || spec.infinite === false) { targetSlide = _ReactDOM2['default'].findDOMNode(spec.trackRef).childNodes[spec.slideIndex]; } else { targetSlideIndex = spec.slideIndex + spec.slidesToShow; targetSlide = _ReactDOM2['default'].findDOMNode(spec.trackRef).childNodes[targetSlideIndex]; } targetLeft = targetSlide ? targetSlide.offsetLeft * -1 : 0; if (spec.centerMode === true) { if (spec.infinite === false) { targetSlide = _ReactDOM2['default'].findDOMNode(spec.trackRef).children[spec.slideIndex]; } else { targetSlide = _ReactDOM2['default'].findDOMNode(spec.trackRef).children[spec.slideIndex + spec.slidesToShow + 1]; } targetLeft = targetSlide ? targetSlide.offsetLeft * -1 : 0; targetLeft += (spec.listWidth - targetSlide.offsetWidth) / 2; } } return targetLeft; }; exports.getTrackLeft = getTrackLeft; /***/ }, /* 6 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, '__esModule', { value: true }); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } var _react = __webpack_require__(2); var _react2 = _interopRequireDefault(_react); var _reactDom = __webpack_require__(7); var _reactDom2 = _interopRequireDefault(_reactDom); var ReactDOM = _react2['default'].version >= '0.14.0' ? _reactDom2['default'] : _react2['default']; exports['default'] = ReactDOM; module.exports = exports['default']; /***/ }, /* 7 */ /***/ function(module, exports) { module.exports = __WEBPACK_EXTERNAL_MODULE_7__; /***/ }, /* 8 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, '__esModule', { value: true }); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } var _react = __webpack_require__(2); var _react2 = _interopRequireDefault(_react); var _ReactDOM = __webpack_require__(6); var _ReactDOM2 = _interopRequireDefault(_ReactDOM); var _reactLibReactTransitionEvents = __webpack_require__(9); var _reactLibReactTransitionEvents2 = _interopRequireDefault(_reactLibReactTransitionEvents); var _trackHelper = __webpack_require__(5); var _objectAssign = __webpack_require__(11); var _objectAssign2 = _interopRequireDefault(_objectAssign); var helpers = { initialize: function initialize(props) { var slideCount = _react2['default'].Children.count(props.children); var listWidth = this.getWidth(_ReactDOM2['default'].findDOMNode(this.refs.list)); var trackWidth = this.getWidth(_ReactDOM2['default'].findDOMNode(this.refs.track)); var slideWidth = this.getWidth(_ReactDOM2['default'].findDOMNode(this)) / props.slidesToShow; var currentSlide = props.rtl ? slideCount - 1 - props.initialSlide : props.initialSlide; this.setState({ slideCount: slideCount, slideWidth: slideWidth, listWidth: listWidth, trackWidth: trackWidth, currentSlide: currentSlide }, function () { var targetLeft = (0, _trackHelper.getTrackLeft)((0, _objectAssign2['default'])({ slideIndex: this.state.currentSlide, trackRef: this.refs.track }, props, this.state)); // getCSS function needs previously set state var trackStyle = (0, _trackHelper.getTrackCSS)((0, _objectAssign2['default'])({ left: targetLeft }, props, this.state)); this.setState({ trackStyle: trackStyle }); this.autoPlay(); // once we're set up, trigger the initial autoplay. }); }, update: function update(props) { // This method has mostly same code as initialize method. // Refactor it var slideCount = _react2['default'].Children.count(props.children); var listWidth = this.getWidth(_ReactDOM2['default'].findDOMNode(this.refs.list)); var trackWidth = this.getWidth(_ReactDOM2['default'].findDOMNode(this.refs.track)); var slideWidth = this.getWidth(_ReactDOM2['default'].findDOMNode(this)) / props.slidesToShow; this.setState({ slideCount: slideCount, slideWidth: slideWidth, listWidth: listWidth, trackWidth: trackWidth }, function () { var targetLeft = (0, _trackHelper.getTrackLeft)((0, _objectAssign2['default'])({ slideIndex: this.state.currentSlide, trackRef: this.refs.track }, props, this.state)); // getCSS function needs previously set state var trackStyle = (0, _trackHelper.getTrackCSS)((0, _objectAssign2['default'])({ left: targetLeft }, props, this.state)); this.setState({ trackStyle: trackStyle }); }); }, getWidth: function getWidth(elem) { return elem.getBoundingClientRect().width || elem.offsetWidth; }, adaptHeight: function adaptHeight() { if (this.props.adaptiveHeight) { var selector = '[data-index="' + this.state.currentSlide + '"]'; if (this.refs.list) { var slickList = _ReactDOM2['default'].findDOMNode(this.refs.list); slickList.style.height = slickList.querySelector(selector).offsetHeight + 'px'; } } }, slideHandler: function slideHandler(index) { var _this = this; // Functionality of animateSlide and postSlide is merged into this function // console.log('slideHandler', index); var targetSlide, currentSlide; var targetLeft, currentLeft; var callback; if (this.props.waitForAnimate && this.state.animating) { return; } if (this.state.currentSlide === index) { return; } if (this.props.fade) { currentSlide = this.state.currentSlide; // Shifting targetSlide back into the range if (index < 0) { targetSlide = index + this.state.slideCount; } else if (index >= this.state.slideCount) { targetSlide = index - this.state.slideCount; } else { targetSlide = index; } if (this.props.lazyLoad && this.state.lazyLoadedList.indexOf(targetSlide) < 0) { this.setState({ lazyLoadedList: this.state.lazyLoadedList.concat(targetSlide) }); } callback = function () { _this.setState({ animating: false }); if (_this.props.afterChange) { _this.props.afterChange(currentSlide); } _reactLibReactTransitionEvents2['default'].removeEndEventListener(_ReactDOM2['default'].findDOMNode(_this.refs.track).children[currentSlide], callback); }; this.setState({ animating: true, currentSlide: targetSlide }, function () { _reactLibReactTransitionEvents2['default'].addEndEventListener(_ReactDOM2['default'].findDOMNode(this.refs.track).children[currentSlide], callback); }); if (this.props.beforeChange) { this.props.beforeChange(this.state.currentSlide, currentSlide); } this.autoPlay(); return; } targetSlide = index; if (targetSlide < 0) { if (this.props.infinite === false) { currentSlide = 0; } else if (this.state.slideCount % this.props.slidesToScroll !== 0) { currentSlide = this.state.slideCount - this.state.slideCount % this.props.slidesToScroll; } else { currentSlide = this.state.slideCount + targetSlide; } } else if (targetSlide >= this.state.slideCount) { if (this.props.infinite === false) { currentSlide = this.state.slideCount - this.props.slidesToShow; } else if (this.state.slideCount % this.props.slidesToScroll !== 0) { currentSlide = 0; } else { currentSlide = targetSlide - this.state.slideCount; } } else { currentSlide = targetSlide; } targetLeft = (0, _trackHelper.getTrackLeft)((0, _objectAssign2['default'])({ slideIndex: targetSlide, trackRef: this.refs.track }, this.props, this.state)); currentLeft = (0, _trackHelper.getTrackLeft)((0, _objectAssign2['default'])({ slideIndex: currentSlide, trackRef: this.refs.track }, this.props, this.state)); if (this.props.infinite === false) { targetLeft = currentLeft; } if (this.props.beforeChange) { this.props.beforeChange(this.state.currentSlide, currentSlide); } if (this.props.lazyLoad) { var loaded = true; var slidesToLoad = []; for (var i = targetSlide; i < targetSlide + this.props.slidesToShow; i++) { loaded = loaded && this.state.lazyLoadedList.indexOf(i) >= 0; if (!loaded) { slidesToLoad.push(i); } } if (!loaded) { this.setState({ lazyLoadedList: this.state.lazyLoadedList.concat(slidesToLoad) }); } } // Slide Transition happens here. // animated transition happens to target Slide and // non - animated transition happens to current Slide // If CSS transitions are false, directly go the current slide. if (this.props.useCSS === false) { this.setState({ currentSlide: currentSlide, trackStyle: (0, _trackHelper.getTrackCSS)((0, _objectAssign2['default'])({ left: currentLeft }, this.props, this.state)) }, function () { if (this.props.afterChange) { this.props.afterChange(currentSlide); } }); } else { var nextStateChanges = { animating: false, currentSlide: currentSlide, trackStyle: (0, _trackHelper.getTrackCSS)((0, _objectAssign2['default'])({ left: currentLeft }, this.props, this.state)), swipeLeft: null }; callback = function () { _this.setState(nextStateChanges); if (_this.props.afterChange) { _this.props.afterChange(currentSlide); } _reactLibReactTransitionEvents2['default'].removeEndEventListener(_ReactDOM2['default'].findDOMNode(_this.refs.track), callback); }; this.setState({ animating: true, currentSlide: targetSlide, trackStyle: (0, _trackHelper.getTrackAnimateCSS)((0, _objectAssign2['default'])({ left: targetLeft }, this.props, this.state)) }, function () { _reactLibReactTransitionEvents2['default'].addEndEventListener(_ReactDOM2['default'].findDOMNode(this.refs.track), callback); }); } this.autoPlay(); }, swipeDirection: function swipeDirection(touchObject) { var xDist, yDist, r, swipeAngle; xDist = touchObject.startX - touchObject.curX; yDist = touchObject.startY - touchObject.curY; r = Math.atan2(yDist, xDist); swipeAngle = Math.round(r * 180 / Math.PI); if (swipeAngle < 0) { swipeAngle = 360 - Math.abs(swipeAngle); } if (swipeAngle <= 45 && swipeAngle >= 0 || swipeAngle <= 360 && swipeAngle >= 315) { return this.props.rtl === false ? 'left' : 'right'; } if (swipeAngle >= 135 && swipeAngle <= 225) { return this.props.rtl === false ? 'right' : 'left'; } return 'vertical'; }, autoPlay: function autoPlay() { var _this2 = this; var play = function play() { if (_this2.state.mounted) { var nextIndex = _this2.props.rtl ? _this2.state.currentSlide - _this2.props.slidesToScroll : _this2.state.currentSlide + _this2.props.slidesToScroll; _this2.slideHandler(nextIndex); } }; if (this.props.autoplay) { window.clearTimeout(this.state.autoPlayTimer); this.setState({ autoPlayTimer: window.setTimeout(play, this.props.autoplaySpeed) }); } }, pause: function pause() { if (this.state.autoPlayTimer) { window.clearTimeout(this.state.autoPlayTimer); } } }; exports['default'] = helpers; module.exports = exports['default']; /***/ }, /* 9 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactTransitionEvents */ 'use strict'; var ExecutionEnvironment = __webpack_require__(10); /** * EVENT_NAME_MAP is used to determine which event fired when a * transition/animation ends, based on the style property used to * define that event. */ var EVENT_NAME_MAP = { transitionend: { 'transition': 'transitionend', 'WebkitTransition': 'webkitTransitionEnd', 'MozTransition': 'mozTransitionEnd', 'OTransition': 'oTransitionEnd', 'msTransition': 'MSTransitionEnd' }, animationend: { 'animation': 'animationend', 'WebkitAnimation': 'webkitAnimationEnd', 'MozAnimation': 'mozAnimationEnd', 'OAnimation': 'oAnimationEnd', 'msAnimation': 'MSAnimationEnd' } }; var endEvents = []; function detectEvents() { var testEl = document.createElement('div'); var style = testEl.style; // On some platforms, in particular some releases of Android 4.x, // the un-prefixed "animation" and "transition" properties are defined on the // style object but the events that fire will still be prefixed, so we need // to check if the un-prefixed events are useable, and if not remove them // from the map if (!('AnimationEvent' in window)) { delete EVENT_NAME_MAP.animationend.animation; } if (!('TransitionEvent' in window)) { delete EVENT_NAME_MAP.transitionend.transition; } for (var baseEventName in EVENT_NAME_MAP) { var baseEvents = EVENT_NAME_MAP[baseEventName]; for (var styleName in baseEvents) { if (styleName in style) { endEvents.push(baseEvents[styleName]); break; } } } } if (ExecutionEnvironment.canUseDOM) { detectEvents(); } // We use the raw {add|remove}EventListener() call because EventListener // does not know how to remove event listeners and we really should // clean up. Also, these events are not triggered in older browsers // so we should be A-OK here. function addEventListener(node, eventName, eventListener) { node.addEventListener(eventName, eventListener, false); } function removeEventListener(node, eventName, eventListener) { node.removeEventListener(eventName, eventListener, false); } var ReactTransitionEvents = { addEndEventListener: function (node, eventListener) { if (endEvents.length === 0) { // If CSS transitions are not supported, trigger an "end animation" // event immediately. window.setTimeout(eventListener, 0); return; } endEvents.forEach(function (endEvent) { addEventListener(node, endEvent, eventListener); }); }, removeEndEventListener: function (node, eventListener) { if (endEvents.length === 0) { return; } endEvents.forEach(function (endEvent) { removeEventListener(node, endEvent, eventListener); }); } }; module.exports = ReactTransitionEvents; /***/ }, /* 10 */ /***/ function(module, exports) { /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ExecutionEnvironment */ 'use strict'; var canUseDOM = !!(typeof window !== 'undefined' && window.document && window.document.createElement); /** * Simple, lightweight module assisting with the detection and context of * Worker. Helps avoid circular dependencies and allows code to reason about * whether or not they are in a Worker, even if they never include the main * `ReactWorker` dependency. */ var ExecutionEnvironment = { canUseDOM: canUseDOM, canUseWorkers: typeof Worker !== 'undefined', canUseEventListeners: canUseDOM && !!(window.addEventListener || window.attachEvent), canUseViewport: canUseDOM && !!window.screen, isInWorker: !canUseDOM // For now, this is true - might change in the future. }; module.exports = ExecutionEnvironment; /***/ }, /* 11 */ /***/ function(module, exports) { 'use strict'; function ToObject(val) { if (val == null) { throw new TypeError('Object.assign cannot be called with null or undefined'); } return Object(val); } module.exports = Object.assign || function (target, source) { var from; var keys; var to = ToObject(target); for (var s = 1; s < arguments.length; s++) { from = arguments[s]; keys = Object.keys(Object(from)); for (var i = 0; i < keys.length; i++) { to[keys[i]] = from[keys[i]]; } } return to; }; /***/ }, /* 12 */ /***/ function(module, exports) { "use strict"; var initialState = { animating: false, dragging: false, autoPlayTimer: null, currentDirection: 0, currentLeft: null, currentSlide: 0, direction: 1, // listWidth: null, // listHeight: null, // loadIndex: 0, slideCount: null, slideWidth: null, // sliding: false, // slideOffset: 0, swipeLeft: null, touchObject: { startX: 0, startY: 0, curX: 0, curY: 0 }, lazyLoadedList: [], // added for react initialized: false, edgeDragged: false, swiped: false, // used by swipeEvent. differentites between touch and swipe. trackStyle: {}, trackWidth: 0 // Removed // transformsEnabled: false, // $nextArrow: null, // $prevArrow: null, // $dots: null, // $list: null, // $slideTrack: null, // $slides: null, }; module.exports = initialState; /***/ }, /* 13 */ /***/ function(module, exports) { 'use strict'; var defaultProps = { className: '', // accessibility: true, adaptiveHeight: false, arrows: true, autoplay: false, autoplaySpeed: 3000, centerMode: false, centerPadding: '50px', cssEase: 'ease', dots: false, dotsClass: 'slick-dots', draggable: true, easing: 'linear', edgeFriction: 0.35, fade: false, focusOnSelect: false, infinite: true, initialSlide: 0, lazyLoad: false, pauseOnHover: false, responsive: null, rtl: false, slide: 'div', slidesToShow: 1, slidesToScroll: 1, speed: 500, swipe: true, swipeToSlide: false, touchMove: true, touchThreshold: 5, useCSS: true, variableWidth: false, vertical: false, waitForAnimate: true, afterChange: null, beforeChange: null, edgeEvent: null, init: null, swipeEvent: null, // nextArrow, prevArrow are react componets nextArrow: null, prevArrow: null }; module.exports = defaultProps; /***/ }, /* 14 */ /***/ function(module, exports, __webpack_require__) { var __WEBPACK_AMD_DEFINE_RESULT__;/*! Copyright (c) 2015 Jed Watson. Licensed under the MIT License (MIT), see http://jedwatson.github.io/classnames */ (function () { 'use strict'; function classNames () { var classes = ''; for (var i = 0; i < arguments.length; i++) { var arg = arguments[i]; if (!arg) continue; var argType = typeof arg; if ('string' === argType || 'number' === argType) { classes += ' ' + arg; } else if (Array.isArray(arg)) { classes += ' ' + classNames.apply(null, arg); } else if ('object' === argType) { for (var key in arg) { if (arg.hasOwnProperty(key) && arg[key]) { classes += ' ' + key; } } } } return classes.substr(1); } if (typeof module !== 'undefined' && module.exports) { module.exports = classNames; } else if (true){ // AMD. Register as an anonymous module. !(__WEBPACK_AMD_DEFINE_RESULT__ = function () { return classNames; }.call(exports, __webpack_require__, exports, module), __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__)); } else { window.classNames = classNames; } }()); /***/ }, /* 15 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, '__esModule', { value: true }); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } var _react = __webpack_require__(2); var _react2 = _interopRequireDefault(_react); var _objectAssign = __webpack_require__(11); var _objectAssign2 = _interopRequireDefault(_objectAssign); var _classnames = __webpack_require__(14); var _classnames2 = _interopRequireDefault(_classnames); var getSlideClasses = function getSlideClasses(spec) { var slickActive, slickCenter, slickCloned; var centerOffset, index; if (spec.rtl) { index = spec.slideCount - 1 - spec.index; } else { index = spec.index; } slickCloned = index < 0 || index >= spec.slideCount; if (spec.centerMode) { centerOffset = Math.floor(spec.slidesToShow / 2); slickCenter = (index - spec.currentSlide) % spec.slideCount === 0; if (index > spec.currentSlide - centerOffset - 1 && index <= spec.currentSlide + centerOffset) { slickActive = true; } } else { slickActive = spec.currentSlide <= index && index < spec.currentSlide + spec.slidesToShow; } return (0, _classnames2['default'])({ 'slick-slide': true, 'slick-active': slickActive, 'slick-center': slickCenter, 'slick-cloned': slickCloned }); }; var getSlideStyle = function getSlideStyle(spec) { var style = {}; if (spec.variableWidth === undefined || spec.variableWidth === false) { style.width = spec.slideWidth; } if (spec.fade) { style.position = 'relative'; style.left = -spec.index * spec.slideWidth; style.opacity = spec.currentSlide === spec.index ? 1 : 0; style.transition = 'opacity ' + spec.speed + 'ms ' + spec.cssEase; style.WebkitTransition = 'opacity ' + spec.speed + 'ms ' + spec.cssEase; } return style; }; var renderSlides = function renderSlides(spec) { var key; var slides = []; var preCloneSlides = []; var postCloneSlides = []; var count = _react2['default'].Children.count(spec.children); var child; _react2['default'].Children.forEach(spec.children, function (elem, index) { if (!spec.lazyLoad | (spec.lazyLoad && spec.lazyLoadedList.indexOf(index) >= 0)) { child = elem; } else { child = _react2['default'].createElement('div', null); } var childStyle = getSlideStyle((0, _objectAssign2['default'])({}, spec, { index: index })); var slickClasses = getSlideClasses((0, _objectAssign2['default'])({ index: index }, spec)); var cssClasses; if (child.props.className) { cssClasses = (0, _classnames2['default'])(slickClasses, child.props.className); } else { cssClasses = slickClasses; } slides.push(_react2['default'].cloneElement(child, { key: index, 'data-index': index, className: cssClasses, style: (0, _objectAssign2['default'])({}, child.props.style || {}, childStyle) })); // variableWidth doesn't wrap properly. if (spec.infinite && spec.fade === false) { var infiniteCount = spec.variableWidth ? spec.slidesToShow + 1 : spec.slidesToShow; if (index >= count - infiniteCount) { key = -(count - index); preCloneSlides.push(_react2['default'].cloneElement(child, { key: key, 'data-index': key, className: getSlideClasses((0, _objectAssign2['default'])({ index: key }, spec)), style: (0, _objectAssign2['default'])({}, child.props.style || {}, childStyle) })); } if (index < infiniteCount) { key = count + index; postCloneSlides.push(_react2['default'].cloneElement(child, { key: key, 'data-index': key, className: getSlideClasses((0, _objectAssign2['default'])({ index: key }, spec)), style: (0, _objectAssign2['default'])({}, child.props.style || {}, childStyle) })); } } }); if (spec.rtl) { return preCloneSlides.concat(slides, postCloneSlides).reverse(); } else { return preCloneSlides.concat(slides, postCloneSlides); } }; var Track = _react2['default'].createClass({ displayName: 'Track', render: function render() { var slides = renderSlides(this.props); return _react2['default'].createElement( 'div', { className: 'slick-track', style: this.props.trackStyle }, slides ); } }); exports.Track = Track; /***/ }, /* 16 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, '__esModule', { value: true }); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } var _react = __webpack_require__(2); var _react2 = _interopRequireDefault(_react); var _classnames = __webpack_require__(14); var _classnames2 = _interopRequireDefault(_classnames); var getDotCount = function getDotCount(spec) { var dots; dots = Math.ceil(spec.slideCount / spec.slidesToScroll); return dots; }; var Dots = _react2['default'].createClass({ displayName: 'Dots', clickHandler: function clickHandler(options, e) { // In Autoplay the focus stays on clicked button even after transition // to next slide. That only goes away by click somewhere outside e.preventDefault(); this.props.clickHandler(options); }, render: function render() { var _this = this; var dotCount = getDotCount({ slideCount: this.props.slideCount, slidesToScroll: this.props.slidesToScroll }); // Apply join & split to Array to pre-fill it for IE8 // // Credit: http://stackoverflow.com/a/13735425/1849458 var dots = Array.apply(null, Array(dotCount + 1).join('0').split('')).map(function (x, i) { var className = (0, _classnames2['default'])({ 'slick-active': _this.props.currentSlide === i * _this.props.slidesToScroll }); var dotOptions = { message: 'dots', index: i, slidesToScroll: _this.props.slidesToScroll, currentSlide: _this.props.currentSlide }; return _react2['default'].createElement( 'li', { key: i, className: className }, _react2['default'].createElement( 'button', { onClick: _this.clickHandler.bind(_this, dotOptions) }, i ) ); }); return _react2['default'].createElement( 'ul', { className: this.props.dotsClass, style: { display: 'block' } }, dots ); } }); exports.Dots = Dots; /***/ }, /* 17 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, '__esModule', { value: true }); var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } var _react = __webpack_require__(2); var _react2 = _interopRequireDefault(_react); var _classnames = __webpack_require__(14); var _classnames2 = _interopRequireDefault(_classnames); var PrevArrow = _react2['default'].createClass({ displayName: 'PrevArrow', clickHandler: function clickHandler(options, e) { e.preventDefault(); this.props.clickHandler(options, e); }, render: function render() { var prevClasses = { 'slick-prev': true }; var prevHandler = this.clickHandler.bind(this, { message: 'previous' }); if (!this.props.infinite && (this.props.currentSlide === 0 || this.props.slideCount <= this.props.slidesToShow)) { prevClasses['slick-disabled'] = true; prevHandler = null; } var prevArrowProps = { key: '0', ref: 'previous', 'data-role': 'none', className: (0, _classnames2['default'])(prevClasses), style: { display: 'block' }, onClick: prevHandler }; var prevArrow; if (this.props.prevArrow) { prevArrow = _react2['default'].createElement(this.props.prevArrow, prevArrowProps); } else { prevArrow = _react2['default'].createElement( 'button', _extends({ key: '0', type: 'button' }, prevArrowProps), ' Previous' ); } return prevArrow; } }); exports.PrevArrow = PrevArrow; var NextArrow = _react2['default'].createClass({ displayName: 'NextArrow', clickHandler: function clickHandler(options, e) { e.preventDefault(); this.props.clickHandler(options, e); }, render: function render() { var nextClasses = { 'slick-next': true }; var nextHandler = this.clickHandler.bind(this, { message: 'next' }); if (!this.props.infinite) { if (this.props.centerMode && this.props.currentSlide >= this.props.slideCount - 1) { nextClasses['slick-disabled'] = true; nextHandler = null; } else { if (this.props.currentSlide >= this.props.slideCount - this.props.slidesToShow) { nextClasses['slick-disabled'] = true; nextHandler = null; } } if (this.props.slideCount <= this.props.slidesToShow) { nextClasses['slick-disabled'] = true; nextHandler = null; } } var nextArrowProps = { key: '1', ref: 'next', 'data-role': 'none', className: (0, _classnames2['default'])(nextClasses), style: { display: 'block' }, onClick: nextHandler }; var nextArrow; if (this.props.nextArrow) { nextArrow = _react2['default'].createElement(this.props.nextArrow, nextArrowProps); } else { nextArrow = _react2['default'].createElement( 'button', _extends({ key: '1', type: 'button' }, nextArrowProps), ' Next' ); } return nextArrow; } }); exports.NextArrow = NextArrow; /***/ }, /* 18 */ /***/ function(module, exports, __webpack_require__) { var camel2hyphen = __webpack_require__(19); var isDimension = function (feature) { var re = /[height|width]$/; return re.test(feature); }; var obj2mq = function (obj) { var mq = ''; var features = Object.keys(obj); features.forEach(function (feature, index) { var value = obj[feature]; feature = camel2hyphen(feature); // Add px to dimension features if (isDimension(feature) && typeof value === 'number') { value = value + 'px'; } if (value === true) { mq += feature; } else if (value === false) { mq += 'not ' + feature; } else { mq += '(' + feature + ': ' + value + ')'; } if (index < features.length-1) { mq += ' and ' } }); return mq; }; var json2mq = function (query) { var mq = ''; if (typeof query === 'string') { return query; } // Handling array of media queries if (query instanceof Array) { query.forEach(function (q, index) { mq += obj2mq(q); if (index < query.length-1) { mq += ', ' } }); return mq; } // Handling single media query return obj2mq(query); }; module.exports = json2mq; /***/ }, /* 19 */ /***/ function(module, exports) { var camel2hyphen = function (str) { return str .replace(/[A-Z]/g, function (match) { return '-' + match.toLowerCase(); }) .toLowerCase(); }; module.exports = camel2hyphen; /***/ }, /* 20 */ /***/ function(module, exports, __webpack_require__) { var canUseDOM = __webpack_require__(21); var enquire = canUseDOM && __webpack_require__(22); var json2mq = __webpack_require__(18); var ResponsiveMixin = { media: function (query, handler) { query = json2mq(query); if (typeof handler === 'function') { handler = { match: handler }; } enquire.register(query, handler); // Queue the handlers to unregister them at unmount if (! this._responsiveMediaHandlers) { this._responsiveMediaHandlers = []; } this._responsiveMediaHandlers.push({query: query, handler: handler}); }, componentWillUnmount: function () { if (this._responsiveMediaHandlers) { this._responsiveMediaHandlers.forEach(function(obj) { enquire.unregister(obj.query, obj.handler); }); } } }; module.exports = ResponsiveMixin; /***/ }, /* 21 */ /***/ function(module, exports) { var canUseDOM = !!( typeof window !== 'undefined' && window.document && window.document.createElement ); module.exports = canUseDOM; /***/ }, /* 22 */ /***/ function(module, exports, __webpack_require__) { var __WEBPACK_AMD_DEFINE_RESULT__;/*! * enquire.js v2.1.1 - Awesome Media Queries in JavaScript * Copyright (c) 2014 Nick Williams - http://wicky.nillia.ms/enquire.js * License: MIT (http://www.opensource.org/licenses/mit-license.php) */ ;(function (name, context, factory) { var matchMedia = window.matchMedia; if (typeof module !== 'undefined' && module.exports) { module.exports = factory(matchMedia); } else if (true) { !(__WEBPACK_AMD_DEFINE_RESULT__ = function() { return (context[name] = factory(matchMedia)); }.call(exports, __webpack_require__, exports, module), __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__)); } else { context[name] = factory(matchMedia); } }('enquire', this, function (matchMedia) { 'use strict'; /*jshint unused:false */ /** * Helper function for iterating over a collection * * @param collection * @param fn */ function each(collection, fn) { var i = 0, length = collection.length, cont; for(i; i < length; i++) { cont = fn(collection[i], i); if(cont === false) { break; //allow early exit } } } /** * Helper function for determining whether target object is an array * * @param target the object under test * @return {Boolean} true if array, false otherwise */ function isArray(target) { return Object.prototype.toString.apply(target) === '[object Array]'; } /** * Helper function for determining whether target object is a function * * @param target the object under test * @return {Boolean} true if function, false otherwise */ function isFunction(target) { return typeof target === 'function'; } /** * Delegate to handle a media query being matched and unmatched. * * @param {object} options * @param {function} options.match callback for when the media query is matched * @param {function} [options.unmatch] callback for when the media query is unmatched * @param {function} [options.setup] one-time callback triggered the first time a query is matched * @param {boolean} [options.deferSetup=false] should the setup callback be run immediately, rather than first time query is matched? * @constructor */ function QueryHandler(options) { this.options = options; !options.deferSetup && this.setup(); } QueryHandler.prototype = { /** * coordinates setup of the handler * * @function */ setup : function() { if(this.options.setup) { this.options.setup(); } this.initialised = true; }, /** * coordinates setup and triggering of the handler * * @function */ on : function() { !this.initialised && this.setup(); this.options.match && this.options.match(); }, /** * coordinates the unmatch event for the handler * * @function */ off : function() { this.options.unmatch && this.options.unmatch(); }, /** * called when a handler is to be destroyed. * delegates to the destroy or unmatch callbacks, depending on availability. * * @function */ destroy : function() { this.options.destroy ? this.options.destroy() : this.off(); }, /** * determines equality by reference. * if object is supplied compare options, if function, compare match callback * * @function * @param {object || function} [target] the target for comparison */ equals : function(target) { return this.options === target || this.options.match === target; } }; /** * Represents a single media query, manages it's state and registered handlers for this query * * @constructor * @param {string} query the media query string * @param {boolean} [isUnconditional=false] whether the media query should run regardless of whether the conditions are met. Primarily for helping older browsers deal with mobile-first design */ function MediaQuery(query, isUnconditional) { this.query = query; this.isUnconditional = isUnconditional; this.handlers = []; this.mql = matchMedia(query); var self = this; this.listener = function(mql) { self.mql = mql; self.assess(); }; this.mql.addListener(this.listener); } MediaQuery.prototype = { /** * add a handler for this query, triggering if already active * * @param {object} handler * @param {function} handler.match callback for when query is activated * @param {function} [handler.unmatch] callback for when query is deactivated * @param {function} [handler.setup] callback for immediate execution when a query handler is registered * @param {boolean} [handler.deferSetup=false] should the setup callback be deferred until the first time the handler is matched? */ addHandler : function(handler) { var qh = new QueryHandler(handler); this.handlers.push(qh); this.matches() && qh.on(); }, /** * removes the given handler from the collection, and calls it's destroy methods * * @param {object || function} handler the handler to remove */ removeHandler : function(handler) { var handlers = this.handlers; each(handlers, function(h, i) { if(h.equals(handler)) { h.destroy(); return !handlers.splice(i,1); //remove from array and exit each early } }); }, /** * Determine whether the media query should be considered a match * * @return {Boolean} true if media query can be considered a match, false otherwise */ matches : function() { return this.mql.matches || this.isUnconditional; }, /** * Clears all handlers and unbinds events */ clear : function() { each(this.handlers, function(handler) { handler.destroy(); }); this.mql.removeListener(this.listener); this.handlers.length = 0; //clear array }, /* * Assesses the query, turning on all handlers if it matches, turning them off if it doesn't match */ assess : function() { var action = this.matches() ? 'on' : 'off'; each(this.handlers, function(handler) { handler[action](); }); } }; /** * Allows for registration of query handlers. * Manages the query handler's state and is responsible for wiring up browser events * * @constructor */ function MediaQueryDispatch () { if(!matchMedia) { throw new Error('matchMedia not present, legacy browsers require a polyfill'); } this.queries = {}; this.browserIsIncapable = !matchMedia('only all').matches; } MediaQueryDispatch.prototype = { /** * Registers a handler for the given media query * * @param {string} q the media query * @param {object || Array || Function} options either a single query handler object, a function, or an array of query handlers * @param {function} options.match fired when query matched * @param {function} [options.unmatch] fired when a query is no longer matched * @param {function} [options.setup] fired when handler first triggered * @param {boolean} [options.deferSetup=false] whether setup should be run immediately or deferred until query is first matched * @param {boolean} [shouldDegrade=false] whether this particular media query should always run on incapable browsers */ register : function(q, options, shouldDegrade) { var queries = this.queries, isUnconditional = shouldDegrade && this.browserIsIncapable; if(!queries[q]) { queries[q] = new MediaQuery(q, isUnconditional); } //normalise to object in an array if(isFunction(options)) { options = { match : options }; } if(!isArray(options)) { options = [options]; } each(options, function(handler) { queries[q].addHandler(handler); }); return this; }, /** * unregisters a query and all it's handlers, or a specific handler for a query * * @param {string} q the media query to target * @param {object || function} [handler] specific handler to unregister */ unregister : function(q, handler) { var query = this.queries[q]; if(query) { if(handler) { query.removeHandler(handler); } else { query.clear(); delete this.queries[q]; } } return this; } }; return new MediaQueryDispatch(); })); /***/ } /******/ ]) }); ;
ajax/libs/react-instantsearch/5.0.3/Dom.min.js
jonobr1/cdnjs
/*! ReactInstantSearch 5.0.3 | © Algolia, inc. | https://community.algolia.com/react-instantsearch */ !function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports,require("react")):"function"==typeof define&&define.amd?define(["exports","react"],t):t((e.ReactInstantSearch=e.ReactInstantSearch||{},e.ReactInstantSearch.Dom={}),e.React)}(this,function(e,t){"use strict";var r="default"in t?t.default:t,n="undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{};function i(){throw new Error("setTimeout has not been defined")}function a(){throw new Error("clearTimeout has not been defined")}var o=i,s=a;function c(e){if(o===setTimeout)return setTimeout(e,0);if((o===i||!o)&&setTimeout)return o=setTimeout,setTimeout(e,0);try{return o(e,0)}catch(t){try{return o.call(null,e,0)}catch(t){return o.call(this,e,0)}}}"function"==typeof n.setTimeout&&(o=setTimeout),"function"==typeof n.clearTimeout&&(s=clearTimeout);var u,l=[],f=!1,h=-1;function p(){f&&u&&(f=!1,u.length?l=u.concat(l):h=-1,l.length&&d())}function d(){if(!f){var e=c(p);f=!0;for(var t=l.length;t;){for(u=l,l=[];++h<t;)u&&u[h].run();h=-1,t=l.length}u=null,f=!1,function(e){if(s===clearTimeout)return clearTimeout(e);if((s===a||!s)&&clearTimeout)return s=clearTimeout,clearTimeout(e);try{s(e)}catch(t){try{return s.call(null,e)}catch(t){return s.call(this,e)}}}(e)}}function m(e){var t=new Array(arguments.length-1);if(arguments.length>1)for(var r=1;r<arguments.length;r++)t[r-1]=arguments[r];l.push(new v(e,t)),1!==l.length||f||c(d)}function v(e,t){this.fun=e,this.array=t}v.prototype.run=function(){this.fun.apply(null,this.array)};function g(){}var y=g,b=g,R=g,_=g,x=g,w=g,S=g;var j=n.performance||{},F=j.now||j.mozNow||j.msNow||j.oNow||j.webkitNow||function(){return(new Date).getTime()};var P=new Date;var N={nextTick:m,title:"browser",browser:!0,env:{},argv:[],version:"",versions:{},on:y,addListener:b,once:R,off:_,removeListener:x,removeAllListeners:w,emit:S,binding:function(e){throw new Error("process.binding is not supported")},cwd:function(){return"/"},chdir:function(e){throw new Error("process.chdir is not supported")},umask:function(){return 0},hrtime:function(e){var t=.001*F.call(j),r=Math.floor(t),n=Math.floor(t%1*1e9);return e&&(r-=e[0],(n-=e[1])<0&&(r--,n+=1e9)),[r,n]},platform:"browser",release:{},config:{},uptime:function(){return(new Date-P)/1e3}},E="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{};function O(e,t){return e(t={exports:{}},t.exports),t.exports}function T(e){return function(){return e}}var A=function(){};A.thatReturns=T,A.thatReturnsFalse=T(!1),A.thatReturnsTrue=T(!0),A.thatReturnsNull=T(null),A.thatReturnsThis=function(){return this},A.thatReturnsArgument=function(e){return e};var C=A;var I=function(e,t,r,n,i,a,o,s){if(!e){var c;if(void 0===t)c=new Error("Minified exception occurred; use the non-minified dev environment for the full error message and additional helpful warnings.");else{var u=[r,n,i,a,o,s],l=0;(c=new Error(t.replace(/%s/g,function(){return u[l++]}))).name="Invariant Violation"}throw c.framesToPop=1,c}},k=Object.getOwnPropertySymbols,q=Object.prototype.hasOwnProperty,M=Object.prototype.propertyIsEnumerable;(function(){try{if(!Object.assign)return!1;var e=new String("abc");if(e[5]="de","5"===Object.getOwnPropertyNames(e)[0])return!1;for(var t={},r=0;r<10;r++)t["_"+String.fromCharCode(r)]=r;if("0123456789"!==Object.getOwnPropertyNames(t).map(function(e){return t[e]}).join(""))return!1;var n={};return"abcdefghijklmnopqrst".split("").forEach(function(e){n[e]=e}),"abcdefghijklmnopqrst"===Object.keys(Object.assign({},n)).join("")}catch(e){return!1}})()&&Object.assign;var H="SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED",L=O(function(e){e.exports=function(){function e(e,t,r,n,i,a){a!==H&&I(!1,"Calling PropTypes validators directly is not supported by the `prop-types` package. Use PropTypes.checkPropTypes() to call them. Read more at http://fb.me/use-check-prop-types")}function t(){return e}e.isRequired=e;var r={array:e,bool:e,func:e,number:e,object:e,string:e,symbol:e,any:e,arrayOf:t,element:e,instanceOf:t,node:e,objectOf:t,oneOf:t,oneOfType:t,shape:t,exact:t};return r.checkPropTypes=C,r.PropTypes=r,r}()});var D=function(){this.__data__=[],this.size=0};var U=function(e,t){return e===t||e!=e&&t!=t};var B=function(e,t){for(var r=e.length;r--;)if(U(e[r][0],t))return r;return-1},Q=Array.prototype.splice;var z=function(e){var t=this.__data__,r=B(t,e);return!(r<0||(r==t.length-1?t.pop():Q.call(t,r,1),--this.size,0))};var V=function(e){var t=this.__data__,r=B(t,e);return r<0?void 0:t[r][1]};var W=function(e){return B(this.__data__,e)>-1};var J=function(e,t){var r=this.__data__,n=B(r,e);return n<0?(++this.size,r.push([e,t])):r[n][1]=t,this};function $(e){var t=-1,r=null==e?0:e.length;for(this.clear();++t<r;){var n=e[t];this.set(n[0],n[1])}}$.prototype.clear=D,$.prototype.delete=z,$.prototype.get=V,$.prototype.has=W,$.prototype.set=J;var K=$;var Y=function(){this.__data__=new K,this.size=0};var G=function(e){var t=this.__data__,r=t.delete(e);return this.size=t.size,r};var X=function(e){return this.__data__.get(e)};var Z=function(e){return this.__data__.has(e)},ee="object"==typeof E&&E&&E.Object===Object&&E,te="object"==typeof self&&self&&self.Object===Object&&self,re=ee||te||Function("return this")(),ne=re.Symbol,ie=Object.prototype,ae=ie.hasOwnProperty,oe=ie.toString,se=ne?ne.toStringTag:void 0;var ce=function(e){var t=ae.call(e,se),r=e[se];try{e[se]=void 0;var n=!0}catch(e){}var i=oe.call(e);return n&&(t?e[se]=r:delete e[se]),i},ue=Object.prototype.toString;var le=function(e){return ue.call(e)},fe="[object Null]",he="[object Undefined]",pe=ne?ne.toStringTag:void 0;var de=function(e){return null==e?void 0===e?he:fe:pe&&pe in Object(e)?ce(e):le(e)};var me=function(e){var t=typeof e;return null!=e&&("object"==t||"function"==t)},ve="[object AsyncFunction]",ge="[object Function]",ye="[object GeneratorFunction]",be="[object Proxy]";var Re,_e=function(e){if(!me(e))return!1;var t=de(e);return t==ge||t==ye||t==ve||t==be},xe=re["__core-js_shared__"],we=(Re=/[^.]+$/.exec(xe&&xe.keys&&xe.keys.IE_PROTO||""))?"Symbol(src)_1."+Re:"";var Se=function(e){return!!we&&we in e},je=Function.prototype.toString;var Fe=function(e){if(null!=e){try{return je.call(e)}catch(e){}try{return e+""}catch(e){}}return""},Pe=/^\[object .+?Constructor\]$/,Ne=Function.prototype,Ee=Object.prototype,Oe=Ne.toString,Te=Ee.hasOwnProperty,Ae=RegExp("^"+Oe.call(Te).replace(/[\\^$.*+?()[\]{}|]/g,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$");var Ce=function(e){return!(!me(e)||Se(e))&&(_e(e)?Ae:Pe).test(Fe(e))};var Ie=function(e,t){return null==e?void 0:e[t]};var ke=function(e,t){var r=Ie(e,t);return Ce(r)?r:void 0},qe=ke(re,"Map"),Me=ke(Object,"create");var He=function(){this.__data__=Me?Me(null):{},this.size=0};var Le=function(e){var t=this.has(e)&&delete this.__data__[e];return this.size-=t?1:0,t},De="__lodash_hash_undefined__",Ue=Object.prototype.hasOwnProperty;var Be=function(e){var t=this.__data__;if(Me){var r=t[e];return r===De?void 0:r}return Ue.call(t,e)?t[e]:void 0},Qe=Object.prototype.hasOwnProperty;var ze=function(e){var t=this.__data__;return Me?void 0!==t[e]:Qe.call(t,e)},Ve="__lodash_hash_undefined__";var We=function(e,t){var r=this.__data__;return this.size+=this.has(e)?0:1,r[e]=Me&&void 0===t?Ve:t,this};function Je(e){var t=-1,r=null==e?0:e.length;for(this.clear();++t<r;){var n=e[t];this.set(n[0],n[1])}}Je.prototype.clear=He,Je.prototype.delete=Le,Je.prototype.get=Be,Je.prototype.has=ze,Je.prototype.set=We;var $e=Je;var Ke=function(){this.size=0,this.__data__={hash:new $e,map:new(qe||K),string:new $e}};var Ye=function(e){var t=typeof e;return"string"==t||"number"==t||"symbol"==t||"boolean"==t?"__proto__"!==e:null===e};var Ge=function(e,t){var r=e.__data__;return Ye(t)?r["string"==typeof t?"string":"hash"]:r.map};var Xe=function(e){var t=Ge(this,e).delete(e);return this.size-=t?1:0,t};var Ze=function(e){return Ge(this,e).get(e)};var et=function(e){return Ge(this,e).has(e)};var tt=function(e,t){var r=Ge(this,e),n=r.size;return r.set(e,t),this.size+=r.size==n?0:1,this};function rt(e){var t=-1,r=null==e?0:e.length;for(this.clear();++t<r;){var n=e[t];this.set(n[0],n[1])}}rt.prototype.clear=Ke,rt.prototype.delete=Xe,rt.prototype.get=Ze,rt.prototype.has=et,rt.prototype.set=tt;var nt=rt,it=200;var at=function(e,t){var r=this.__data__;if(r instanceof K){var n=r.__data__;if(!qe||n.length<it-1)return n.push([e,t]),this.size=++r.size,this;r=this.__data__=new nt(n)}return r.set(e,t),this.size=r.size,this};function ot(e){var t=this.__data__=new K(e);this.size=t.size}ot.prototype.clear=Y,ot.prototype.delete=G,ot.prototype.get=X,ot.prototype.has=Z,ot.prototype.set=at;var st=ot,ct="__lodash_hash_undefined__";var ut=function(e){return this.__data__.set(e,ct),this};var lt=function(e){return this.__data__.has(e)};function ft(e){var t=-1,r=null==e?0:e.length;for(this.__data__=new nt;++t<r;)this.add(e[t])}ft.prototype.add=ft.prototype.push=ut,ft.prototype.has=lt;var ht=ft;var pt=function(e,t){for(var r=-1,n=null==e?0:e.length;++r<n;)if(t(e[r],r,e))return!0;return!1};var dt=function(e,t){return e.has(t)},mt=1,vt=2;var gt=function(e,t,r,n,i,a){var o=r&mt,s=e.length,c=t.length;if(s!=c&&!(o&&c>s))return!1;var u=a.get(e);if(u&&a.get(t))return u==t;var l=-1,f=!0,h=r&vt?new ht:void 0;for(a.set(e,t),a.set(t,e);++l<s;){var p=e[l],d=t[l];if(n)var m=o?n(d,p,l,t,e,a):n(p,d,l,e,t,a);if(void 0!==m){if(m)continue;f=!1;break}if(h){if(!pt(t,function(e,t){if(!dt(h,t)&&(p===e||i(p,e,r,n,a)))return h.push(t)})){f=!1;break}}else if(p!==d&&!i(p,d,r,n,a)){f=!1;break}}return a.delete(e),a.delete(t),f},yt=re.Uint8Array;var bt=function(e){var t=-1,r=Array(e.size);return e.forEach(function(e,n){r[++t]=[n,e]}),r};var Rt=function(e){var t=-1,r=Array(e.size);return e.forEach(function(e){r[++t]=e}),r},_t=1,xt=2,wt="[object Boolean]",St="[object Date]",jt="[object Error]",Ft="[object Map]",Pt="[object Number]",Nt="[object RegExp]",Et="[object Set]",Ot="[object String]",Tt="[object Symbol]",At="[object ArrayBuffer]",Ct="[object DataView]",It=ne?ne.prototype:void 0,kt=It?It.valueOf:void 0;var qt=function(e,t,r,n,i,a,o){switch(r){case Ct:if(e.byteLength!=t.byteLength||e.byteOffset!=t.byteOffset)return!1;e=e.buffer,t=t.buffer;case At:return!(e.byteLength!=t.byteLength||!a(new yt(e),new yt(t)));case wt:case St:case Pt:return U(+e,+t);case jt:return e.name==t.name&&e.message==t.message;case Nt:case Ot:return e==t+"";case Ft:var s=bt;case Et:var c=n&_t;if(s||(s=Rt),e.size!=t.size&&!c)return!1;var u=o.get(e);if(u)return u==t;n|=xt,o.set(e,t);var l=gt(s(e),s(t),n,i,a,o);return o.delete(e),l;case Tt:if(kt)return kt.call(e)==kt.call(t)}return!1};var Mt=function(e,t){for(var r=-1,n=t.length,i=e.length;++r<n;)e[i+r]=t[r];return e},Ht=Array.isArray;var Lt=function(e,t,r){var n=t(e);return Ht(e)?n:Mt(n,r(e))};var Dt=function(e,t){for(var r=-1,n=null==e?0:e.length,i=0,a=[];++r<n;){var o=e[r];t(o,r,e)&&(a[i++]=o)}return a};var Ut=function(){return[]},Bt=Object.prototype.propertyIsEnumerable,Qt=Object.getOwnPropertySymbols,zt=Qt?function(e){return null==e?[]:(e=Object(e),Dt(Qt(e),function(t){return Bt.call(e,t)}))}:Ut;var Vt=function(e,t){for(var r=-1,n=Array(e);++r<e;)n[r]=t(r);return n};var Wt=function(e){return null!=e&&"object"==typeof e},Jt="[object Arguments]";var $t=function(e){return Wt(e)&&de(e)==Jt},Kt=Object.prototype,Yt=Kt.hasOwnProperty,Gt=Kt.propertyIsEnumerable,Xt=$t(function(){return arguments}())?$t:function(e){return Wt(e)&&Yt.call(e,"callee")&&!Gt.call(e,"callee")};var Zt=function(){return!1},er=O(function(e,t){var r=t&&!t.nodeType&&t,n=r&&e&&!e.nodeType&&e,i=n&&n.exports===r?re.Buffer:void 0,a=(i?i.isBuffer:void 0)||Zt;e.exports=a}),tr=9007199254740991,rr=/^(?:0|[1-9]\d*)$/;var nr=function(e,t){var r=typeof e;return!!(t=null==t?tr:t)&&("number"==r||"symbol"!=r&&rr.test(e))&&e>-1&&e%1==0&&e<t},ir=9007199254740991;var ar=function(e){return"number"==typeof e&&e>-1&&e%1==0&&e<=ir},or={};or["[object Float32Array]"]=or["[object Float64Array]"]=or["[object Int8Array]"]=or["[object Int16Array]"]=or["[object Int32Array]"]=or["[object Uint8Array]"]=or["[object Uint8ClampedArray]"]=or["[object Uint16Array]"]=or["[object Uint32Array]"]=!0,or["[object Arguments]"]=or["[object Array]"]=or["[object ArrayBuffer]"]=or["[object Boolean]"]=or["[object DataView]"]=or["[object Date]"]=or["[object Error]"]=or["[object Function]"]=or["[object Map]"]=or["[object Number]"]=or["[object Object]"]=or["[object RegExp]"]=or["[object Set]"]=or["[object String]"]=or["[object WeakMap]"]=!1;var sr=function(e){return Wt(e)&&ar(e.length)&&!!or[de(e)]};var cr=function(e){return function(t){return e(t)}},ur=O(function(e,t){var r=t&&!t.nodeType&&t,n=r&&e&&!e.nodeType&&e,i=n&&n.exports===r&&ee.process,a=function(){try{return i&&i.binding&&i.binding("util")}catch(e){}}();e.exports=a}),lr=ur&&ur.isTypedArray,fr=lr?cr(lr):sr,hr=Object.prototype.hasOwnProperty;var pr=function(e,t){var r=Ht(e),n=!r&&Xt(e),i=!r&&!n&&er(e),a=!r&&!n&&!i&&fr(e),o=r||n||i||a,s=o?Vt(e.length,String):[],c=s.length;for(var u in e)!t&&!hr.call(e,u)||o&&("length"==u||i&&("offset"==u||"parent"==u)||a&&("buffer"==u||"byteLength"==u||"byteOffset"==u)||nr(u,c))||s.push(u);return s},dr=Object.prototype;var mr=function(e){var t=e&&e.constructor;return e===("function"==typeof t&&t.prototype||dr)};var vr=function(e,t){return function(r){return e(t(r))}},gr=vr(Object.keys,Object),yr=Object.prototype.hasOwnProperty;var br=function(e){if(!mr(e))return gr(e);var t=[];for(var r in Object(e))yr.call(e,r)&&"constructor"!=r&&t.push(r);return t};var Rr=function(e){return null!=e&&ar(e.length)&&!_e(e)};var _r=function(e){return Rr(e)?pr(e):br(e)};var xr=function(e){return Lt(e,_r,zt)},wr=1,Sr=Object.prototype.hasOwnProperty;var jr=function(e,t,r,n,i,a){var o=r&wr,s=xr(e),c=s.length;if(c!=xr(t).length&&!o)return!1;for(var u=c;u--;){var l=s[u];if(!(o?l in t:Sr.call(t,l)))return!1}var f=a.get(e);if(f&&a.get(t))return f==t;var h=!0;a.set(e,t),a.set(t,e);for(var p=o;++u<c;){var d=e[l=s[u]],m=t[l];if(n)var v=o?n(m,d,l,t,e,a):n(d,m,l,e,t,a);if(!(void 0===v?d===m||i(d,m,r,n,a):v)){h=!1;break}p||(p="constructor"==l)}if(h&&!p){var g=e.constructor,y=t.constructor;g!=y&&"constructor"in e&&"constructor"in t&&!("function"==typeof g&&g instanceof g&&"function"==typeof y&&y instanceof y)&&(h=!1)}return a.delete(e),a.delete(t),h},Fr=ke(re,"DataView"),Pr=ke(re,"Promise"),Nr=ke(re,"Set"),Er=ke(re,"WeakMap"),Or=Fe(Fr),Tr=Fe(qe),Ar=Fe(Pr),Cr=Fe(Nr),Ir=Fe(Er),kr=de;(Fr&&"[object DataView]"!=kr(new Fr(new ArrayBuffer(1)))||qe&&"[object Map]"!=kr(new qe)||Pr&&"[object Promise]"!=kr(Pr.resolve())||Nr&&"[object Set]"!=kr(new Nr)||Er&&"[object WeakMap]"!=kr(new Er))&&(kr=function(e){var t=de(e),r="[object Object]"==t?e.constructor:void 0,n=r?Fe(r):"";if(n)switch(n){case Or:return"[object DataView]";case Tr:return"[object Map]";case Ar:return"[object Promise]";case Cr:return"[object Set]";case Ir:return"[object WeakMap]"}return t});var qr=kr,Mr=1,Hr="[object Arguments]",Lr="[object Array]",Dr="[object Object]",Ur=Object.prototype.hasOwnProperty;var Br=function(e,t,r,n,i,a){var o=Ht(e),s=Ht(t),c=o?Lr:qr(e),u=s?Lr:qr(t),l=(c=c==Hr?Dr:c)==Dr,f=(u=u==Hr?Dr:u)==Dr,h=c==u;if(h&&er(e)){if(!er(t))return!1;o=!0,l=!1}if(h&&!l)return a||(a=new st),o||fr(e)?gt(e,t,r,n,i,a):qt(e,t,c,r,n,i,a);if(!(r&Mr)){var p=l&&Ur.call(e,"__wrapped__"),d=f&&Ur.call(t,"__wrapped__");if(p||d){var m=p?e.value():e,v=d?t.value():t;return a||(a=new st),i(m,v,r,n,a)}}return!!h&&(a||(a=new st),jr(e,t,r,n,i,a))};var Qr=function e(t,r,n,i,a){return t===r||(null==t||null==r||!Wt(t)&&!Wt(r)?t!=t&&r!=r:Br(t,r,n,i,e,a))},zr=1,Vr=2;var Wr=function(e,t,r,n){var i=r.length,a=i,o=!n;if(null==e)return!a;for(e=Object(e);i--;){var s=r[i];if(o&&s[2]?s[1]!==e[s[0]]:!(s[0]in e))return!1}for(;++i<a;){var c=(s=r[i])[0],u=e[c],l=s[1];if(o&&s[2]){if(void 0===u&&!(c in e))return!1}else{var f=new st;if(n)var h=n(u,l,c,e,t,f);if(!(void 0===h?Qr(l,u,zr|Vr,n,f):h))return!1}}return!0};var Jr=function(e){return e==e&&!me(e)};var $r=function(e){for(var t=_r(e),r=t.length;r--;){var n=t[r],i=e[n];t[r]=[n,i,Jr(i)]}return t};var Kr=function(e,t){return function(r){return null!=r&&r[e]===t&&(void 0!==t||e in Object(r))}};var Yr=function(e){var t=$r(e);return 1==t.length&&t[0][2]?Kr(t[0][0],t[0][1]):function(r){return r===e||Wr(r,e,t)}},Gr="[object Symbol]";var Xr=function(e){return"symbol"==typeof e||Wt(e)&&de(e)==Gr},Zr=/\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/,en=/^\w*$/;var tn=function(e,t){if(Ht(e))return!1;var r=typeof e;return!("number"!=r&&"symbol"!=r&&"boolean"!=r&&null!=e&&!Xr(e))||en.test(e)||!Zr.test(e)||null!=t&&e in Object(t)},rn="Expected a function";function nn(e,t){if("function"!=typeof e||null!=t&&"function"!=typeof t)throw new TypeError(rn);var r=function(){var n=arguments,i=t?t.apply(this,n):n[0],a=r.cache;if(a.has(i))return a.get(i);var o=e.apply(this,n);return r.cache=a.set(i,o)||a,o};return r.cache=new(nn.Cache||nt),r}nn.Cache=nt;var an=nn,on=500;var sn=/[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g,cn=/\\(\\)?/g,un=function(e){var t=an(e,function(e){return r.size===on&&r.clear(),e}),r=t.cache;return t}(function(e){var t=[];return 46===e.charCodeAt(0)&&t.push(""),e.replace(sn,function(e,r,n,i){t.push(n?i.replace(cn,"$1"):r||e)}),t});var ln=function(e,t){for(var r=-1,n=null==e?0:e.length,i=Array(n);++r<n;)i[r]=t(e[r],r,e);return i},fn=1/0,hn=ne?ne.prototype:void 0,pn=hn?hn.toString:void 0;var dn=function e(t){if("string"==typeof t)return t;if(Ht(t))return ln(t,e)+"";if(Xr(t))return pn?pn.call(t):"";var r=t+"";return"0"==r&&1/t==-fn?"-0":r};var mn=function(e){return null==e?"":dn(e)};var vn=function(e,t){return Ht(e)?e:tn(e,t)?[e]:un(mn(e))},gn=1/0;var yn=function(e){if("string"==typeof e||Xr(e))return e;var t=e+"";return"0"==t&&1/e==-gn?"-0":t};var bn=function(e,t){for(var r=0,n=(t=vn(t,e)).length;null!=e&&r<n;)e=e[yn(t[r++])];return r&&r==n?e:void 0};var Rn=function(e,t,r){var n=null==e?void 0:bn(e,t);return void 0===n?r:n};var _n=function(e,t){return null!=e&&t in Object(e)};var xn=function(e,t,r){for(var n=-1,i=(t=vn(t,e)).length,a=!1;++n<i;){var o=yn(t[n]);if(!(a=null!=e&&r(e,o)))break;e=e[o]}return a||++n!=i?a:!!(i=null==e?0:e.length)&&ar(i)&&nr(o,i)&&(Ht(e)||Xt(e))};var wn=function(e,t){return null!=e&&xn(e,t,_n)},Sn=1,jn=2;var Fn=function(e,t){return tn(e)&&Jr(t)?Kr(yn(e),t):function(r){var n=Rn(r,e);return void 0===n&&n===t?wn(r,e):Qr(t,n,Sn|jn)}};var Pn=function(e){return e};var Nn=function(e){return function(t){return null==t?void 0:t[e]}};var En=function(e){return function(t){return bn(t,e)}};var On=function(e){return tn(e)?Nn(yn(e)):En(e)};var Tn=function(e){return"function"==typeof e?e:null==e?Pn:"object"==typeof e?Ht(e)?Fn(e[0],e[1]):Yr(e):On(e)};var An=function(e){return function(t,r,n){var i=Object(t);if(!Rr(t)){var a=Tn(r,3);t=_r(t),r=function(e){return a(i[e],e,i)}}var o=e(t,r,n);return o>-1?i[a?t[o]:o]:void 0}};var Cn=function(e,t,r,n){for(var i=e.length,a=r+(n?1:-1);n?a--:++a<i;)if(t(e[a],a,e))return a;return-1},In=NaN,kn=/^\s+|\s+$/g,qn=/^[-+]0x[0-9a-f]+$/i,Mn=/^0b[01]+$/i,Hn=/^0o[0-7]+$/i,Ln=parseInt;var Dn=function(e){if("number"==typeof e)return e;if(Xr(e))return In;if(me(e)){var t="function"==typeof e.valueOf?e.valueOf():e;e=me(t)?t+"":t}if("string"!=typeof e)return 0===e?e:+e;e=e.replace(kn,"");var r=Mn.test(e);return r||Hn.test(e)?Ln(e.slice(2),r?2:8):qn.test(e)?In:+e},Un=1/0,Bn=1.7976931348623157e308;var Qn=function(e){return e?(e=Dn(e))===Un||e===-Un?(e<0?-1:1)*Bn:e==e?e:0:0===e?e:0};var zn=function(e){var t=Qn(e),r=t%1;return t==t?r?t-r:t:0},Vn=Math.max;var Wn=function(e,t,r){var n=null==e?0:e.length;if(!n)return-1;var i=null==r?0:zn(r);return i<0&&(i=Vn(n+i,0)),Cn(e,Tn(t,3),i)},Jn=An(Wn),$n="[object Map]",Kn="[object Set]",Yn=Object.prototype.hasOwnProperty;var Gn=function(e){if(null==e)return!0;if(Rr(e)&&(Ht(e)||"string"==typeof e||"function"==typeof e.splice||er(e)||fr(e)||Xt(e)))return!e.length;var t=qr(e);if(t==$n||t==Kn)return!e.size;if(mr(e))return!br(e).length;for(var r in e)if(Yn.call(e,r))return!1;return!0};var Xn=function(e,t){for(var r=-1,n=null==e?0:e.length;++r<n&&!1!==t(e[r],r,e););return e},Zn=function(){try{var e=ke(Object,"defineProperty");return e({},"",{}),e}catch(e){}}();var ei=function(e,t,r){"__proto__"==t&&Zn?Zn(e,t,{configurable:!0,enumerable:!0,value:r,writable:!0}):e[t]=r},ti=Object.prototype.hasOwnProperty;var ri=function(e,t,r){var n=e[t];ti.call(e,t)&&U(n,r)&&(void 0!==r||t in e)||ei(e,t,r)};var ni=function(e,t,r,n){var i=!r;r||(r={});for(var a=-1,o=t.length;++a<o;){var s=t[a],c=n?n(r[s],e[s],s,r,e):void 0;void 0===c&&(c=e[s]),i?ei(r,s,c):ri(r,s,c)}return r};var ii=function(e,t){return e&&ni(t,_r(t),e)};var ai=function(e){var t=[];if(null!=e)for(var r in Object(e))t.push(r);return t},oi=Object.prototype.hasOwnProperty;var si=function(e){if(!me(e))return ai(e);var t=mr(e),r=[];for(var n in e)("constructor"!=n||!t&&oi.call(e,n))&&r.push(n);return r};var ci=function(e){return Rr(e)?pr(e,!0):si(e)};var ui=function(e,t){return e&&ni(t,ci(t),e)},li=O(function(e,t){var r=t&&!t.nodeType&&t,n=r&&e&&!e.nodeType&&e,i=n&&n.exports===r?re.Buffer:void 0,a=i?i.allocUnsafe:void 0;e.exports=function(e,t){if(t)return e.slice();var r=e.length,n=a?a(r):new e.constructor(r);return e.copy(n),n}});var fi=function(e,t){var r=-1,n=e.length;for(t||(t=Array(n));++r<n;)t[r]=e[r];return t};var hi=function(e,t){return ni(e,zt(e),t)},pi=vr(Object.getPrototypeOf,Object),di=Object.getOwnPropertySymbols?function(e){for(var t=[];e;)Mt(t,zt(e)),e=pi(e);return t}:Ut;var mi=function(e,t){return ni(e,di(e),t)};var vi=function(e){return Lt(e,ci,di)},gi=Object.prototype.hasOwnProperty;var yi=function(e){var t=e.length,r=new e.constructor(t);return t&&"string"==typeof e[0]&&gi.call(e,"index")&&(r.index=e.index,r.input=e.input),r};var bi=function(e){var t=new e.constructor(e.byteLength);return new yt(t).set(new yt(e)),t};var Ri=function(e,t){var r=t?bi(e.buffer):e.buffer;return new e.constructor(r,e.byteOffset,e.byteLength)},_i=/\w*$/;var xi=function(e){var t=new e.constructor(e.source,_i.exec(e));return t.lastIndex=e.lastIndex,t},wi=ne?ne.prototype:void 0,Si=wi?wi.valueOf:void 0;var ji=function(e){return Si?Object(Si.call(e)):{}};var Fi=function(e,t){var r=t?bi(e.buffer):e.buffer;return new e.constructor(r,e.byteOffset,e.length)},Pi="[object Boolean]",Ni="[object Date]",Ei="[object Map]",Oi="[object Number]",Ti="[object RegExp]",Ai="[object Set]",Ci="[object String]",Ii="[object Symbol]",ki="[object ArrayBuffer]",qi="[object DataView]",Mi="[object Float32Array]",Hi="[object Float64Array]",Li="[object Int8Array]",Di="[object Int16Array]",Ui="[object Int32Array]",Bi="[object Uint8Array]",Qi="[object Uint8ClampedArray]",zi="[object Uint16Array]",Vi="[object Uint32Array]";var Wi=function(e,t,r){var n=e.constructor;switch(t){case ki:return bi(e);case Pi:case Ni:return new n(+e);case qi:return Ri(e,r);case Mi:case Hi:case Li:case Di:case Ui:case Bi:case Qi:case zi:case Vi:return Fi(e,r);case Ei:return new n;case Oi:case Ci:return new n(e);case Ti:return xi(e);case Ai:return new n;case Ii:return ji(e)}},Ji=Object.create,$i=function(){function e(){}return function(t){if(!me(t))return{};if(Ji)return Ji(t);e.prototype=t;var r=new e;return e.prototype=void 0,r}}();var Ki=function(e){return"function"!=typeof e.constructor||mr(e)?{}:$i(pi(e))},Yi="[object Map]";var Gi=function(e){return Wt(e)&&qr(e)==Yi},Xi=ur&&ur.isMap,Zi=Xi?cr(Xi):Gi,ea="[object Set]";var ta=function(e){return Wt(e)&&qr(e)==ea},ra=ur&&ur.isSet,na=ra?cr(ra):ta,ia=1,aa=2,oa=4,sa="[object Arguments]",ca="[object Function]",ua="[object GeneratorFunction]",la="[object Object]",fa={};fa[sa]=fa["[object Array]"]=fa["[object ArrayBuffer]"]=fa["[object DataView]"]=fa["[object Boolean]"]=fa["[object Date]"]=fa["[object Float32Array]"]=fa["[object Float64Array]"]=fa["[object Int8Array]"]=fa["[object Int16Array]"]=fa["[object Int32Array]"]=fa["[object Map]"]=fa["[object Number]"]=fa[la]=fa["[object RegExp]"]=fa["[object Set]"]=fa["[object String]"]=fa["[object Symbol]"]=fa["[object Uint8Array]"]=fa["[object Uint8ClampedArray]"]=fa["[object Uint16Array]"]=fa["[object Uint32Array]"]=!0,fa["[object Error]"]=fa[ca]=fa["[object WeakMap]"]=!1;var ha=function e(t,r,n,i,a,o){var s,c=r&ia,u=r&aa,l=r&oa;if(n&&(s=a?n(t,i,a,o):n(t)),void 0!==s)return s;if(!me(t))return t;var f=Ht(t);if(f){if(s=yi(t),!c)return fi(t,s)}else{var h=qr(t),p=h==ca||h==ua;if(er(t))return li(t,c);if(h==la||h==sa||p&&!a){if(s=u||p?{}:Ki(t),!c)return u?mi(t,ui(s,t)):hi(t,ii(s,t))}else{if(!fa[h])return a?t:{};s=Wi(t,h,c)}}o||(o=new st);var d=o.get(t);if(d)return d;if(o.set(t,s),na(t))return t.forEach(function(i){s.add(e(i,r,n,i,t,o))}),s;if(Zi(t))return t.forEach(function(i,a){s.set(a,e(i,r,n,a,t,o))}),s;var m=l?u?vi:xr:u?keysIn:_r,v=f?void 0:m(t);return Xn(v||t,function(i,a){v&&(i=t[a=i]),ri(s,a,e(i,r,n,a,t,o))}),s};var pa=function(e){var t=null==e?0:e.length;return t?e[t-1]:void 0};var da=function(e,t,r){var n=-1,i=e.length;t<0&&(t=-t>i?0:i+t),(r=r>i?i:r)<0&&(r+=i),i=t>r?0:r-t>>>0,t>>>=0;for(var a=Array(i);++n<i;)a[n]=e[n+t];return a};var ma=function(e,t){return t.length<2?e:bn(e,da(t,0,-1))};var va=function(e,t){return t=vn(t,e),null==(e=ma(e,t))||delete e[yn(pa(t))]},ga="[object Object]",ya=Function.prototype,ba=Object.prototype,Ra=ya.toString,_a=ba.hasOwnProperty,xa=Ra.call(Object);var wa=function(e){if(!Wt(e)||de(e)!=ga)return!1;var t=pi(e);if(null===t)return!0;var r=_a.call(t,"constructor")&&t.constructor;return"function"==typeof r&&r instanceof r&&Ra.call(r)==xa};var Sa=function(e){return wa(e)?void 0:e},ja=ne?ne.isConcatSpreadable:void 0;var Fa=function(e){return Ht(e)||Xt(e)||!!(ja&&e&&e[ja])};var Pa=function e(t,r,n,i,a){var o=-1,s=t.length;for(n||(n=Fa),a||(a=[]);++o<s;){var c=t[o];r>0&&n(c)?r>1?e(c,r-1,n,i,a):Mt(a,c):i||(a[a.length]=c)}return a};var Na=function(e){return null!=e&&e.length?Pa(e,1):[]};var Ea=function(e,t,r){switch(r.length){case 0:return e.call(t);case 1:return e.call(t,r[0]);case 2:return e.call(t,r[0],r[1]);case 3:return e.call(t,r[0],r[1],r[2])}return e.apply(t,r)},Oa=Math.max;var Ta=function(e,t,r){return t=Oa(void 0===t?e.length-1:t,0),function(){for(var n=arguments,i=-1,a=Oa(n.length-t,0),o=Array(a);++i<a;)o[i]=n[t+i];i=-1;for(var s=Array(t+1);++i<t;)s[i]=n[i];return s[t]=r(o),Ea(e,this,s)}};var Aa=function(e){return function(){return e}},Ca=Zn?function(e,t){return Zn(e,"toString",{configurable:!0,enumerable:!1,value:Aa(t),writable:!0})}:Pn,Ia=800,ka=16,qa=Date.now;var Ma=function(e){var t=0,r=0;return function(){var n=qa(),i=ka-(n-r);if(r=n,i>0){if(++t>=Ia)return arguments[0]}else t=0;return e.apply(void 0,arguments)}},Ha=Ma(Ca);var La=function(e){return Ha(Ta(e,void 0,Na),e+"")},Da=La(function(e,t){var r={};if(null==e)return r;var n=!1;t=ln(t,function(t){return t=vn(t,e),n||(n=t.length>1),t}),ni(e,vi(e),r),n&&(r=ha(r,7,Sa));for(var i=t.length;i--;)va(r,t[i]);return r});var Ua=function(e){return e!=e};var Ba=function(e,t,r){for(var n=r-1,i=e.length;++n<i;)if(e[n]===t)return n;return-1};var Qa=function(e,t,r){return t==t?Ba(e,t,r):Cn(e,Ua,r)};var za=function(e,t){return!(null==e||!e.length)&&Qa(e,t,0)>-1};var Va=function(e,t,r){for(var n=-1,i=null==e?0:e.length;++n<i;)if(r(t,e[n]))return!0;return!1},Wa=Math.min;var Ja=function(e,t,r){for(var n=r?Va:za,i=e[0].length,a=e.length,o=a,s=Array(a),c=1/0,u=[];o--;){var l=e[o];o&&t&&(l=ln(l,cr(t))),c=Wa(l.length,c),s[o]=!r&&(t||i>=120&&l.length>=120)?new ht(o&&l):void 0}l=e[0];var f=-1,h=s[0];e:for(;++f<i&&u.length<c;){var p=l[f],d=t?t(p):p;if(p=r||0!==p?p:0,!(h?dt(h,d):n(u,d,r))){for(o=a;--o;){var m=s[o];if(!(m?dt(m,d):n(e[o],d,r)))continue e}h&&h.push(d),u.push(p)}}return u};var $a=function(e,t){return Ha(Ta(e,t,Pn),e+"")};var Ka=function(e){return Wt(e)&&Rr(e)};var Ya=function(e){return Ka(e)?e:[]},Ga=$a(function(e){var t=ln(e,Ya);return t.length&&t[0]===e[0]?Ja(t):[]});var Xa=function(e){return function(t,r,n){for(var i=-1,a=Object(t),o=n(t),s=o.length;s--;){var c=o[e?s:++i];if(!1===r(a[c],c,a))break}return t}}();var Za=function(e,t){return e&&Xa(e,t,_r)};var eo=function(e){return"function"==typeof e?e:Pn};var to=function(e,t){return e&&Za(e,eo(t))};var ro=function(e,t){return function(r,n){if(null==r)return r;if(!Rr(r))return e(r,n);for(var i=r.length,a=t?i:-1,o=Object(r);(t?a--:++a<i)&&!1!==n(o[a],a,o););return r}}(Za);var no=function(e,t){return(Ht(e)?Xn:ro)(e,eo(t))};var io=function(e,t){var r=[];return ro(e,function(e,n,i){t(e,n,i)&&r.push(e)}),r};var ao=function(e,t){return(Ht(e)?Dt:io)(e,Tn(t,3))};var oo=function(e,t){var r=-1,n=Rr(e)?Array(e.length):[];return ro(e,function(e,i,a){n[++r]=t(e,i,a)}),n};var so=function(e,t){return(Ht(e)?ln:oo)(e,Tn(t,3))};var co=function(e,t,r,n){var i=-1,a=null==e?0:e.length;for(n&&a&&(r=e[++i]);++i<a;)r=t(r,e[i],i,e);return r};var uo=function(e,t,r,n,i){return i(e,function(e,i,a){r=n?(n=!1,e):t(r,e,i,a)}),r};var lo=function(e,t,r){var n=Ht(e)?co:uo,i=arguments.length<3;return n(e,Tn(t,4),r,i,ro)},fo=Math.max;var ho=function(e,t,r){var n=null==e?0:e.length;if(!n)return-1;var i=null==r?0:zn(r);return i<0&&(i=fo(n+i,0)),Qa(e,t,i)},po="[object Number]";var mo=function(e){return"number"==typeof e||Wt(e)&&de(e)==po};var vo=function(e){return mo(e)&&e!=+e};var go=function(e,t){return Qr(e,t)};var yo=function(e){return void 0===e},bo="[object String]";var Ro=function(e){return"string"==typeof e||!Ht(e)&&Wt(e)&&de(e)==bo};var _o=function(e,t,r){var n=e.length;return r=void 0===r?n:r,!t&&r>=n?e:da(e,t,r)};var xo=function(e,t){for(var r=e.length;r--&&Qa(t,e[r],0)>-1;);return r};var wo=function(e,t){for(var r=-1,n=e.length;++r<n&&Qa(t,e[r],0)>-1;);return r};var So=function(e){return e.split("")},jo=RegExp("[\\u200d\\ud800-\\udfff\\u0300-\\u036f\\ufe20-\\ufe2f\\u20d0-\\u20ff\\ufe0e\\ufe0f]");var Fo=function(e){return jo.test(e)},Po="[\\ud800-\\udfff]",No="[\\u0300-\\u036f\\ufe20-\\ufe2f\\u20d0-\\u20ff]",Eo="\\ud83c[\\udffb-\\udfff]",Oo="[^\\ud800-\\udfff]",To="(?:\\ud83c[\\udde6-\\uddff]){2}",Ao="[\\ud800-\\udbff][\\udc00-\\udfff]",Co="(?:"+No+"|"+Eo+")"+"?",Io="[\\ufe0e\\ufe0f]?"+Co+("(?:\\u200d(?:"+[Oo,To,Ao].join("|")+")[\\ufe0e\\ufe0f]?"+Co+")*"),ko="(?:"+[Oo+No+"?",No,To,Ao,Po].join("|")+")",qo=RegExp(Eo+"(?="+Eo+")|"+ko+Io,"g");var Mo=function(e){return e.match(qo)||[]};var Ho=function(e){return Fo(e)?Mo(e):So(e)},Lo=/^\s+|\s+$/g;var Do=function(e,t,r){if((e=mn(e))&&(r||void 0===t))return e.replace(Lo,"");if(!e||!(t=dn(t)))return e;var n=Ho(e),i=Ho(t),a=wo(n,i),o=xo(n,i)+1;return _o(n,a,o).join("")};var Uo=function(e,t,r){if(!me(r))return!1;var n=typeof t;return!!("number"==n?Rr(r)&&nr(t,r.length):"string"==n&&t in r)&&U(r[t],e)},Bo=Object.prototype,Qo=Bo.hasOwnProperty,zo=$a(function(e,t){e=Object(e);var r=-1,n=t.length,i=n>2?t[2]:void 0;for(i&&Uo(t[0],t[1],i)&&(n=1);++r<n;)for(var a=t[r],o=ci(a),s=-1,c=o.length;++s<c;){var u=o[s],l=e[u];(void 0===l||U(l,Bo[u])&&!Qo.call(e,u))&&(e[u]=a[u])}return e});var Vo=function(e,t,r){(void 0===r||U(e[t],r))&&(void 0!==r||t in e)||ei(e,t,r)};var Wo=function(e,t){return"__proto__"==t?void 0:e[t]};var Jo=function(e){return ni(e,ci(e))};var $o=function(e,t,r,n,i,a,o){var s=Wo(e,r),c=Wo(t,r),u=o.get(c);if(u)Vo(e,r,u);else{var l=a?a(s,c,r+"",e,t,o):void 0,f=void 0===l;if(f){var h=Ht(c),p=!h&&er(c),d=!h&&!p&&fr(c);l=c,h||p||d?Ht(s)?l=s:Ka(s)?l=fi(s):p?(f=!1,l=li(c,!0)):d?(f=!1,l=Fi(c,!0)):l=[]:wa(c)||Xt(c)?(l=s,Xt(s)?l=Jo(s):(!me(s)||n&&_e(s))&&(l=Ki(c))):f=!1}f&&(o.set(c,l),i(l,c,n,a,o),o.delete(c)),Vo(e,r,l)}};var Ko=function e(t,r,n,i,a){t!==r&&Xa(r,function(o,s){if(me(o))a||(a=new st),$o(t,r,s,n,e,i,a);else{var c=i?i(Wo(t,s),o,s+"",t,r,a):void 0;void 0===c&&(c=o),Vo(t,s,c)}},ci)};var Yo=function(e){return $a(function(t,r){var n=-1,i=r.length,a=i>1?r[i-1]:void 0,o=i>2?r[2]:void 0;for(a=e.length>3&&"function"==typeof a?(i--,a):void 0,o&&Uo(r[0],r[1],o)&&(a=i<3?void 0:a,i=1),t=Object(t);++n<i;){var s=r[n];s&&e(t,s,n,a)}return t})}(function(e,t,r){Ko(e,t,r)});var Go=function e(t){if(mo(t))return t;if(Ro(t))return parseFloat(t);if(Ht(t))return so(t,e);throw new Error("The value should be a number, a parseable string or an array of those.")};var Xo=function(e,t){var r={},n=ao(t,function(e){return-1!==e.indexOf("attribute:")}),i=so(n,function(e){return e.split(":")[1]});-1===ho(i,"*")?no(i,function(t){e.isConjunctiveFacet(t)&&e.isFacetRefined(t)&&(r.facetsRefinements||(r.facetsRefinements={}),r.facetsRefinements[t]=e.facetsRefinements[t]),e.isDisjunctiveFacet(t)&&e.isDisjunctiveFacetRefined(t)&&(r.disjunctiveFacetsRefinements||(r.disjunctiveFacetsRefinements={}),r.disjunctiveFacetsRefinements[t]=e.disjunctiveFacetsRefinements[t]),e.isHierarchicalFacet(t)&&e.isHierarchicalFacetRefined(t)&&(r.hierarchicalFacetsRefinements||(r.hierarchicalFacetsRefinements={}),r.hierarchicalFacetsRefinements[t]=e.hierarchicalFacetsRefinements[t]);var n=e.getNumericRefinements(t);Gn(n)||(r.numericRefinements||(r.numericRefinements={}),r.numericRefinements[t]=e.numericRefinements[t])}):(Gn(e.numericRefinements)||(r.numericRefinements=e.numericRefinements),Gn(e.facetsRefinements)||(r.facetsRefinements=e.facetsRefinements),Gn(e.disjunctiveFacetsRefinements)||(r.disjunctiveFacetsRefinements=e.disjunctiveFacetsRefinements),Gn(e.hierarchicalFacetsRefinements)||(r.hierarchicalFacetsRefinements=e.hierarchicalFacetsRefinements));var a=ao(t,function(e){return-1===e.indexOf("attribute:")});return no(a,function(t){r[t]=e[t]}),r},Zo={addRefinement:function(e,t,r){if(Zo.isRefined(e,t,r))return e;var n=""+r,i=e[t]?e[t].concat(n):[n],a={};return a[t]=i,zo({},a,e)},removeRefinement:function(e,t,r){if(yo(r))return Zo.clearRefinement(e,t);var n=""+r;return Zo.clearRefinement(e,function(e,r){return t===r&&n===e})},toggleRefinement:function(e,t,r){if(yo(r))throw new Error("toggleRefinement should be used with a value");return Zo.isRefined(e,t,r)?Zo.removeRefinement(e,t,r):Zo.addRefinement(e,t,r)},clearRefinement:function(e,t,r){if(yo(t))return Gn(e)?e:{};if(Ro(t))return Gn(e[t])?e:Da(e,t);if(_e(t)){var n=!1,i=lo(e,function(e,i,a){var o=ao(i,function(e){return!t(e,a,r)});return Gn(o)?n=!0:(o.length!==i.length&&(n=!0),e[a]=o),e},{});return n?i:e}},isRefined:function(e,t,r){var n=ho,i=!!e[t]&&e[t].length>0;if(yo(r)||!i)return i;var a=""+r;return-1!==n(e[t],a)}},es=Zo;function ts(e){var t=e?ts._parseNumbers(e):{};this.index=t.index||"",this.query=t.query||"",this.facets=t.facets||[],this.disjunctiveFacets=t.disjunctiveFacets||[],this.hierarchicalFacets=t.hierarchicalFacets||[],this.facetsRefinements=t.facetsRefinements||{},this.facetsExcludes=t.facetsExcludes||{},this.disjunctiveFacetsRefinements=t.disjunctiveFacetsRefinements||{},this.numericRefinements=t.numericRefinements||{},this.tagRefinements=t.tagRefinements||[],this.hierarchicalFacetsRefinements=t.hierarchicalFacetsRefinements||{},this.numericFilters=t.numericFilters,this.tagFilters=t.tagFilters,this.optionalTagFilters=t.optionalTagFilters,this.optionalFacetFilters=t.optionalFacetFilters,this.hitsPerPage=t.hitsPerPage,this.maxValuesPerFacet=t.maxValuesPerFacet,this.page=t.page||0,this.queryType=t.queryType,this.typoTolerance=t.typoTolerance,this.minWordSizefor1Typo=t.minWordSizefor1Typo,this.minWordSizefor2Typos=t.minWordSizefor2Typos,this.minProximity=t.minProximity,this.allowTyposOnNumericTokens=t.allowTyposOnNumericTokens,this.ignorePlurals=t.ignorePlurals,this.restrictSearchableAttributes=t.restrictSearchableAttributes,this.advancedSyntax=t.advancedSyntax,this.analytics=t.analytics,this.analyticsTags=t.analyticsTags,this.synonyms=t.synonyms,this.replaceSynonymsInHighlight=t.replaceSynonymsInHighlight,this.optionalWords=t.optionalWords,this.removeWordsIfNoResults=t.removeWordsIfNoResults,this.attributesToRetrieve=t.attributesToRetrieve,this.attributesToHighlight=t.attributesToHighlight,this.highlightPreTag=t.highlightPreTag,this.highlightPostTag=t.highlightPostTag,this.attributesToSnippet=t.attributesToSnippet,this.getRankingInfo=t.getRankingInfo,this.distinct=t.distinct,this.aroundLatLng=t.aroundLatLng,this.aroundLatLngViaIP=t.aroundLatLngViaIP,this.aroundRadius=t.aroundRadius,this.minimumAroundRadius=t.minimumAroundRadius,this.aroundPrecision=t.aroundPrecision,this.insideBoundingBox=t.insideBoundingBox,this.insidePolygon=t.insidePolygon,this.snippetEllipsisText=t.snippetEllipsisText,this.disableExactOnAttributes=t.disableExactOnAttributes,this.enableExactOnSingleWordQuery=t.enableExactOnSingleWordQuery,this.offset=t.offset,this.length=t.length;var r=this;to(t,function(e,t){-1===ts.PARAMETERS.indexOf(t)&&(r[t]=e)})}ts.PARAMETERS=_r(new ts),ts._parseNumbers=function(e){if(e instanceof ts)return e;var t={};if(no(["aroundPrecision","aroundRadius","getRankingInfo","minWordSizefor2Typos","minWordSizefor1Typo","page","maxValuesPerFacet","distinct","minimumAroundRadius","hitsPerPage","minProximity"],function(r){var n=e[r];if(Ro(n)){var i=parseFloat(n);t[r]=vo(i)?n:i}}),Array.isArray(e.insideBoundingBox)&&(t.insideBoundingBox=e.insideBoundingBox.map(function(e){return e.map(function(e){return parseFloat(e)})})),e.numericRefinements){var r={};no(e.numericRefinements,function(e,t){r[t]={},no(e,function(e,n){var i=so(e,function(e){return Ht(e)?so(e,function(e){return Ro(e)?parseFloat(e):e}):Ro(e)?parseFloat(e):e});r[t][n]=i})}),t.numericRefinements=r}return Yo({},e,t)},ts.make=function(e){var t=new ts(e);return no(e.hierarchicalFacets,function(e){if(e.rootPath){var r=t.getHierarchicalRefinement(e.name);r.length>0&&0!==r[0].indexOf(e.rootPath)&&(t=t.clearRefinements(e.name)),0===(r=t.getHierarchicalRefinement(e.name)).length&&(t=t.toggleHierarchicalFacetRefinement(e.name,e.rootPath))}}),t},ts.validate=function(e,t){var r=t||{};return e.tagFilters&&r.tagRefinements&&r.tagRefinements.length>0?new Error("[Tags] Cannot switch from the managed tag API to the advanced API. It is probably an error, if it is really what you want, you should first clear the tags with clearTags method."):e.tagRefinements.length>0&&r.tagFilters?new Error("[Tags] Cannot switch from the advanced tag API to the managed API. It is probably an error, if it is not, you should first clear the tags with clearTags method."):e.numericFilters&&r.numericRefinements&&!Gn(r.numericRefinements)?new Error("[Numeric filters] Can't switch from the advanced to the managed API. It is probably an error, if this is really what you want, you have to first clear the numeric filters."):!Gn(e.numericRefinements)&&r.numericFilters?new Error("[Numeric filters] Can't switch from the managed API to the advanced. It is probably an error, if this is really what you want, you have to first clear the numeric filters."):null},ts.prototype={constructor:ts,clearRefinements:function(e){var t=es.clearRefinement,r={numericRefinements:this._clearNumericRefinements(e),facetsRefinements:t(this.facetsRefinements,e,"conjunctiveFacet"),facetsExcludes:t(this.facetsExcludes,e,"exclude"),disjunctiveFacetsRefinements:t(this.disjunctiveFacetsRefinements,e,"disjunctiveFacet"),hierarchicalFacetsRefinements:t(this.hierarchicalFacetsRefinements,e,"hierarchicalFacet")};return r.numericRefinements===this.numericRefinements&&r.facetsRefinements===this.facetsRefinements&&r.facetsExcludes===this.facetsExcludes&&r.disjunctiveFacetsRefinements===this.disjunctiveFacetsRefinements&&r.hierarchicalFacetsRefinements===this.hierarchicalFacetsRefinements?this:this.setQueryParameters(r)},clearTags:function(){return void 0===this.tagFilters&&0===this.tagRefinements.length?this:this.setQueryParameters({tagFilters:void 0,tagRefinements:[]})},setIndex:function(e){return e===this.index?this:this.setQueryParameters({index:e})},setQuery:function(e){return e===this.query?this:this.setQueryParameters({query:e})},setPage:function(e){return e===this.page?this:this.setQueryParameters({page:e})},setFacets:function(e){return this.setQueryParameters({facets:e})},setDisjunctiveFacets:function(e){return this.setQueryParameters({disjunctiveFacets:e})},setHitsPerPage:function(e){return this.hitsPerPage===e?this:this.setQueryParameters({hitsPerPage:e})},setTypoTolerance:function(e){return this.typoTolerance===e?this:this.setQueryParameters({typoTolerance:e})},addNumericRefinement:function(e,t,r){var n=Go(r);if(this.isNumericRefined(e,t,n))return this;var i=Yo({},this.numericRefinements);return i[e]=Yo({},i[e]),i[e][t]?(i[e][t]=i[e][t].slice(),i[e][t].push(n)):i[e][t]=[n],this.setQueryParameters({numericRefinements:i})},getConjunctiveRefinements:function(e){if(!this.isConjunctiveFacet(e))throw new Error(e+" is not defined in the facets attribute of the helper configuration");return this.facetsRefinements[e]||[]},getDisjunctiveRefinements:function(e){if(!this.isDisjunctiveFacet(e))throw new Error(e+" is not defined in the disjunctiveFacets attribute of the helper configuration");return this.disjunctiveFacetsRefinements[e]||[]},getHierarchicalRefinement:function(e){return this.hierarchicalFacetsRefinements[e]||[]},getExcludeRefinements:function(e){if(!this.isConjunctiveFacet(e))throw new Error(e+" is not defined in the facets attribute of the helper configuration");return this.facetsExcludes[e]||[]},removeNumericRefinement:function(e,t,r){if(void 0!==r){var n=Go(r);return this.isNumericRefined(e,t,n)?this.setQueryParameters({numericRefinements:this._clearNumericRefinements(function(r,i){return i===e&&r.op===t&&go(r.val,n)})}):this}return void 0!==t?this.isNumericRefined(e,t)?this.setQueryParameters({numericRefinements:this._clearNumericRefinements(function(r,n){return n===e&&r.op===t})}):this:this.isNumericRefined(e)?this.setQueryParameters({numericRefinements:this._clearNumericRefinements(function(t,r){return r===e})}):this},getNumericRefinements:function(e){return this.numericRefinements[e]||{}},getNumericRefinement:function(e,t){return this.numericRefinements[e]&&this.numericRefinements[e][t]},_clearNumericRefinements:function(e){if(yo(e))return Gn(this.numericRefinements)?this.numericRefinements:{};if(Ro(e))return Gn(this.numericRefinements[e])?this.numericRefinements:Da(this.numericRefinements,e);if(_e(e)){var t=!1,r=lo(this.numericRefinements,function(r,n,i){var a={};return no(n,function(r,n){var o=[];no(r,function(t){e({val:t,op:n},i,"numeric")||o.push(t)}),Gn(o)?t=!0:(o.length!==r.length&&(t=!0),a[n]=o)}),Gn(a)||(r[i]=a),r},{});return t?r:this.numericRefinements}},addFacet:function(e){return this.isConjunctiveFacet(e)?this:this.setQueryParameters({facets:this.facets.concat([e])})},addDisjunctiveFacet:function(e){return this.isDisjunctiveFacet(e)?this:this.setQueryParameters({disjunctiveFacets:this.disjunctiveFacets.concat([e])})},addHierarchicalFacet:function(e){if(this.isHierarchicalFacet(e.name))throw new Error("Cannot declare two hierarchical facets with the same name: `"+e.name+"`");return this.setQueryParameters({hierarchicalFacets:this.hierarchicalFacets.concat([e])})},addFacetRefinement:function(e,t){if(!this.isConjunctiveFacet(e))throw new Error(e+" is not defined in the facets attribute of the helper configuration");return es.isRefined(this.facetsRefinements,e,t)?this:this.setQueryParameters({facetsRefinements:es.addRefinement(this.facetsRefinements,e,t)})},addExcludeRefinement:function(e,t){if(!this.isConjunctiveFacet(e))throw new Error(e+" is not defined in the facets attribute of the helper configuration");return es.isRefined(this.facetsExcludes,e,t)?this:this.setQueryParameters({facetsExcludes:es.addRefinement(this.facetsExcludes,e,t)})},addDisjunctiveFacetRefinement:function(e,t){if(!this.isDisjunctiveFacet(e))throw new Error(e+" is not defined in the disjunctiveFacets attribute of the helper configuration");return es.isRefined(this.disjunctiveFacetsRefinements,e,t)?this:this.setQueryParameters({disjunctiveFacetsRefinements:es.addRefinement(this.disjunctiveFacetsRefinements,e,t)})},addTagRefinement:function(e){if(this.isTagRefined(e))return this;var t={tagRefinements:this.tagRefinements.concat(e)};return this.setQueryParameters(t)},removeFacet:function(e){return this.isConjunctiveFacet(e)?this.clearRefinements(e).setQueryParameters({facets:ao(this.facets,function(t){return t!==e})}):this},removeDisjunctiveFacet:function(e){return this.isDisjunctiveFacet(e)?this.clearRefinements(e).setQueryParameters({disjunctiveFacets:ao(this.disjunctiveFacets,function(t){return t!==e})}):this},removeHierarchicalFacet:function(e){return this.isHierarchicalFacet(e)?this.clearRefinements(e).setQueryParameters({hierarchicalFacets:ao(this.hierarchicalFacets,function(t){return t.name!==e})}):this},removeFacetRefinement:function(e,t){if(!this.isConjunctiveFacet(e))throw new Error(e+" is not defined in the facets attribute of the helper configuration");return es.isRefined(this.facetsRefinements,e,t)?this.setQueryParameters({facetsRefinements:es.removeRefinement(this.facetsRefinements,e,t)}):this},removeExcludeRefinement:function(e,t){if(!this.isConjunctiveFacet(e))throw new Error(e+" is not defined in the facets attribute of the helper configuration");return es.isRefined(this.facetsExcludes,e,t)?this.setQueryParameters({facetsExcludes:es.removeRefinement(this.facetsExcludes,e,t)}):this},removeDisjunctiveFacetRefinement:function(e,t){if(!this.isDisjunctiveFacet(e))throw new Error(e+" is not defined in the disjunctiveFacets attribute of the helper configuration");return es.isRefined(this.disjunctiveFacetsRefinements,e,t)?this.setQueryParameters({disjunctiveFacetsRefinements:es.removeRefinement(this.disjunctiveFacetsRefinements,e,t)}):this},removeTagRefinement:function(e){if(!this.isTagRefined(e))return this;var t={tagRefinements:ao(this.tagRefinements,function(t){return t!==e})};return this.setQueryParameters(t)},toggleRefinement:function(e,t){return this.toggleFacetRefinement(e,t)},toggleFacetRefinement:function(e,t){if(this.isHierarchicalFacet(e))return this.toggleHierarchicalFacetRefinement(e,t);if(this.isConjunctiveFacet(e))return this.toggleConjunctiveFacetRefinement(e,t);if(this.isDisjunctiveFacet(e))return this.toggleDisjunctiveFacetRefinement(e,t);throw new Error("Cannot refine the undeclared facet "+e+"; it should be added to the helper options facets, disjunctiveFacets or hierarchicalFacets")},toggleConjunctiveFacetRefinement:function(e,t){if(!this.isConjunctiveFacet(e))throw new Error(e+" is not defined in the facets attribute of the helper configuration");return this.setQueryParameters({facetsRefinements:es.toggleRefinement(this.facetsRefinements,e,t)})},toggleExcludeFacetRefinement:function(e,t){if(!this.isConjunctiveFacet(e))throw new Error(e+" is not defined in the facets attribute of the helper configuration");return this.setQueryParameters({facetsExcludes:es.toggleRefinement(this.facetsExcludes,e,t)})},toggleDisjunctiveFacetRefinement:function(e,t){if(!this.isDisjunctiveFacet(e))throw new Error(e+" is not defined in the disjunctiveFacets attribute of the helper configuration");return this.setQueryParameters({disjunctiveFacetsRefinements:es.toggleRefinement(this.disjunctiveFacetsRefinements,e,t)})},toggleHierarchicalFacetRefinement:function(e,t){if(!this.isHierarchicalFacet(e))throw new Error(e+" is not defined in the hierarchicalFacets attribute of the helper configuration");var r=this._getHierarchicalFacetSeparator(this.getHierarchicalFacetByName(e)),n={};return void 0!==this.hierarchicalFacetsRefinements[e]&&this.hierarchicalFacetsRefinements[e].length>0&&(this.hierarchicalFacetsRefinements[e][0]===t||0===this.hierarchicalFacetsRefinements[e][0].indexOf(t+r))?-1===t.indexOf(r)?n[e]=[]:n[e]=[t.slice(0,t.lastIndexOf(r))]:n[e]=[t],this.setQueryParameters({hierarchicalFacetsRefinements:zo({},n,this.hierarchicalFacetsRefinements)})},addHierarchicalFacetRefinement:function(e,t){if(this.isHierarchicalFacetRefined(e))throw new Error(e+" is already refined.");var r={};return r[e]=[t],this.setQueryParameters({hierarchicalFacetsRefinements:zo({},r,this.hierarchicalFacetsRefinements)})},removeHierarchicalFacetRefinement:function(e){if(!this.isHierarchicalFacetRefined(e))throw new Error(e+" is not refined.");var t={};return t[e]=[],this.setQueryParameters({hierarchicalFacetsRefinements:zo({},t,this.hierarchicalFacetsRefinements)})},toggleTagRefinement:function(e){return this.isTagRefined(e)?this.removeTagRefinement(e):this.addTagRefinement(e)},isDisjunctiveFacet:function(e){return ho(this.disjunctiveFacets,e)>-1},isHierarchicalFacet:function(e){return void 0!==this.getHierarchicalFacetByName(e)},isConjunctiveFacet:function(e){return ho(this.facets,e)>-1},isFacetRefined:function(e,t){if(!this.isConjunctiveFacet(e))throw new Error(e+" is not defined in the facets attribute of the helper configuration");return es.isRefined(this.facetsRefinements,e,t)},isExcludeRefined:function(e,t){if(!this.isConjunctiveFacet(e))throw new Error(e+" is not defined in the facets attribute of the helper configuration");return es.isRefined(this.facetsExcludes,e,t)},isDisjunctiveFacetRefined:function(e,t){if(!this.isDisjunctiveFacet(e))throw new Error(e+" is not defined in the disjunctiveFacets attribute of the helper configuration");return es.isRefined(this.disjunctiveFacetsRefinements,e,t)},isHierarchicalFacetRefined:function(e,t){if(!this.isHierarchicalFacet(e))throw new Error(e+" is not defined in the hierarchicalFacets attribute of the helper configuration");var r=this.getHierarchicalRefinement(e);return t?-1!==ho(r,t):r.length>0},isNumericRefined:function(e,t,r){if(yo(r)&&yo(t))return!!this.numericRefinements[e];var n=this.numericRefinements[e]&&!yo(this.numericRefinements[e][t]);if(yo(r)||!n)return n;var i,a,o=Go(r),s=!yo((i=this.numericRefinements[e][t],a=o,Jn(i,function(e){return go(e,a)})));return n&&s},isTagRefined:function(e){return-1!==ho(this.tagRefinements,e)},getRefinedDisjunctiveFacets:function(){var e=Ga(_r(this.numericRefinements),this.disjunctiveFacets);return _r(this.disjunctiveFacetsRefinements).concat(e).concat(this.getRefinedHierarchicalFacets())},getRefinedHierarchicalFacets:function(){return Ga(so(this.hierarchicalFacets,"name"),_r(this.hierarchicalFacetsRefinements))},getUnrefinedDisjunctiveFacets:function(){var e=this.getRefinedDisjunctiveFacets();return ao(this.disjunctiveFacets,function(t){return-1===ho(e,t)})},managedParameters:["index","facets","disjunctiveFacets","facetsRefinements","facetsExcludes","disjunctiveFacetsRefinements","numericRefinements","tagRefinements","hierarchicalFacets","hierarchicalFacetsRefinements"],getQueryParams:function(){var e=this.managedParameters,t={};return to(this,function(r,n){-1===ho(e,n)&&void 0!==r&&(t[n]=r)}),t},getQueryParameter:function(e){if(!this.hasOwnProperty(e))throw new Error("Parameter '"+e+"' is not an attribute of SearchParameters (http://algolia.github.io/algoliasearch-helper-js/docs/SearchParameters.html)");return this[e]},setQueryParameter:function(e,t){if(this[e]===t)return this;var r={};return r[e]=t,this.setQueryParameters(r)},setQueryParameters:function(e){if(!e)return this;var t=ts.validate(this,e);if(t)throw t;var r=ts._parseNumbers(e);return this.mutateMe(function(t){var n=_r(e);return no(n,function(e){t[e]=r[e]}),t})},filter:function(e){return Xo(this,e)},mutateMe:function(e){var t=new this.constructor(this);return e(t,this),t},_getHierarchicalFacetSortBy:function(e){return e.sortBy||["isRefined:desc","name:asc"]},_getHierarchicalFacetSeparator:function(e){return e.separator||" > "},_getHierarchicalRootPath:function(e){return e.rootPath||null},_getHierarchicalShowParentLevel:function(e){return"boolean"!=typeof e.showParentLevel||e.showParentLevel},getHierarchicalFacetByName:function(e){return Jn(this.hierarchicalFacets,{name:e})},getHierarchicalFacetBreadcrumb:function(e){if(!this.isHierarchicalFacet(e))throw new Error("Cannot get the breadcrumb of an unknown hierarchical facet: `"+e+"`");var t=this.getHierarchicalRefinement(e)[0];if(!t)return[];var r=this._getHierarchicalFacetSeparator(this.getHierarchicalFacetByName(e)),n=t.split(r);return so(n,Do)},toString:function(){return JSON.stringify(this,null,2)}};var rs=ts;var ns=function(e){for(var t=-1,r=null==e?0:e.length,n=0,i=[];++t<r;){var a=e[t];a&&(i[n++]=a)}return i};var is=function(e,t){for(var r,n=-1,i=e.length;++n<i;){var a=t(e[n]);void 0!==a&&(r=void 0===r?a:r+a)}return r};var as=function(e,t){return e&&e.length?is(e,Tn(t,2)):0};var os=function(e,t){return ln(t,function(t){return e[t]})};var ss=function(e){return null==e?[]:os(e,_r(e))},cs=Math.max;var us=function(e,t,r,n){e=Rr(e)?e:ss(e),r=r&&!n?zn(r):0;var i=e.length;return r<0&&(r=cs(i+r,0)),Ro(e)?r<=i&&e.indexOf(t,r)>-1:!!i&&Qa(e,t,r)>-1};var ls=function(e,t){var r=e.length;for(e.sort(t);r--;)e[r]=e[r].value;return e};var fs=function(e,t){if(e!==t){var r=void 0!==e,n=null===e,i=e==e,a=Xr(e),o=void 0!==t,s=null===t,c=t==t,u=Xr(t);if(!s&&!u&&!a&&e>t||a&&o&&c&&!s&&!u||n&&o&&c||!r&&c||!i)return 1;if(!n&&!a&&!u&&e<t||u&&r&&i&&!n&&!a||s&&r&&i||!o&&i||!c)return-1}return 0};var hs=function(e,t,r){for(var n=-1,i=e.criteria,a=t.criteria,o=i.length,s=r.length;++n<o;){var c=fs(i[n],a[n]);if(c)return n>=s?c:c*("desc"==r[n]?-1:1)}return e.index-t.index};var ps=function(e,t,r){var n=-1;t=ln(t.length?t:[Pn],cr(Tn));var i=oo(e,function(e,r,i){return{criteria:ln(t,function(t){return t(e)}),index:++n,value:e}});return ls(i,function(e,t){return hs(e,t,r)})};var ds=function(e,t,r,n){return null==e?[]:(Ht(t)||(t=null==t?[]:[t]),Ht(r=n?void 0:r)||(r=null==r?[]:[r]),ps(e,t,r))},ms=Er&&new Er,vs=ms?function(e,t){return ms.set(e,t),e}:Pn;var gs=function(e){return function(){var t=arguments;switch(t.length){case 0:return new e;case 1:return new e(t[0]);case 2:return new e(t[0],t[1]);case 3:return new e(t[0],t[1],t[2]);case 4:return new e(t[0],t[1],t[2],t[3]);case 5:return new e(t[0],t[1],t[2],t[3],t[4]);case 6:return new e(t[0],t[1],t[2],t[3],t[4],t[5]);case 7:return new e(t[0],t[1],t[2],t[3],t[4],t[5],t[6])}var r=$i(e.prototype),n=e.apply(r,t);return me(n)?n:r}},ys=1;var bs=function(e,t,r){var n=t&ys,i=gs(e);return function t(){return(this&&this!==re&&this instanceof t?i:e).apply(n?r:this,arguments)}},Rs=Math.max;var _s=function(e,t,r,n){for(var i=-1,a=e.length,o=r.length,s=-1,c=t.length,u=Rs(a-o,0),l=Array(c+u),f=!n;++s<c;)l[s]=t[s];for(;++i<o;)(f||i<a)&&(l[r[i]]=e[i]);for(;u--;)l[s++]=e[i++];return l},xs=Math.max;var ws=function(e,t,r,n){for(var i=-1,a=e.length,o=-1,s=r.length,c=-1,u=t.length,l=xs(a-s,0),f=Array(l+u),h=!n;++i<l;)f[i]=e[i];for(var p=i;++c<u;)f[p+c]=t[c];for(;++o<s;)(h||i<a)&&(f[p+r[o]]=e[i++]);return f};var Ss=function(e,t){for(var r=e.length,n=0;r--;)e[r]===t&&++n;return n};var js=function(){},Fs=4294967295;function Ps(e){this.__wrapped__=e,this.__actions__=[],this.__dir__=1,this.__filtered__=!1,this.__iteratees__=[],this.__takeCount__=Fs,this.__views__=[]}Ps.prototype=$i(js.prototype),Ps.prototype.constructor=Ps;var Ns=Ps;var Es=ms?function(e){return ms.get(e)}:function(){},Os={},Ts=Object.prototype.hasOwnProperty;var As=function(e){for(var t=e.name+"",r=Os[t],n=Ts.call(Os,t)?r.length:0;n--;){var i=r[n],a=i.func;if(null==a||a==e)return i.name}return t};function Cs(e,t){this.__wrapped__=e,this.__actions__=[],this.__chain__=!!t,this.__index__=0,this.__values__=void 0}Cs.prototype=$i(js.prototype),Cs.prototype.constructor=Cs;var Is=Cs;var ks=function(e){if(e instanceof Ns)return e.clone();var t=new Is(e.__wrapped__,e.__chain__);return t.__actions__=fi(e.__actions__),t.__index__=e.__index__,t.__values__=e.__values__,t},qs=Object.prototype.hasOwnProperty;function Ms(e){if(Wt(e)&&!Ht(e)&&!(e instanceof Ns)){if(e instanceof Is)return e;if(qs.call(e,"__wrapped__"))return ks(e)}return new Is(e)}Ms.prototype=js.prototype,Ms.prototype.constructor=Ms;var Hs=Ms;var Ls=function(e){var t=As(e),r=Hs[t];if("function"!=typeof r||!(t in Ns.prototype))return!1;if(e===r)return!0;var n=Es(r);return!!n&&e===n[0]},Ds=Ma(vs),Us=/\{\n\/\* \[wrapped with (.+)\] \*/,Bs=/,? & /;var Qs=function(e){var t=e.match(Us);return t?t[1].split(Bs):[]},zs=/\{(?:\n\/\* \[wrapped with .+\] \*\/)?\n?/;var Vs=function(e,t){var r=t.length;if(!r)return e;var n=r-1;return t[n]=(r>1?"& ":"")+t[n],t=t.join(r>2?", ":" "),e.replace(zs,"{\n/* [wrapped with "+t+"] */\n")},Ws=[["ary",128],["bind",1],["bindKey",2],["curry",8],["curryRight",16],["flip",512],["partial",32],["partialRight",64],["rearg",256]];var Js=function(e,t){return Xn(Ws,function(r){var n="_."+r[0];t&r[1]&&!za(e,n)&&e.push(n)}),e.sort()};var $s=function(e,t,r){var n=t+"";return Ha(e,Vs(n,Js(Qs(n),r)))},Ks=1,Ys=2,Gs=4,Xs=8,Zs=32,ec=64;var tc=function(e,t,r,n,i,a,o,s,c,u){var l=t&Xs;t|=l?Zs:ec,(t&=~(l?ec:Zs))&Gs||(t&=~(Ks|Ys));var f=[e,t,i,l?a:void 0,l?o:void 0,l?void 0:a,l?void 0:o,s,c,u],h=r.apply(void 0,f);return Ls(e)&&Ds(h,f),h.placeholder=n,$s(h,e,t)};var rc=function(e){return e.placeholder},nc=Math.min;var ic=function(e,t){for(var r=e.length,n=nc(t.length,r),i=fi(e);n--;){var a=t[n];e[n]=nr(a,r)?i[a]:void 0}return e},ac="__lodash_placeholder__";var oc=function(e,t){for(var r=-1,n=e.length,i=0,a=[];++r<n;){var o=e[r];o!==t&&o!==ac||(e[r]=ac,a[i++]=r)}return a},sc=1,cc=2,uc=8,lc=16,fc=128,hc=512;var pc=function e(t,r,n,i,a,o,s,c,u,l){var f=r&fc,h=r&sc,p=r&cc,d=r&(uc|lc),m=r&hc,v=p?void 0:gs(t);return function g(){for(var y=arguments.length,b=Array(y),R=y;R--;)b[R]=arguments[R];if(d)var _=rc(g),x=Ss(b,_);if(i&&(b=_s(b,i,a,d)),o&&(b=ws(b,o,s,d)),y-=x,d&&y<l){var w=oc(b,_);return tc(t,r,e,g.placeholder,n,b,w,c,u,l-y)}var S=h?n:this,j=p?S[t]:t;return y=b.length,c?b=ic(b,c):m&&y>1&&b.reverse(),f&&u<y&&(b.length=u),this&&this!==re&&this instanceof g&&(j=v||gs(j)),j.apply(S,b)}};var dc=function(e,t,r){var n=gs(e);return function i(){for(var a=arguments.length,o=Array(a),s=a,c=rc(i);s--;)o[s]=arguments[s];var u=a<3&&o[0]!==c&&o[a-1]!==c?[]:oc(o,c);return(a-=u.length)<r?tc(e,t,pc,i.placeholder,void 0,o,u,void 0,void 0,r-a):Ea(this&&this!==re&&this instanceof i?n:e,this,o)}},mc=1;var vc=function(e,t,r,n){var i=t&mc,a=gs(e);return function t(){for(var o=-1,s=arguments.length,c=-1,u=n.length,l=Array(u+s),f=this&&this!==re&&this instanceof t?a:e;++c<u;)l[c]=n[c];for(;s--;)l[c++]=arguments[++o];return Ea(f,i?r:this,l)}},gc="__lodash_placeholder__",yc=1,bc=2,Rc=4,_c=8,xc=128,wc=256,Sc=Math.min;var jc=function(e,t){var r=e[1],n=t[1],i=r|n,a=i<(yc|bc|xc),o=n==xc&&r==_c||n==xc&&r==wc&&e[7].length<=t[8]||n==(xc|wc)&&t[7].length<=t[8]&&r==_c;if(!a&&!o)return e;n&yc&&(e[2]=t[2],i|=r&yc?0:Rc);var s=t[3];if(s){var c=e[3];e[3]=c?_s(c,s,t[4]):s,e[4]=c?oc(e[3],gc):t[4]}return(s=t[5])&&(c=e[5],e[5]=c?ws(c,s,t[6]):s,e[6]=c?oc(e[5],gc):t[6]),(s=t[7])&&(e[7]=s),n&xc&&(e[8]=null==e[8]?t[8]:Sc(e[8],t[8])),null==e[9]&&(e[9]=t[9]),e[0]=t[0],e[1]=i,e},Fc="Expected a function",Pc=1,Nc=2,Ec=8,Oc=16,Tc=32,Ac=64,Cc=Math.max;var Ic=function(e,t,r,n,i,a,o,s){var c=t&Nc;if(!c&&"function"!=typeof e)throw new TypeError(Fc);var u=n?n.length:0;if(u||(t&=~(Tc|Ac),n=i=void 0),o=void 0===o?o:Cc(zn(o),0),s=void 0===s?s:zn(s),u-=i?i.length:0,t&Ac){var l=n,f=i;n=i=void 0}var h=c?void 0:Es(e),p=[e,t,r,n,i,l,f,a,o,s];if(h&&jc(p,h),e=p[0],t=p[1],r=p[2],n=p[3],i=p[4],!(s=p[9]=void 0===p[9]?c?0:e.length:Cc(p[9]-u,0))&&t&(Ec|Oc)&&(t&=~(Ec|Oc)),t&&t!=Pc)d=t==Ec||t==Oc?dc(e,t,s):t!=Tc&&t!=(Pc|Tc)||i.length?pc.apply(void 0,p):vc(e,t,r,n);else var d=bs(e,t,r);return $s((h?vs:Ds)(d,p),e,t)},kc=$a(function(e,t){var r=oc(t,rc(kc));return Ic(e,32,void 0,t,r)});kc.placeholder={};var qc=kc,Mc=$a(function(e,t){var r=oc(t,rc(Mc));return Ic(e,64,void 0,t,r)});Mc.placeholder={};var Hc=Mc;var Lc=function(e,t,r){return e==e&&(void 0!==r&&(e=e<=r?e:r),void 0!==t&&(e=e>=t?e:t)),e};var Dc=function(e,t,r){return e=mn(e),r=null==r?0:Lc(zn(r),0,e.length),t=dn(t),e.slice(r,r+t.length)==t},Uc=function(e,t){return lo(e,function(e,r){var n=r.split(":");if(t&&1===n.length){var i=Jn(t,function(e){return Dc(e,r[0])});i&&(n=i.split(":"))}return e[0].push(n[0]),e[1].push(n[1]),e},[[],[]])};var Bc=function(e,t,r,n){if(!me(e))return e;for(var i=-1,a=(t=vn(t,e)).length,o=a-1,s=e;null!=s&&++i<a;){var c=yn(t[i]),u=r;if(i!=o){var l=s[c];void 0===(u=n?n(l,c,s):void 0)&&(u=me(l)?l:nr(t[i+1])?[]:{})}ri(s,c,u),s=s[c]}return e};var Qc=function(e,t,r){for(var n=-1,i=t.length,a={};++n<i;){var o=t[n],s=bn(e,o);r(s,o)&&Bc(a,vn(o,e),s)}return a};var zc=function(e,t){if(null==e)return{};var r=ln(vi(e),function(e){return[e]});return t=Tn(t),Qc(e,r,function(e,r){return t(e,r[0])})},Vc=function(e){return function(t,r){var n=e.hierarchicalFacets[r],i=e.hierarchicalFacetsRefinements[n.name]&&e.hierarchicalFacetsRefinements[n.name][0]||"",a=e._getHierarchicalFacetSeparator(n),o=e._getHierarchicalRootPath(n),s=e._getHierarchicalShowParentLevel(n),c=Uc(e._getHierarchicalFacetSortBy(n)),u=function(e,t,r,n,i){return function(a,o,s){var c=a;if(s>0){var u=0;for(c=a;u<s;)c=c&&Jn(c.data,{isRefined:!0}),u++}if(c){var l=function(e,t,r,n,i){return function(a,o){return(!n||0===o.indexOf(n)&&n!==o)&&(!n&&-1===o.indexOf(r)||n&&o.split(r).length-n.split(r).length==1||-1===o.indexOf(r)&&-1===t.indexOf(r)||0===t.indexOf(o)||0===o.indexOf(e+r)&&(i||0===o.indexOf(t)))}}(c.path||r,i,t,r,n);c.data=ds(so(zc(o.data,l),function(e,t){return function(r,n){return{name:Do(pa(n.split(e))),path:n,count:r,isRefined:t===n||0===t.indexOf(n+e),data:null}}}(t,i)),e[0],e[1])}return a}}(c,a,o,s,i),l=t;return o&&(l=t.slice(o.split(a).length)),lo(l,u,{name:e.hierarchicalFacets[r].name,count:null,isRefined:!0,path:null,data:null})}};function Wc(e){var t={};return no(e,function(e,r){t[e]=r}),t}function Jc(e,t,r){t&&t[r]&&(e.stats=t[r])}function $c(e,t){var r=t[0];this._rawResults=t,this.query=r.query,this.parsedQuery=r.parsedQuery,this.hits=r.hits,this.index=r.index,this.hitsPerPage=r.hitsPerPage,this.nbHits=r.nbHits,this.nbPages=r.nbPages,this.page=r.page,this.processingTimeMS=as(t,"processingTimeMS"),this.aroundLatLng=r.aroundLatLng,this.automaticRadius=r.automaticRadius,this.serverUsed=r.serverUsed,this.timeoutCounts=r.timeoutCounts,this.timeoutHits=r.timeoutHits,this.exhaustiveFacetsCount=r.exhaustiveFacetsCount,this.exhaustiveNbHits=r.exhaustiveNbHits,this.userData=r.userData,this.queryID=r.queryID,this.disjunctiveFacets=[],this.hierarchicalFacets=so(e.hierarchicalFacets,function(){return[]}),this.facets=[];var n=e.getRefinedDisjunctiveFacets(),i=Wc(e.facets),a=Wc(e.disjunctiveFacets),o=1,s=this;no(r.facets,function(t,n){var o,c,u=(o=e.hierarchicalFacets,c=n,Jn(o,function(e){return us(e.attributes,c)}));if(u){var l=u.attributes.indexOf(n),f=Wn(e.hierarchicalFacets,{name:u.name});s.hierarchicalFacets[f][l]={attribute:n,data:t,exhaustive:r.exhaustiveFacetsCount}}else{var h,p=-1!==ho(e.disjunctiveFacets,n),d=-1!==ho(e.facets,n);p&&(h=a[n],s.disjunctiveFacets[h]={name:n,data:t,exhaustive:r.exhaustiveFacetsCount},Jc(s.disjunctiveFacets[h],r.facets_stats,n)),d&&(h=i[n],s.facets[h]={name:n,data:t,exhaustive:r.exhaustiveFacetsCount},Jc(s.facets[h],r.facets_stats,n))}}),this.hierarchicalFacets=ns(this.hierarchicalFacets),no(n,function(n){var i=t[o],c=e.getHierarchicalFacetByName(n);no(i.facets,function(t,n){var o;if(c){o=Wn(e.hierarchicalFacets,{name:c.name});var u=Wn(s.hierarchicalFacets[o],{attribute:n});if(-1===u)return;s.hierarchicalFacets[o][u].data=Yo({},s.hierarchicalFacets[o][u].data,t)}else{o=a[n];var l=r.facets&&r.facets[n]||{};s.disjunctiveFacets[o]={name:n,data:zo({},t,l),exhaustive:i.exhaustiveFacetsCount},Jc(s.disjunctiveFacets[o],i.facets_stats,n),e.disjunctiveFacetsRefinements[n]&&no(e.disjunctiveFacetsRefinements[n],function(t){!s.disjunctiveFacets[o].data[t]&&ho(e.disjunctiveFacetsRefinements[n],t)>-1&&(s.disjunctiveFacets[o].data[t]=0)})}}),o++}),no(e.getRefinedHierarchicalFacets(),function(r){var n=e.getHierarchicalFacetByName(r),i=e._getHierarchicalFacetSeparator(n),a=e.getHierarchicalRefinement(r);if(!(0===a.length||a[0].split(i).length<2)){var c=t[o];no(c.facets,function(t,r){var o=Wn(e.hierarchicalFacets,{name:n.name}),c=Wn(s.hierarchicalFacets[o],{attribute:r});if(-1!==c){var u={};if(a.length>0){var l=a[0].split(i)[0];u[l]=s.hierarchicalFacets[o][c].data[l]}s.hierarchicalFacets[o][c].data=zo(u,t,s.hierarchicalFacets[o][c].data)}}),o++}}),no(e.facetsExcludes,function(e,t){var n=i[t];s.facets[n]={name:t,data:r.facets[t],exhaustive:r.exhaustiveFacetsCount},no(e,function(e){s.facets[n]=s.facets[n]||{name:t},s.facets[n].data=s.facets[n].data||{},s.facets[n].data[e]=0})}),this.hierarchicalFacets=so(this.hierarchicalFacets,Vc(e)),this.facets=ns(this.facets),this.disjunctiveFacets=ns(this.disjunctiveFacets),this._state=e}function Kc(e,t){if(!t.data||0===t.data.length)return t;var r=e(so(t.data,qc(Kc,e)));return Yo({},t,{data:r})}function Yc(e,t){return t.sort(e)}function Gc(e,t){var r=Jn(e,{name:t});return r&&r.stats}function Xc(e,t,r,n,i){var a=Jn(i,{name:r}),o=Rn(a,"data["+n+"]"),s=Rn(a,"exhaustive");return{type:t,attributeName:r,name:n,count:o||0,exhaustive:s||!1}}$c.prototype.getFacetByName=function(e){var t={name:e};return Jn(this.facets,t)||Jn(this.disjunctiveFacets,t)||Jn(this.hierarchicalFacets,t)},$c.DEFAULT_SORT=["isRefined:desc","count:desc","name:asc"],$c.prototype.getFacetValues=function(e,t){var r=function(e,t){var r={name:t};if(e._state.isConjunctiveFacet(t)){var n=Jn(e.facets,r);return n?so(n.data,function(r,n){return{name:n,count:r,isRefined:e._state.isFacetRefined(t,n),isExcluded:e._state.isExcludeRefined(t,n)}}):[]}if(e._state.isDisjunctiveFacet(t)){var i=Jn(e.disjunctiveFacets,r);return i?so(i.data,function(r,n){return{name:n,count:r,isRefined:e._state.isDisjunctiveFacetRefined(t,n)}}):[]}if(e._state.isHierarchicalFacet(t))return Jn(e.hierarchicalFacets,r)}(this,e);if(!r)throw new Error(e+" is not a retrieved facet.");var n=zo({},t,{sortBy:$c.DEFAULT_SORT});if(Ht(n.sortBy)){var i=Uc(n.sortBy,$c.DEFAULT_SORT);return Ht(r)?ds(r,i[0],i[1]):Kc(Hc(ds,i[0],i[1]),r)}if(_e(n.sortBy))return Ht(r)?r.sort(n.sortBy):Kc(qc(Yc,n.sortBy),r);throw new Error("options.sortBy is optional but if defined it must be either an array of string (predicates) or a sorting function")},$c.prototype.getFacetStats=function(e){if(this._state.isConjunctiveFacet(e))return Gc(this.facets,e);if(this._state.isDisjunctiveFacet(e))return Gc(this.disjunctiveFacets,e);throw new Error(e+" is not present in `facets` or `disjunctiveFacets`")},$c.prototype.getRefinements=function(){var e=this._state,t=this,r=[];return no(e.facetsRefinements,function(n,i){no(n,function(n){r.push(Xc(e,"facet",i,n,t.facets))})}),no(e.facetsExcludes,function(n,i){no(n,function(n){r.push(Xc(e,"exclude",i,n,t.facets))})}),no(e.disjunctiveFacetsRefinements,function(n,i){no(n,function(n){r.push(Xc(e,"disjunctive",i,n,t.disjunctiveFacets))})}),no(e.hierarchicalFacetsRefinements,function(n,i){no(n,function(n){r.push(function(e,t,r,n){for(var i=Jn(n,{name:t}),a=e.getHierarchicalFacetByName(t),o=r.split(a.separator),s=o[o.length-1],c=0;void 0!==i&&c<o.length;++c)i=Jn(i.data,{name:o[c]});var u=Rn(i,"count"),l=Rn(i,"exhaustive");return{type:"hierarchical",attributeName:t,name:s,count:u||0,exhaustive:l||!1}}(e,i,n,t.hierarchicalFacets))})}),no(e.numericRefinements,function(e,t){no(e,function(e,n){no(e,function(e){r.push({type:"numeric",attributeName:t,name:e,numericValue:e,operator:n})})})}),no(e.tagRefinements,function(e){r.push({type:"tag",attributeName:"_tags",name:e})}),r};var Zc=$c,eu=function(e){return e&&"object"==typeof e&&"function"==typeof e.copy&&"function"==typeof e.fill&&"function"==typeof e.readUInt8},tu=O(function(e){"function"==typeof Object.create?e.exports=function(e,t){e.super_=t,e.prototype=Object.create(t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}})}:e.exports=function(e,t){e.super_=t;var r=function(){};r.prototype=t.prototype,e.prototype=new r,e.prototype.constructor=e}}),ru=O(function(e,t){var r=/%[sdj%]/g;t.format=function(e){if(!m(e)){for(var t=[],n=0;n<arguments.length;n++)t.push(a(arguments[n]));return t.join(" ")}n=1;for(var i=arguments,o=i.length,s=String(e).replace(r,function(e){if("%%"===e)return"%";if(n>=o)return e;switch(e){case"%s":return String(i[n++]);case"%d":return Number(i[n++]);case"%j":try{return JSON.stringify(i[n++])}catch(e){return"[Circular]"}default:return e}}),c=i[n];n<o;c=i[++n])p(c)||!y(c)?s+=" "+c:s+=" "+a(c);return s},t.deprecate=function(e,r){if(v(E.process))return function(){return t.deprecate(e,r).apply(this,arguments)};if(!0===N.noDeprecation)return e;var n=!1;return function(){if(!n){if(N.throwDeprecation)throw new Error(r);N.traceDeprecation?console.trace(r):console.error(r),n=!0}return e.apply(this,arguments)}};var n,i={};function a(e,r){var n={seen:[],stylize:s};return arguments.length>=3&&(n.depth=arguments[2]),arguments.length>=4&&(n.colors=arguments[3]),h(r)?n.showHidden=r:r&&t._extend(n,r),v(n.showHidden)&&(n.showHidden=!1),v(n.depth)&&(n.depth=2),v(n.colors)&&(n.colors=!1),v(n.customInspect)&&(n.customInspect=!0),n.colors&&(n.stylize=o),c(n,e,n.depth)}function o(e,t){var r=a.styles[t];return r?"["+a.colors[r][0]+"m"+e+"["+a.colors[r][1]+"m":e}function s(e,t){return e}function c(e,r,n){if(e.customInspect&&r&&_(r.inspect)&&r.inspect!==t.inspect&&(!r.constructor||r.constructor.prototype!==r)){var i=r.inspect(n,e);return m(i)||(i=c(e,i,n)),i}var a=function(e,t){if(v(t))return e.stylize("undefined","undefined");if(m(t)){var r="'"+JSON.stringify(t).replace(/^"|"$/g,"").replace(/'/g,"\\'").replace(/\\"/g,'"')+"'";return e.stylize(r,"string")}if(d(t))return e.stylize(""+t,"number");if(h(t))return e.stylize(""+t,"boolean");if(p(t))return e.stylize("null","null")}(e,r);if(a)return a;var o=Object.keys(r),s=function(e){var t={};return e.forEach(function(e,r){t[e]=!0}),t}(o);if(e.showHidden&&(o=Object.getOwnPropertyNames(r)),R(r)&&(o.indexOf("message")>=0||o.indexOf("description")>=0))return u(r);if(0===o.length){if(_(r)){var y=r.name?": "+r.name:"";return e.stylize("[Function"+y+"]","special")}if(g(r))return e.stylize(RegExp.prototype.toString.call(r),"regexp");if(b(r))return e.stylize(Date.prototype.toString.call(r),"date");if(R(r))return u(r)}var x,w="",S=!1,F=["{","}"];(f(r)&&(S=!0,F=["[","]"]),_(r))&&(w=" [Function"+(r.name?": "+r.name:"")+"]");return g(r)&&(w=" "+RegExp.prototype.toString.call(r)),b(r)&&(w=" "+Date.prototype.toUTCString.call(r)),R(r)&&(w=" "+u(r)),0!==o.length||S&&0!=r.length?n<0?g(r)?e.stylize(RegExp.prototype.toString.call(r),"regexp"):e.stylize("[Object]","special"):(e.seen.push(r),x=S?function(e,t,r,n,i){for(var a=[],o=0,s=t.length;o<s;++o)j(t,String(o))?a.push(l(e,t,r,n,String(o),!0)):a.push("");return i.forEach(function(i){i.match(/^\d+$/)||a.push(l(e,t,r,n,i,!0))}),a}(e,r,n,s,o):o.map(function(t){return l(e,r,n,s,t,S)}),e.seen.pop(),function(e,t,r){if(e.reduce(function(e,t){return 0,t.indexOf("\n")>=0&&0,e+t.replace(/\u001b\[\d\d?m/g,"").length+1},0)>60)return r[0]+(""===t?"":t+"\n ")+" "+e.join(",\n ")+" "+r[1];return r[0]+t+" "+e.join(", ")+" "+r[1]}(x,w,F)):F[0]+w+F[1]}function u(e){return"["+Error.prototype.toString.call(e)+"]"}function l(e,t,r,n,i,a){var o,s,u;if((u=Object.getOwnPropertyDescriptor(t,i)||{value:t[i]}).get?s=u.set?e.stylize("[Getter/Setter]","special"):e.stylize("[Getter]","special"):u.set&&(s=e.stylize("[Setter]","special")),j(n,i)||(o="["+i+"]"),s||(e.seen.indexOf(u.value)<0?(s=p(r)?c(e,u.value,null):c(e,u.value,r-1)).indexOf("\n")>-1&&(s=a?s.split("\n").map(function(e){return" "+e}).join("\n").substr(2):"\n"+s.split("\n").map(function(e){return" "+e}).join("\n")):s=e.stylize("[Circular]","special")),v(o)){if(a&&i.match(/^\d+$/))return s;(o=JSON.stringify(""+i)).match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)?(o=o.substr(1,o.length-2),o=e.stylize(o,"name")):(o=o.replace(/'/g,"\\'").replace(/\\"/g,'"').replace(/(^"|"$)/g,"'"),o=e.stylize(o,"string"))}return o+": "+s}function f(e){return Array.isArray(e)}function h(e){return"boolean"==typeof e}function p(e){return null===e}function d(e){return"number"==typeof e}function m(e){return"string"==typeof e}function v(e){return void 0===e}function g(e){return y(e)&&"[object RegExp]"===x(e)}function y(e){return"object"==typeof e&&null!==e}function b(e){return y(e)&&"[object Date]"===x(e)}function R(e){return y(e)&&("[object Error]"===x(e)||e instanceof Error)}function _(e){return"function"==typeof e}function x(e){return Object.prototype.toString.call(e)}function w(e){return e<10?"0"+e.toString(10):e.toString(10)}t.debuglog=function(e){if(v(n)&&(n=N.env.NODE_DEBUG||""),e=e.toUpperCase(),!i[e])if(new RegExp("\\b"+e+"\\b","i").test(n)){var r=N.pid;i[e]=function(){var n=t.format.apply(t,arguments);console.error("%s %d: %s",e,r,n)}}else i[e]=function(){};return i[e]},t.inspect=a,a.colors={bold:[1,22],italic:[3,23],underline:[4,24],inverse:[7,27],white:[37,39],grey:[90,39],black:[30,39],blue:[34,39],cyan:[36,39],green:[32,39],magenta:[35,39],red:[31,39],yellow:[33,39]},a.styles={special:"cyan",number:"yellow",boolean:"yellow",undefined:"grey",null:"bold",string:"green",date:"magenta",regexp:"red"},t.isArray=f,t.isBoolean=h,t.isNull=p,t.isNullOrUndefined=function(e){return null==e},t.isNumber=d,t.isString=m,t.isSymbol=function(e){return"symbol"==typeof e},t.isUndefined=v,t.isRegExp=g,t.isObject=y,t.isDate=b,t.isError=R,t.isFunction=_,t.isPrimitive=function(e){return null===e||"boolean"==typeof e||"number"==typeof e||"string"==typeof e||"symbol"==typeof e||void 0===e},t.isBuffer=eu;var S=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];function j(e,t){return Object.prototype.hasOwnProperty.call(e,t)}t.log=function(){var e,r;console.log("%s - %s",(e=new Date,r=[w(e.getHours()),w(e.getMinutes()),w(e.getSeconds())].join(":"),[e.getDate(),S[e.getMonth()],r].join(" ")),t.format.apply(t,arguments))},t.inherits=tu,t._extend=function(e,t){if(!t||!y(t))return e;for(var r=Object.keys(t),n=r.length;n--;)e[r[n]]=t[r[n]];return e}});ru.format,ru.deprecate,ru.debuglog,ru.inspect,ru.isArray,ru.isBoolean,ru.isNull,ru.isNullOrUndefined,ru.isNumber,ru.isString,ru.isSymbol,ru.isUndefined,ru.isRegExp,ru.isObject,ru.isDate,ru.isError,ru.isFunction,ru.isPrimitive,ru.isBuffer,ru.log,ru.inherits,ru._extend;function nu(){this._events=this._events||{},this._maxListeners=this._maxListeners||void 0}var iu=nu;function au(e){return"function"==typeof e}function ou(e){return"object"==typeof e&&null!==e}function su(e){return void 0===e}function cu(e,t){this.main=e,this.fn=t,this.lastResults=null}nu.EventEmitter=nu,nu.prototype._events=void 0,nu.prototype._maxListeners=void 0,nu.defaultMaxListeners=10,nu.prototype.setMaxListeners=function(e){if("number"!=typeof e||e<0||isNaN(e))throw TypeError("n must be a positive number");return this._maxListeners=e,this},nu.prototype.emit=function(e){var t,r,n,i,a,o;if(this._events||(this._events={}),"error"===e&&(!this._events.error||ou(this._events.error)&&!this._events.error.length)){if((t=arguments[1])instanceof Error)throw t;var s=new Error('Uncaught, unspecified "error" event. ('+t+")");throw s.context=t,s}if(su(r=this._events[e]))return!1;if(au(r))switch(arguments.length){case 1:r.call(this);break;case 2:r.call(this,arguments[1]);break;case 3:r.call(this,arguments[1],arguments[2]);break;default:i=Array.prototype.slice.call(arguments,1),r.apply(this,i)}else if(ou(r))for(i=Array.prototype.slice.call(arguments,1),n=(o=r.slice()).length,a=0;a<n;a++)o[a].apply(this,i);return!0},nu.prototype.addListener=function(e,t){var r;if(!au(t))throw TypeError("listener must be a function");return this._events||(this._events={}),this._events.newListener&&this.emit("newListener",e,au(t.listener)?t.listener:t),this._events[e]?ou(this._events[e])?this._events[e].push(t):this._events[e]=[this._events[e],t]:this._events[e]=t,ou(this._events[e])&&!this._events[e].warned&&(r=su(this._maxListeners)?nu.defaultMaxListeners:this._maxListeners)&&r>0&&this._events[e].length>r&&(this._events[e].warned=!0,console.error("(node) warning: possible EventEmitter memory leak detected. %d listeners added. Use emitter.setMaxListeners() to increase limit.",this._events[e].length),"function"==typeof console.trace&&console.trace()),this},nu.prototype.on=nu.prototype.addListener,nu.prototype.once=function(e,t){if(!au(t))throw TypeError("listener must be a function");var r=!1;function n(){this.removeListener(e,n),r||(r=!0,t.apply(this,arguments))}return n.listener=t,this.on(e,n),this},nu.prototype.removeListener=function(e,t){var r,n,i,a;if(!au(t))throw TypeError("listener must be a function");if(!this._events||!this._events[e])return this;if(i=(r=this._events[e]).length,n=-1,r===t||au(r.listener)&&r.listener===t)delete this._events[e],this._events.removeListener&&this.emit("removeListener",e,t);else if(ou(r)){for(a=i;a-- >0;)if(r[a]===t||r[a].listener&&r[a].listener===t){n=a;break}if(n<0)return this;1===r.length?(r.length=0,delete this._events[e]):r.splice(n,1),this._events.removeListener&&this.emit("removeListener",e,t)}return this},nu.prototype.removeAllListeners=function(e){var t,r;if(!this._events)return this;if(!this._events.removeListener)return 0===arguments.length?this._events={}:this._events[e]&&delete this._events[e],this;if(0===arguments.length){for(t in this._events)"removeListener"!==t&&this.removeAllListeners(t);return this.removeAllListeners("removeListener"),this._events={},this}if(au(r=this._events[e]))this.removeListener(e,r);else if(r)for(;r.length;)this.removeListener(e,r[r.length-1]);return delete this._events[e],this},nu.prototype.listeners=function(e){return this._events&&this._events[e]?au(this._events[e])?[this._events[e]]:this._events[e].slice():[]},nu.prototype.listenerCount=function(e){if(this._events){var t=this._events[e];if(au(t))return 1;if(t)return t.length}return 0},nu.listenerCount=function(e,t){return e.listenerCount(t)},ru.inherits(cu,iu.EventEmitter),cu.prototype.detach=function(){this.removeAllListeners(),this.main.detachDerivedHelper(this)},cu.prototype.getModifiedState=function(e){return this.fn(e)};var uu=cu,lu={_getQueries:function(e,t){var r=[];return r.push({indexName:e,params:lu._getHitsSearchParams(t)}),no(t.getRefinedDisjunctiveFacets(),function(n){r.push({indexName:e,params:lu._getDisjunctiveFacetSearchParams(t,n)})}),no(t.getRefinedHierarchicalFacets(),function(n){var i=t.getHierarchicalFacetByName(n),a=t.getHierarchicalRefinement(n),o=t._getHierarchicalFacetSeparator(i);a.length>0&&a[0].split(o).length>1&&r.push({indexName:e,params:lu._getDisjunctiveFacetSearchParams(t,n,!0)})}),r},_getHitsSearchParams:function(e){var t=e.facets.concat(e.disjunctiveFacets).concat(lu._getHitsHierarchicalFacetsAttributes(e)),r=lu._getFacetFilters(e),n=lu._getNumericFilters(e),i={facets:t,tagFilters:lu._getTagFilters(e)};return r.length>0&&(i.facetFilters=r),n.length>0&&(i.numericFilters=n),Yo(e.getQueryParams(),i)},_getDisjunctiveFacetSearchParams:function(e,t,r){var n=lu._getFacetFilters(e,t,r),i=lu._getNumericFilters(e,t),a={hitsPerPage:1,page:0,attributesToRetrieve:[],attributesToHighlight:[],attributesToSnippet:[],tagFilters:lu._getTagFilters(e),analytics:!1,clickAnalytics:!1},o=e.getHierarchicalFacetByName(t);return a.facets=o?lu._getDisjunctiveHierarchicalFacetAttribute(e,o,r):t,i.length>0&&(a.numericFilters=i),n.length>0&&(a.facetFilters=n),Yo(e.getQueryParams(),a)},_getNumericFilters:function(e,t){if(e.numericFilters)return e.numericFilters;var r=[];return no(e.numericRefinements,function(e,n){no(e,function(e,i){t!==n&&no(e,function(e){if(Ht(e)){var t=so(e,function(e){return n+i+e});r.push(t)}else r.push(n+i+e)})})}),r},_getTagFilters:function(e){return e.tagFilters?e.tagFilters:e.tagRefinements.join(",")},_getFacetFilters:function(e,t,r){var n=[];return no(e.facetsRefinements,function(e,t){no(e,function(e){n.push(t+":"+e)})}),no(e.facetsExcludes,function(e,t){no(e,function(e){n.push(t+":-"+e)})}),no(e.disjunctiveFacetsRefinements,function(e,r){if(r!==t&&e&&0!==e.length){var i=[];no(e,function(e){i.push(r+":"+e)}),n.push(i)}}),no(e.hierarchicalFacetsRefinements,function(i,a){var o=i[0];if(void 0!==o){var s,c,u=e.getHierarchicalFacetByName(a),l=e._getHierarchicalFacetSeparator(u),f=e._getHierarchicalRootPath(u);if(t===a){if(-1===o.indexOf(l)||!f&&!0===r||f&&f.split(l).length===o.split(l).length)return;f?(c=f.split(l).length-1,o=f):(c=o.split(l).length-2,o=o.slice(0,o.lastIndexOf(l))),s=u.attributes[c]}else c=o.split(l).length-1,s=u.attributes[c];s&&n.push([s+":"+o])}}),n},_getHitsHierarchicalFacetsAttributes:function(e){return lo(e.hierarchicalFacets,function(t,r){var n=e.getHierarchicalRefinement(r.name)[0];if(!n)return t.push(r.attributes[0]),t;var i=e._getHierarchicalFacetSeparator(r),a=n.split(i).length,o=r.attributes.slice(0,a+1);return t.concat(o)},[])},_getDisjunctiveHierarchicalFacetAttribute:function(e,t,r){var n=e._getHierarchicalFacetSeparator(t);if(!0===r){var i=e._getHierarchicalRootPath(t),a=0;return i&&(a=i.split(n).length),[t.attributes[a]]}var o=(e.getHierarchicalRefinement(t.name)[0]||"").split(n).length-1;return t.attributes.slice(0,o+1)},getSearchForFacetQuery:function(e,t,r,n){var i=n.isDisjunctiveFacet(e)?n.clearRefinements(e):n,a={facetQuery:t,facetName:e};return"number"==typeof r&&(a.maxFacetHits=r),Yo(lu._getHitsSearchParams(i),a)}},fu=lu;var hu=function(e,t,r,n){return Za(e,function(e,i,a){t(n,r(e),i,a)}),n};var pu=function(e,t){return function(r,n){return hu(r,e,t(n),{})}},du=Object.prototype.toString,mu=pu(function(e,t,r){null!=t&&"function"!=typeof t.toString&&(t=du.call(t)),e[t]=r},Aa(Pn)),vu={advancedSyntax:"aS",allowTyposOnNumericTokens:"aTONT",analyticsTags:"aT",analytics:"a",aroundLatLngViaIP:"aLLVIP",aroundLatLng:"aLL",aroundPrecision:"aP",aroundRadius:"aR",attributesToHighlight:"aTH",attributesToRetrieve:"aTR",attributesToSnippet:"aTS",disjunctiveFacetsRefinements:"dFR",disjunctiveFacets:"dF",distinct:"d",facetsExcludes:"fE",facetsRefinements:"fR",facets:"f",getRankingInfo:"gRI",hierarchicalFacetsRefinements:"hFR",hierarchicalFacets:"hF",highlightPostTag:"hPoT",highlightPreTag:"hPrT",hitsPerPage:"hPP",ignorePlurals:"iP",index:"idx",insideBoundingBox:"iBB",insidePolygon:"iPg",length:"l",maxValuesPerFacet:"mVPF",minimumAroundRadius:"mAR",minProximity:"mP",minWordSizefor1Typo:"mWS1T",minWordSizefor2Typos:"mWS2T",numericFilters:"nF",numericRefinements:"nR",offset:"o",optionalWords:"oW",page:"p",queryType:"qT",query:"q",removeWordsIfNoResults:"rWINR",replaceSynonymsInHighlight:"rSIH",restrictSearchableAttributes:"rSA",synonyms:"s",tagFilters:"tF",tagRefinements:"tR",typoTolerance:"tT",optionalTagFilters:"oTF",optionalFacetFilters:"oFF",snippetEllipsisText:"sET",disableExactOnAttributes:"dEOA",enableExactOnSingleWordQuery:"eEOSWQ"},gu=mu(vu),yu={ENCODED_PARAMETERS:_r(gu),decode:function(e){return gu[e]},encode:function(e){return vu[e]}},bu=O(function(e,t){var r=Object.prototype.hasOwnProperty,n=function(){for(var e=[],t=0;t<256;++t)e.push("%"+((t<16?"0":"")+t.toString(16)).toUpperCase());return e}();t.arrayToObject=function(e,t){for(var r=t&&t.plainObjects?Object.create(null):{},n=0;n<e.length;++n)void 0!==e[n]&&(r[n]=e[n]);return r},t.merge=function(e,n,i){if(!n)return e;if("object"!=typeof n){if(Array.isArray(e))e.push(n);else{if("object"!=typeof e)return[e,n];(i.plainObjects||i.allowPrototypes||!r.call(Object.prototype,n))&&(e[n]=!0)}return e}if("object"!=typeof e)return[e].concat(n);var a=e;return Array.isArray(e)&&!Array.isArray(n)&&(a=t.arrayToObject(e,i)),Array.isArray(e)&&Array.isArray(n)?(n.forEach(function(n,a){r.call(e,a)?e[a]&&"object"==typeof e[a]?e[a]=t.merge(e[a],n,i):e.push(n):e[a]=n}),e):Object.keys(n).reduce(function(e,a){var o=n[a];return r.call(e,a)?e[a]=t.merge(e[a],o,i):e[a]=o,e},a)},t.assign=function(e,t){return Object.keys(t).reduce(function(e,r){return e[r]=t[r],e},e)},t.decode=function(e){try{return decodeURIComponent(e.replace(/\+/g," "))}catch(t){return e}},t.encode=function(e){if(0===e.length)return e;for(var t="string"==typeof e?e:String(e),r="",i=0;i<t.length;++i){var a=t.charCodeAt(i);45===a||46===a||95===a||126===a||a>=48&&a<=57||a>=65&&a<=90||a>=97&&a<=122?r+=t.charAt(i):a<128?r+=n[a]:a<2048?r+=n[192|a>>6]+n[128|63&a]:a<55296||a>=57344?r+=n[224|a>>12]+n[128|a>>6&63]+n[128|63&a]:(i+=1,a=65536+((1023&a)<<10|1023&t.charCodeAt(i)),r+=n[240|a>>18]+n[128|a>>12&63]+n[128|a>>6&63]+n[128|63&a])}return r},t.compact=function(e){for(var t=[{obj:{o:e},prop:"o"}],r=[],n=0;n<t.length;++n)for(var i=t[n],a=i.obj[i.prop],o=Object.keys(a),s=0;s<o.length;++s){var c=o[s],u=a[c];"object"==typeof u&&null!==u&&-1===r.indexOf(u)&&(t.push({obj:a,prop:c}),r.push(u))}return function(e){for(var t;e.length;){var r=e.pop();if(t=r.obj[r.prop],Array.isArray(t)){for(var n=[],i=0;i<t.length;++i)void 0!==t[i]&&n.push(t[i]);r.obj[r.prop]=n}}return t}(t)},t.isRegExp=function(e){return"[object RegExp]"===Object.prototype.toString.call(e)},t.isBuffer=function(e){return null!==e&&void 0!==e&&!!(e.constructor&&e.constructor.isBuffer&&e.constructor.isBuffer(e))}}),Ru=(bu.arrayToObject,bu.merge,bu.assign,bu.decode,bu.encode,bu.compact,bu.isRegExp,bu.isBuffer,String.prototype.replace),_u=/%20/g,xu={default:"RFC3986",formatters:{RFC1738:function(e){return Ru.call(e,_u,"+")},RFC3986:function(e){return e}},RFC1738:"RFC1738",RFC3986:"RFC3986"},wu={brackets:function(e){return e+"[]"},indices:function(e,t){return e+"["+t+"]"},repeat:function(e){return e}},Su=Date.prototype.toISOString,ju={delimiter:"&",encode:!0,encoder:bu.encode,encodeValuesOnly:!1,serializeDate:function(e){return Su.call(e)},skipNulls:!1,strictNullHandling:!1},Fu=function e(t,r,n,i,a,o,s,c,u,l,f,h){var p=t;if("function"==typeof s)p=s(r,p);else if(p instanceof Date)p=l(p);else if(null===p){if(i)return o&&!h?o(r,ju.encoder):r;p=""}if("string"==typeof p||"number"==typeof p||"boolean"==typeof p||bu.isBuffer(p))return o?[f(h?r:o(r,ju.encoder))+"="+f(o(p,ju.encoder))]:[f(r)+"="+f(String(p))];var d,m=[];if(void 0===p)return m;if(Array.isArray(s))d=s;else{var v=Object.keys(p);d=c?v.sort(c):v}for(var g=0;g<d.length;++g){var y=d[g];a&&null===p[y]||(m=Array.isArray(p)?m.concat(e(p[y],n(r,y),n,i,a,o,s,c,u,l,f,h)):m.concat(e(p[y],r+(u?"."+y:"["+y+"]"),n,i,a,o,s,c,u,l,f,h)))}return m},Pu=Object.prototype.hasOwnProperty,Nu={allowDots:!1,allowPrototypes:!1,arrayLimit:20,decoder:bu.decode,delimiter:"&",depth:5,parameterLimit:1e3,plainObjects:!1,strictNullHandling:!1},Eu=function(e,t,r){if(e){var n=r.allowDots?e.replace(/\.([^.[]+)/g,"[$1]"):e,i=/(\[[^[\]]*])/g,a=/(\[[^[\]]*])/.exec(n),o=a?n.slice(0,a.index):n,s=[];if(o){if(!r.plainObjects&&Pu.call(Object.prototype,o)&&!r.allowPrototypes)return;s.push(o)}for(var c=0;null!==(a=i.exec(n))&&c<r.depth;){if(c+=1,!r.plainObjects&&Pu.call(Object.prototype,a[1].slice(1,-1))&&!r.allowPrototypes)return;s.push(a[1])}return a&&s.push("["+n.slice(a.index)+"]"),function(e,t,r){for(var n=t,i=e.length-1;i>=0;--i){var a,o=e[i];if("[]"===o)a=(a=[]).concat(n);else{a=r.plainObjects?Object.create(null):{};var s="["===o.charAt(0)&&"]"===o.charAt(o.length-1)?o.slice(1,-1):o,c=parseInt(s,10);!isNaN(c)&&o!==s&&String(c)===s&&c>=0&&r.parseArrays&&c<=r.arrayLimit?(a=[])[c]=n:a[s]=n}n=a}return n}(s,t,r)}},Ou=function(e,t){var r=t?bu.assign({},t):{};if(null!==r.decoder&&void 0!==r.decoder&&"function"!=typeof r.decoder)throw new TypeError("Decoder has to be a function.");if(r.ignoreQueryPrefix=!0===r.ignoreQueryPrefix,r.delimiter="string"==typeof r.delimiter||bu.isRegExp(r.delimiter)?r.delimiter:Nu.delimiter,r.depth="number"==typeof r.depth?r.depth:Nu.depth,r.arrayLimit="number"==typeof r.arrayLimit?r.arrayLimit:Nu.arrayLimit,r.parseArrays=!1!==r.parseArrays,r.decoder="function"==typeof r.decoder?r.decoder:Nu.decoder,r.allowDots="boolean"==typeof r.allowDots?r.allowDots:Nu.allowDots,r.plainObjects="boolean"==typeof r.plainObjects?r.plainObjects:Nu.plainObjects,r.allowPrototypes="boolean"==typeof r.allowPrototypes?r.allowPrototypes:Nu.allowPrototypes,r.parameterLimit="number"==typeof r.parameterLimit?r.parameterLimit:Nu.parameterLimit,r.strictNullHandling="boolean"==typeof r.strictNullHandling?r.strictNullHandling:Nu.strictNullHandling,""===e||null===e||void 0===e)return r.plainObjects?Object.create(null):{};for(var n="string"==typeof e?function(e,t){for(var r={},n=t.ignoreQueryPrefix?e.replace(/^\?/,""):e,i=t.parameterLimit===1/0?void 0:t.parameterLimit,a=n.split(t.delimiter,i),o=0;o<a.length;++o){var s,c,u=a[o],l=u.indexOf("]="),f=-1===l?u.indexOf("="):l+1;-1===f?(s=t.decoder(u,Nu.decoder),c=t.strictNullHandling?null:""):(s=t.decoder(u.slice(0,f),Nu.decoder),c=t.decoder(u.slice(f+1),Nu.decoder)),Pu.call(r,s)?r[s]=[].concat(r[s]).concat(c):r[s]=c}return r}(e,r):e,i=r.plainObjects?Object.create(null):{},a=Object.keys(n),o=0;o<a.length;++o){var s=a[o],c=Eu(s,n[s],r);i=bu.merge(i,c,r)}return bu.compact(i)},Tu=function(e,t){var r=e,n=t?bu.assign({},t):{};if(null!==n.encoder&&void 0!==n.encoder&&"function"!=typeof n.encoder)throw new TypeError("Encoder has to be a function.");var i=void 0===n.delimiter?ju.delimiter:n.delimiter,a="boolean"==typeof n.strictNullHandling?n.strictNullHandling:ju.strictNullHandling,o="boolean"==typeof n.skipNulls?n.skipNulls:ju.skipNulls,s="boolean"==typeof n.encode?n.encode:ju.encode,c="function"==typeof n.encoder?n.encoder:ju.encoder,u="function"==typeof n.sort?n.sort:null,l=void 0!==n.allowDots&&n.allowDots,f="function"==typeof n.serializeDate?n.serializeDate:ju.serializeDate,h="boolean"==typeof n.encodeValuesOnly?n.encodeValuesOnly:ju.encodeValuesOnly;if(void 0===n.format)n.format=xu.default;else if(!Object.prototype.hasOwnProperty.call(xu.formatters,n.format))throw new TypeError("Unknown format option provided.");var p,d,m=xu.formatters[n.format];"function"==typeof n.filter?r=(d=n.filter)("",r):Array.isArray(n.filter)&&(p=d=n.filter);var v,g=[];if("object"!=typeof r||null===r)return"";v=n.arrayFormat in wu?n.arrayFormat:"indices"in n?n.indices?"indices":"repeat":"indices";var y=wu[v];p||(p=Object.keys(r)),u&&p.sort(u);for(var b=0;b<p.length;++b){var R=p[b];o&&null===r[R]||(g=g.concat(Fu(r[R],R,y,a,o,s?c:null,d,u,l,f,m,h)))}var _=g.join(i),x=!0===n.addQueryPrefix?"?":"";return _.length>0?x+_:""},Au=$a(function(e,t,r){var n=1;if(r.length){var i=oc(r,rc(Au));n|=32}return Ic(e,n,t,r,i)});Au.placeholder={};var Cu=Au;var Iu=function(e,t){return Qc(e,t,function(t,r){return wn(e,r)})},ku=La(function(e,t){return null==e?{}:Iu(e,t)});var qu=function(e,t){var r={};return t=Tn(t,3),Za(e,function(e,n,i){ei(r,t(e,n,i),e)}),r};var Mu=function(e,t){var r={};return t=Tn(t,3),Za(e,function(e,n,i){ei(r,n,t(e,n,i))}),r},Hu=bu.encode;function Lu(e){return wa(e)?Mu(e,Lu):Ht(e)?so(e,Lu):Ro(e)?Hu(e):e}var Du=["dFR","fR","nR","hFR","tR"],Uu=yu.ENCODED_PARAMETERS;function Bu(e,t,r,n){if(null!==e&&(r=r.replace(e,""),n=n.replace(e,"")),r=t[r]||r,n=t[n]||n,-1!==Uu.indexOf(r)||-1!==Uu.indexOf(n)){if("q"===r)return-1;if("q"===n)return 1;var i=-1!==Du.indexOf(r),a=-1!==Du.indexOf(n);if(i&&!a)return 1;if(a&&!i)return-1}return r.localeCompare(n)}var Qu={getStateFromQueryString:function(e,t){var r=t&&t.prefix||"",n=t&&t.mapping||{},i=mu(n),a=Ou(e),o=new RegExp("^"+r),s=qu(a,function(e,t){var n=r&&o.test(t)?t.replace(o,""):t;return yu.decode(i[n]||n)||n}),c=rs._parseNumbers(s);return ku(c,rs.PARAMETERS)},getUnrecognizedParametersInQueryString:function(e,t){var r=t&&t.prefix,n=t&&t.mapping||{},i=mu(n),a={},o=Ou(e);if(r){var s=new RegExp("^"+r);no(o,function(e,t){s.test(t)||(a[t]=e)})}else no(o,function(e,t){yu.decode(i[t]||t)||(a[t]=e)});return a},getQueryStringFromState:function(e,t){var r=t&&t.moreAttributes,n=t&&t.prefix||"",i=t&&t.mapping||{},a=t&&t.safe||!1,o=mu(i),s=a?e:Lu(e),c=qu(s,function(e,t){var r=yu.encode(t);return n+(i[r]||r)}),u=""===n?null:new RegExp("^"+n),l=Cu(Bu,null,u,o);if(!Gn(r)){var f=Tu(c,{encode:a,sort:l}),h=Tu(r,{encode:a});return f?f+"&"+h:h}return Tu(c,{encode:a,sort:l})}},zu="2.24.0";function Vu(e,t,r){e.addAlgoliaAgent?$u(e)||e.addAlgoliaAgent("JS Helper "+zu):console.log("Please upgrade to the newest version of the JS Client."),this.setClient(e);var n=r||{};n.index=t,this.state=rs.make(n),this.lastResults=null,this._queryId=0,this._lastQueryIdReceived=-1,this.derivedHelpers=[],this._currentNbQueries=0}function Wu(e){if(e<0)throw new Error("Page requested below 0.");return this._change(this.state.setPage(e)),this}function Ju(){return this.state.page}function $u(e){var t=e._ua;return!!t&&-1!==t.indexOf("JS Helper")}ru.inherits(Vu,iu.EventEmitter),Vu.prototype.search=function(){return this._search(),this},Vu.prototype.getQuery=function(){var e=this.state;return fu._getHitsSearchParams(e)},Vu.prototype.searchOnce=function(e,t){var r=e?this.state.setQueryParameters(e):this.state,n=fu._getQueries(r.index,r),i=this;return this._currentNbQueries++,this.emit("searchOnce",r),t?this.client.search(n,function(e,n){i._currentNbQueries--,0===i._currentNbQueries&&i.emit("searchQueueEmpty"),t(e,e?null:new Zc(r,n.results),r)}):this.client.search(n).then(function(e){return i._currentNbQueries--,0===i._currentNbQueries&&i.emit("searchQueueEmpty"),{content:new Zc(r,e.results),state:r,_originalResponse:e}},function(e){throw i._currentNbQueries--,0===i._currentNbQueries&&i.emit("searchQueueEmpty"),e})},Vu.prototype.searchForFacetValues=function(e,t,r,n){var i=this.state.setQueryParameters(n||{}),a=this.client.initIndex(i.index),o=i.isDisjunctiveFacet(e),s=fu.getSearchForFacetQuery(e,t,r,i);this._currentNbQueries++;var c=this;return this.emit("searchForFacetValues",i,e,t),a.searchForFacetValues(s).then(function(t){return c._currentNbQueries--,0===c._currentNbQueries&&c.emit("searchQueueEmpty"),t.facetHits=no(t.facetHits,function(t){t.isRefined=o?i.isDisjunctiveFacetRefined(e,t.value):i.isFacetRefined(e,t.value)}),t},function(e){throw c._currentNbQueries--,0===c._currentNbQueries&&c.emit("searchQueueEmpty"),e})},Vu.prototype.setQuery=function(e){return this._change(this.state.setPage(0).setQuery(e)),this},Vu.prototype.clearRefinements=function(e){return this._change(this.state.setPage(0).clearRefinements(e)),this},Vu.prototype.clearTags=function(){return this._change(this.state.setPage(0).clearTags()),this},Vu.prototype.addDisjunctiveFacetRefinement=function(e,t){return this._change(this.state.setPage(0).addDisjunctiveFacetRefinement(e,t)),this},Vu.prototype.addDisjunctiveRefine=function(){return this.addDisjunctiveFacetRefinement.apply(this,arguments)},Vu.prototype.addHierarchicalFacetRefinement=function(e,t){return this._change(this.state.setPage(0).addHierarchicalFacetRefinement(e,t)),this},Vu.prototype.addNumericRefinement=function(e,t,r){return this._change(this.state.setPage(0).addNumericRefinement(e,t,r)),this},Vu.prototype.addFacetRefinement=function(e,t){return this._change(this.state.setPage(0).addFacetRefinement(e,t)),this},Vu.prototype.addRefine=function(){return this.addFacetRefinement.apply(this,arguments)},Vu.prototype.addFacetExclusion=function(e,t){return this._change(this.state.setPage(0).addExcludeRefinement(e,t)),this},Vu.prototype.addExclude=function(){return this.addFacetExclusion.apply(this,arguments)},Vu.prototype.addTag=function(e){return this._change(this.state.setPage(0).addTagRefinement(e)),this},Vu.prototype.removeNumericRefinement=function(e,t,r){return this._change(this.state.setPage(0).removeNumericRefinement(e,t,r)),this},Vu.prototype.removeDisjunctiveFacetRefinement=function(e,t){return this._change(this.state.setPage(0).removeDisjunctiveFacetRefinement(e,t)),this},Vu.prototype.removeDisjunctiveRefine=function(){return this.removeDisjunctiveFacetRefinement.apply(this,arguments)},Vu.prototype.removeHierarchicalFacetRefinement=function(e){return this._change(this.state.setPage(0).removeHierarchicalFacetRefinement(e)),this},Vu.prototype.removeFacetRefinement=function(e,t){return this._change(this.state.setPage(0).removeFacetRefinement(e,t)),this},Vu.prototype.removeRefine=function(){return this.removeFacetRefinement.apply(this,arguments)},Vu.prototype.removeFacetExclusion=function(e,t){return this._change(this.state.setPage(0).removeExcludeRefinement(e,t)),this},Vu.prototype.removeExclude=function(){return this.removeFacetExclusion.apply(this,arguments)},Vu.prototype.removeTag=function(e){return this._change(this.state.setPage(0).removeTagRefinement(e)),this},Vu.prototype.toggleFacetExclusion=function(e,t){return this._change(this.state.setPage(0).toggleExcludeFacetRefinement(e,t)),this},Vu.prototype.toggleExclude=function(){return this.toggleFacetExclusion.apply(this,arguments)},Vu.prototype.toggleRefinement=function(e,t){return this.toggleFacetRefinement(e,t)},Vu.prototype.toggleFacetRefinement=function(e,t){return this._change(this.state.setPage(0).toggleFacetRefinement(e,t)),this},Vu.prototype.toggleRefine=function(){return this.toggleFacetRefinement.apply(this,arguments)},Vu.prototype.toggleTag=function(e){return this._change(this.state.setPage(0).toggleTagRefinement(e)),this},Vu.prototype.nextPage=function(){return this.setPage(this.state.page+1)},Vu.prototype.previousPage=function(){return this.setPage(this.state.page-1)},Vu.prototype.setCurrentPage=Wu,Vu.prototype.setPage=Wu,Vu.prototype.setIndex=function(e){return this._change(this.state.setPage(0).setIndex(e)),this},Vu.prototype.setQueryParameter=function(e,t){return this._change(this.state.setPage(0).setQueryParameter(e,t)),this},Vu.prototype.setState=function(e){return this._change(rs.make(e)),this},Vu.prototype.getState=function(e){return void 0===e?this.state:this.state.filter(e)},Vu.prototype.getStateAsQueryString=function(e){var t=e&&e.filters||["query","attribute:*"],r=this.getState(t);return Qu.getQueryStringFromState(r,e)},Vu.getConfigurationFromQueryString=Qu.getStateFromQueryString,Vu.getForeignConfigurationInQueryString=Qu.getUnrecognizedParametersInQueryString,Vu.prototype.setStateFromQueryString=function(e,t){var r=t&&t.triggerChange||!1,n=Qu.getStateFromQueryString(e,t),i=this.state.setQueryParameters(n);r?this.setState(i):this.overrideStateWithoutTriggeringChangeEvent(i)},Vu.prototype.overrideStateWithoutTriggeringChangeEvent=function(e){return this.state=new rs(e),this},Vu.prototype.isRefined=function(e,t){if(this.state.isConjunctiveFacet(e))return this.state.isFacetRefined(e,t);if(this.state.isDisjunctiveFacet(e))return this.state.isDisjunctiveFacetRefined(e,t);throw new Error(e+" is not properly defined in this helper configuration(use the facets or disjunctiveFacets keys to configure it)")},Vu.prototype.hasRefinements=function(e){return!Gn(this.state.getNumericRefinements(e))||(this.state.isConjunctiveFacet(e)?this.state.isFacetRefined(e):this.state.isDisjunctiveFacet(e)?this.state.isDisjunctiveFacetRefined(e):!!this.state.isHierarchicalFacet(e)&&this.state.isHierarchicalFacetRefined(e))},Vu.prototype.isExcluded=function(e,t){return this.state.isExcludeRefined(e,t)},Vu.prototype.isDisjunctiveRefined=function(e,t){return this.state.isDisjunctiveFacetRefined(e,t)},Vu.prototype.hasTag=function(e){return this.state.isTagRefined(e)},Vu.prototype.isTagRefined=function(){return this.hasTagRefinements.apply(this,arguments)},Vu.prototype.getIndex=function(){return this.state.index},Vu.prototype.getCurrentPage=Ju,Vu.prototype.getPage=Ju,Vu.prototype.getTags=function(){return this.state.tagRefinements},Vu.prototype.getQueryParameter=function(e){return this.state.getQueryParameter(e)},Vu.prototype.getRefinements=function(e){var t=[];if(this.state.isConjunctiveFacet(e)){var r=this.state.getConjunctiveRefinements(e);no(r,function(e){t.push({value:e,type:"conjunctive"})});var n=this.state.getExcludeRefinements(e);no(n,function(e){t.push({value:e,type:"exclude"})})}else if(this.state.isDisjunctiveFacet(e)){var i=this.state.getDisjunctiveRefinements(e);no(i,function(e){t.push({value:e,type:"disjunctive"})})}var a=this.state.getNumericRefinements(e);return no(a,function(e,r){t.push({value:e,operator:r,type:"numeric"})}),t},Vu.prototype.getNumericRefinement=function(e,t){return this.state.getNumericRefinement(e,t)},Vu.prototype.getHierarchicalFacetBreadcrumb=function(e){return this.state.getHierarchicalFacetBreadcrumb(e)},Vu.prototype._search=function(){var e=this.state,t=fu._getQueries(e.index,e),r=[{state:e,queriesCount:t.length,helper:this}];this.emit("search",e,this.lastResults);var n=so(this.derivedHelpers,function(t){var n=t.getModifiedState(e),i=fu._getQueries(n.index,n);return r.push({state:n,queriesCount:i.length,helper:t}),t.emit("search",n,t.lastResults),i}),i=t.concat(Na(n)),a=this._queryId++;this._currentNbQueries++,this.client.search(i,this._dispatchAlgoliaResponse.bind(this,r,a))},Vu.prototype._dispatchAlgoliaResponse=function(e,t,r,n){if(!(t<this._lastQueryIdReceived))if(this._currentNbQueries-=t-this._lastQueryIdReceived,this._lastQueryIdReceived=t,r)this.emit("error",r),0===this._currentNbQueries&&this.emit("searchQueueEmpty");else{0===this._currentNbQueries&&this.emit("searchQueueEmpty");var i=n.results;no(e,function(e){var t=e.state,r=e.queriesCount,n=e.helper,a=i.splice(0,r),o=n.lastResults=new Zc(t,a);n.emit("result",o,t)})}},Vu.prototype.containsRefinement=function(e,t,r,n){return e||0!==t.length||0!==r.length||0!==n.length},Vu.prototype._hasDisjunctiveRefinements=function(e){return this.state.disjunctiveRefinements[e]&&this.state.disjunctiveRefinements[e].length>0},Vu.prototype._change=function(e){e!==this.state&&(this.state=e,this.emit("change",this.state,this.lastResults))},Vu.prototype.clearCache=function(){return this.client.clearCache(),this},Vu.prototype.setClient=function(e){return this.client===e?this:(e.addAlgoliaAgent&&!$u(e)&&e.addAlgoliaAgent("JS Helper "+zu),this.client=e,this)},Vu.prototype.getClient=function(){return this.client},Vu.prototype.derive=function(e){var t=new uu(this,e);return this.derivedHelpers.push(t),t},Vu.prototype.detachDerivedHelper=function(e){var t=this.derivedHelpers.indexOf(e);if(-1===t)throw new Error("Derived helper already detached");this.derivedHelpers.splice(t,1)},Vu.prototype.hasPendingRequests=function(){return this._currentNbQueries>0};var Ku=Vu;function Yu(e,t,r){return new Ku(e,t,r)}Yu.version=zu,Yu.AlgoliaSearchHelper=Ku,Yu.SearchParameters=rs,Yu.SearchResults=Zc,Yu.url=Qu;var Gu=Yu,Xu=Gu.SearchParameters;function Zu(e,t){if(e===t)return!0;var r=Object.keys(e),n=Object.keys(t);if(r.length!==n.length)return!1;for(var i=Object.prototype.hasOwnProperty,a=0;a<r.length;a++)if(!i.call(t,r[a])||e[r[a]]!==t[r[a]])return!1;return!0}function el(e){return e.displayName||e.name||"UnknownComponent"}var tl=Promise.resolve(),rl=function(e){tl.then(e)};function nl(e){var t=e,r=[];return{getState:function(){return t},setState:function(e){t=e,r.forEach(function(e){return e()})},subscribe:function(e){return r.push(e),function(){r.splice(r.indexOf(e),1)}}}}var il={highlightPreTag:"<ais-highlight-0000000000>",highlightPostTag:"</ais-highlight-0000000000>"},al=function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")},ol=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}}(),sl=function(e,t,r){return t in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e},cl=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},ul=function(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)},ll=function(e,t){var r={};for(var n in e)t.indexOf(n)>=0||Object.prototype.hasOwnProperty.call(e,n)&&(r[n]=e[n]);return r},fl=function(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t},hl=function(){return function(e,t){if(Array.isArray(e))return e;if(Symbol.iterator in Object(e))return function(e,t){var r=[],n=!0,i=!1,a=void 0;try{for(var o,s=e[Symbol.iterator]();!(n=(o=s.next()).done)&&(r.push(o.value),!t||r.length!==t);n=!0);}catch(e){i=!0,a=e}finally{try{!n&&s.return&&s.return()}finally{if(i)throw a}}return r}(e,t);throw new TypeError("Invalid attempt to destructure non-iterable instance")}}(),pl=function(e){if(Array.isArray(e)){for(var t=0,r=Array(e.length);t<e.length;t++)r[t]=e[t];return r}return Array.from(e)};function dl(e){var t=e.indexName,r=e.initialState,n=void 0===r?{}:r,i=e.algoliaClient,a=e.resultsState,o=e.stalledSearchDelay,s=new Xu(cl({index:t},il)),c=null,u=Gu(i,t,s);u.on("result",y),u.on("error",b),u.on("search",function(){c||(c=setTimeout(function(){var e=Da(cl({},d.getState(),{isSearchStalled:!0}),"resultsFacetValues");d.setState(e)},o))});var l={},f={},h=u.state,p=function(e){var t=[],r=!1;function n(){r||(r=!0,rl(function(){r=!1,e()}))}return{registerWidget:function(e){return t.push(e),n(),function(){t.splice(t.indexOf(e),1),n()}},update:n,getWidgets:function(){return t}}}(function(){var e=v(d.getState().widgets);d.setState(cl({},d.getState(),{metadata:e,searching:!0})),g()}),d=nl({widgets:n,metadata:[],results:a||null,error:null,searching:!1,isSearchStalled:!0,searchingForFacetValues:!1}),m=!1;function v(e){return p.getWidgets().filter(function(e){return Boolean(e.getMetadata)}).map(function(t){return t.getMetadata(e)})}function g(){if(!m){var e=function(){f={};var e=p.getWidgets().filter(function(e){return Boolean(e.getSearchParameters)}).filter(function(e){return!(e.context.multiIndexContext||e.props.indexName!==t&&e.props.indexName)}).reduce(function(e,t){return t.getSearchParameters(e)},h);f[e.index]=t;var r=p.getWidgets().filter(function(e){return Boolean(e.getSearchParameters)}).filter(function(e){return e.context.multiIndexContext&&e.context.multiIndexContext.targetedIndex!==t||e.props.indexName&&e.props.indexName!==t}).reduce(function(e,t){var r=t.context.multiIndexContext?t.context.multiIndexContext.targetedIndex:t.props.indexName,n=Jn(e,function(e){return e.targetedIndex===r});return n?n.widgets.push(t):e.push({targetedIndex:r,widgets:[t]}),e},[]),n=p.getWidgets().filter(function(e){return Boolean(e.getSearchParameters)}).filter(function(e){return e.context.multiIndexContext&&e.context.multiIndexContext.targetedIndex===t||e.props.indexName&&e.props.indexName===t}).reduce(function(e,t){return t.getSearchParameters(e)},e);return f[n.index]=t,{sharedParameters:e,mainIndexParameters:n,derivatedWidgets:r}}(u.state),r=e.sharedParameters,n=e.mainIndexParameters,i=e.derivatedWidgets;Object.keys(l).forEach(function(e){return l[e].detach()}),l={},u.setState(r),i.forEach(function(e){var t=e.targetedIndex,n=u.derive(function(){var n=e.widgets.reduce(function(e,t){return t.getSearchParameters(e)},r);return f[n.index]=t,n});n.on("result",y),n.on("error",b),l[t]=n}),u.setState(n),u.search()}}function y(e){var t=d.getState(),r=t.results?t.results:{};r=!Gn(l)&&r.getFacetByName?{}:r,Gn(l)?r=e:r[f[e.index]]=e;var n=d.getState(),i=n.isSearchStalled;u.hasPendingRequests()||(clearTimeout(c),c=null,i=!1);var a=Da(cl({},n,{results:r,isSearchStalled:i,searching:!1,error:null}),"resultsFacetValues");d.setState(a)}function b(e){var t=d.getState(),r=t.isSearchStalled;u.hasPendingRequests()||(clearTimeout(c),r=!1);var n=Da(cl({},t,{isSearchStalled:r,error:e,searching:!1}),"resultsFacetValues");d.setState(n)}return{store:d,widgetsManager:p,getWidgetsIds:function(){return d.getState().metadata.reduce(function(e,t){return void 0!==t.id?e.concat(t.id):e},[])},onExternalStateUpdate:function(e){var t=v(e);d.setState(cl({},d.getState(),{widgets:e,metadata:t,searching:!0})),g()},transitionState:function(e){var t=d.getState().widgets;return p.getWidgets().filter(function(e){return Boolean(e.transitionState)}).reduce(function(e,r){return r.transitionState(t,e)},e)},onSearchForFacetValues:function(e){var t=e.facetName,r=e.query,n=e.maxFacetHits;d.setState(cl({},d.getState(),{searchingForFacetValues:!0})),u.searchForFacetValues(t,r,n).then(function(e){var n;d.setState(cl({},d.getState(),{resultsFacetValues:cl({},d.getState().resultsFacetValues,(n={},sl(n,t,e.facetHits),sl(n,"query",r),n)),searchingForFacetValues:!1}))},function(e){d.setState(cl({},d.getState(),{error:e,searchingForFacetValues:!1}))}).catch(function(e){setTimeout(function(){throw e})})},updateClient:function(e){u.setClient(e),g()},updateIndex:function(e){h=h.setIndex(e),g()},clearCache:function(){u.clearCache(),g()},skipSearch:function(){m=!0}}}var ml=function(e){function n(e){al(this,n);var t=fl(this,(n.__proto__||Object.getPrototypeOf(n)).call(this,e));t.isControlled=Boolean(e.searchState);var r=t.isControlled?e.searchState:{};return t.isUnmounting=!1,t.aisManager=dl({indexName:e.indexName,algoliaClient:e.algoliaClient,initialState:r,resultsState:e.resultsState,stalledSearchDelay:e.stalledSearchDelay}),t}return ul(n,e),ol(n,[{key:"componentWillReceiveProps",value:function(e){!function(e,t){if(!e.searchState&&t.searchState)throw new Error("You can't switch <InstantSearch> from being uncontrolled to controlled");if(e.searchState&&!t.searchState)throw new Error("You can't switch <InstantSearch> from being controlled to uncontrolled")}(this.props,e),this.props.indexName!==e.indexName&&this.aisManager.updateIndex(e.indexName),this.props.refresh!==e.refresh&&e.refresh&&this.aisManager.clearCache(),this.props.algoliaClient!==e.algoliaClient&&this.aisManager.updateClient(e.algoliaClient),this.isControlled&&this.aisManager.onExternalStateUpdate(e.searchState)}},{key:"componentWillUnmount",value:function(){this.isUnmounting=!0,this.aisManager.skipSearch()}},{key:"getChildContext",value:function(){return this._aisContextCache||(this._aisContextCache={ais:{onInternalStateUpdate:this.onWidgetsInternalStateUpdate.bind(this),createHrefForState:this.createHrefForState.bind(this),onSearchForFacetValues:this.onSearchForFacetValues.bind(this),onSearchStateChange:this.onSearchStateChange.bind(this),onSearchParameters:this.onSearchParameters.bind(this)}}),{ais:cl({},this._aisContextCache.ais,{store:this.aisManager.store,widgetsManager:this.aisManager.widgetsManager,mainTargetedIndex:this.props.indexName})}}},{key:"createHrefForState",value:function(e){return e=this.aisManager.transitionState(e),this.isControlled&&this.props.createURL?this.props.createURL(e,this.getKnownKeys()):"#"}},{key:"onWidgetsInternalStateUpdate",value:function(e){e=this.aisManager.transitionState(e),this.onSearchStateChange(e),this.isControlled||this.aisManager.onExternalStateUpdate(e)}},{key:"onSearchStateChange",value:function(e){this.props.onSearchStateChange&&!this.isUnmounting&&this.props.onSearchStateChange(e)}},{key:"onSearchParameters",value:function(e,t,r){if(this.props.onSearchParameters){var n=this.props.searchState?this.props.searchState:{};this.props.onSearchParameters(e,t,r,n)}}},{key:"onSearchForFacetValues",value:function(e){this.aisManager.onSearchForFacetValues(e)}},{key:"getKnownKeys",value:function(){return this.aisManager.getWidgetsIds()}},{key:"render",value:function(){var e=t.Children.count(this.props.children),n=this.props.root,i=n.Root,a=n.props;return 0===e?null:r.createElement(i,a,this.props.children)}}]),n}(t.Component);ml.defaultProps={stalledSearchDelay:200},ml.propTypes={indexName:L.string.isRequired,algoliaClient:L.object.isRequired,createURL:L.func,refresh:L.bool.isRequired,searchState:L.object,onSearchStateChange:L.func,onSearchParameters:L.func,resultsState:L.oneOfType([L.object,L.array]),children:L.node,root:L.shape({Root:L.oneOfType([L.string,L.func]),props:L.object}).isRequired,stalledSearchDelay:L.number},ml.childContextTypes={ais:L.object.isRequired};var vl="5.0.3";var gl=function(e){function n(e,t){al(this,n);var r=fl(this,(n.__proto__||Object.getPrototypeOf(n)).call(this,e)),i=t.ais.widgetsManager;return r.unregisterWidget=i.registerWidget(r),r}return ul(n,e),ol(n,[{key:"componentWillMount",value:function(){this.context.ais.onSearchParameters(this.getSearchParameters,this.getChildContext(),this.props)}},{key:"componentWillReceiveProps",value:function(e){this.props.indexName!==e.indexName&&this.context.ais.widgetsManager.update()}},{key:"componentWillUnmount",value:function(){this.unregisterWidget()}},{key:"getChildContext",value:function(){return{multiIndexContext:{targetedIndex:this.props.indexName}}}},{key:"getSearchParameters",value:function(e,t){return e.setIndex(this.props?this.props.indexName:t.indexName)}},{key:"render",value:function(){var e=t.Children.count(this.props.children),n=this.props.root,i=n.Root,a=n.props;return 0===e?null:r.createElement(i,a,this.props.children)}}]),n}(t.Component);gl.propTypes={indexName:L.string.isRequired,children:L.node,root:L.shape({Root:L.oneOfType([L.string,L.func]),props:L.object}).isRequired},gl.childContextTypes={multiIndexContext:L.object.isRequired},gl.contextTypes={ais:L.object.isRequired};var yl=O(function(e){"function"==typeof Object.create?e.exports=function(e,t){e.super_=t,e.prototype=Object.create(t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}})}:e.exports=function(e,t){e.super_=t;var r=function(){};r.prototype=t.prototype,e.prototype=new r,e.prototype.constructor=e}}),bl=Object.prototype.hasOwnProperty,Rl=Object.prototype.toString,_l=function(e,t,r){if("[object Function]"!==Rl.call(t))throw new TypeError("iterator must be a function");var n=e.length;if(n===+n)for(var i=0;i<n;i++)t.call(r,e[i],i,e);else for(var a in e)bl.call(e,a)&&t.call(r,e[a],a,e)};function xl(e,t){var r=_l,n=this;"function"==typeof Error.captureStackTrace?Error.captureStackTrace(this,this.constructor):n.stack=(new Error).stack||"Cannot get a stacktrace, browser is too old",this.name="AlgoliaSearchError",this.message=e||"Unknown error",t&&r(t,function(e,t){n[t]=e})}function wl(e,t){function r(){var r=Array.prototype.slice.call(arguments,0);"string"!=typeof r[0]&&r.unshift(t),xl.apply(this,r),this.name="AlgoliaSearch"+e+"Error"}return yl(r,xl),r}yl(xl,Error);var Sl={AlgoliaSearchError:xl,UnparsableJSON:wl("UnparsableJSON","Could not parse the incoming response as JSON, see err.more for details"),RequestTimeout:wl("RequestTimeout","Request timedout before getting a response"),Network:wl("Network","Network issue, see err.more for details"),JSONPScriptFail:wl("JSONPScriptFail","<script> was loaded but did not call our provided callback"),JSONPScriptError:wl("JSONPScriptError","<script> unable to load due to an `error` event on it"),Unknown:wl("Unknown","Unknown error occured")},jl=function(e,t){t(e,0)},Fl=function(e,t){return function(r,n,i){if("function"==typeof r&&"object"==typeof n||"object"==typeof i)throw new Sl.AlgoliaSearchError("index.search usage is index.search(query, params, cb)");0===arguments.length||"function"==typeof r?(i=r,r=""):1!==arguments.length&&"function"!=typeof n||(i=n,n=void 0),"object"==typeof r&&null!==r?(n=r,r=void 0):void 0!==r&&null!==r||(r="");var a,o="";return void 0!==r&&(o+=e+"="+encodeURIComponent(r)),void 0!==n&&(n.additionalUA&&(a=n.additionalUA,delete n.additionalUA),o=this.as._getSearchParams(n,o)),this._search(o,t,i,a)}};var Pl=function e(t){var r=Array.prototype.slice.call(arguments);return _l(r,function(r){for(var n in r)r.hasOwnProperty(n)&&("object"==typeof t[n]&&"object"==typeof r[n]?t[n]=e({},t[n],r[n]):void 0!==r[n]&&(t[n]=r[n]))}),t},Nl=function(e){return JSON.parse(JSON.stringify(e))},El=Object.prototype.toString,Ol=function(e){var t=El.call(e),r="[object Arguments]"===t;return r||(r="[object Array]"!==t&&null!==e&&"object"==typeof e&&"number"==typeof e.length&&e.length>=0&&"[object Function]"===El.call(e.callee)),r},Tl=Object.prototype.hasOwnProperty,Al=Object.prototype.toString,Cl=Array.prototype.slice,Il=Object.prototype.propertyIsEnumerable,kl=!Il.call({toString:null},"toString"),ql=Il.call(function(){},"prototype"),Ml=["toString","toLocaleString","valueOf","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","constructor"],Hl=function(e){var t=e.constructor;return t&&t.prototype===e},Ll={$console:!0,$external:!0,$frame:!0,$frameElement:!0,$frames:!0,$innerHeight:!0,$innerWidth:!0,$outerHeight:!0,$outerWidth:!0,$pageXOffset:!0,$pageYOffset:!0,$parent:!0,$scrollLeft:!0,$scrollTop:!0,$scrollX:!0,$scrollY:!0,$self:!0,$webkitIndexedDB:!0,$webkitStorageInfo:!0,$window:!0},Dl=function(){if("undefined"==typeof window)return!1;for(var e in window)try{if(!Ll["$"+e]&&Tl.call(window,e)&&null!==window[e]&&"object"==typeof window[e])try{Hl(window[e])}catch(e){return!0}}catch(e){return!0}return!1}(),Ul=function(e){var t=null!==e&&"object"==typeof e,r="[object Function]"===Al.call(e),n=Ol(e),i=t&&"[object String]"===Al.call(e),a=[];if(!t&&!r&&!n)throw new TypeError("Object.keys called on a non-object");var o=ql&&r;if(i&&e.length>0&&!Tl.call(e,0))for(var s=0;s<e.length;++s)a.push(String(s));if(n&&e.length>0)for(var c=0;c<e.length;++c)a.push(String(c));else for(var u in e)o&&"prototype"===u||!Tl.call(e,u)||a.push(String(u));if(kl)for(var l=function(e){if("undefined"==typeof window||!Dl)return Hl(e);try{return Hl(e)}catch(e){return!1}}(e),f=0;f<Ml.length;++f)l&&"constructor"===Ml[f]||!Tl.call(e,Ml[f])||a.push(Ml[f]);return a};Ul.shim=function(){if(Object.keys){if(!function(){return 2===(Object.keys(arguments)||"").length}(1,2)){var e=Object.keys;Object.keys=function(t){return Ol(t)?e(Cl.call(t)):e(t)}}}else Object.keys=Ul;return Object.keys||Ul};var Bl,Ql=Ul,zl=function(e,t){var r={};return _l(Ql(e),function(n){!0!==t(n)&&(r[n]=e[n])}),r},Vl={}.toString,Wl=Array.isArray||function(e){return"[object Array]"==Vl.call(e)},Jl=function(e,t){var r=[];return _l(e,function(n,i){r.push(t(n,i,e))}),r},$l=Kl;function Kl(e,t){this.indexName=t,this.as=e,this.typeAheadArgs=null,this.typeAheadValueOption=null,this.cache={}}Kl.prototype.clearCache=function(){this.cache={}},Kl.prototype.search=Fl("query"),Kl.prototype.similarSearch=Fl("similarQuery"),Kl.prototype.browse=function(e,t,r){var n,i,a=Pl;0===arguments.length||1===arguments.length&&"function"==typeof arguments[0]?(n=0,r=arguments[0],e=void 0):"number"==typeof arguments[0]?(n=arguments[0],"number"==typeof arguments[1]?i=arguments[1]:"function"==typeof arguments[1]&&(r=arguments[1],i=void 0),e=void 0,t=void 0):"object"==typeof arguments[0]?("function"==typeof arguments[1]&&(r=arguments[1]),t=arguments[0],e=void 0):"string"==typeof arguments[0]&&"function"==typeof arguments[1]&&(r=arguments[1],t=void 0),t=a({},t||{},{page:n,hitsPerPage:i,query:e});var o=this.as._getSearchParams(t,"");return this.as._jsonRequest({method:"POST",url:"/1/indexes/"+encodeURIComponent(this.indexName)+"/browse",body:{params:o},hostType:"read",callback:r})},Kl.prototype.browseFrom=function(e,t){return this.as._jsonRequest({method:"POST",url:"/1/indexes/"+encodeURIComponent(this.indexName)+"/browse",body:{cursor:e},hostType:"read",callback:t})},Kl.prototype.searchForFacetValues=function(e,t){var r=Nl,n=zl;if(void 0===e.facetName||void 0===e.facetQuery)throw new Error("Usage: index.searchForFacetValues({facetName, facetQuery, ...params}[, callback])");var i=e.facetName,a=n(r(e),function(e){return"facetName"===e}),o=this.as._getSearchParams(a,"");return this.as._jsonRequest({method:"POST",url:"/1/indexes/"+encodeURIComponent(this.indexName)+"/facets/"+encodeURIComponent(i)+"/query",hostType:"read",body:{params:o},callback:t})},Kl.prototype.searchFacet=function(e,t){var r=!1;return function(){return r||(console.warn(t),r=!0),e.apply(this,arguments)}}(function(e,t){return this.searchForFacetValues(e,t)},"algoliasearch: `"+(Bl="index.searchFacet(params[, callback])")+"` was replaced by `"+"index.searchForFacetValues(params[, callback])"+"`. Please see https://github.com/algolia/algoliasearch-client-javascript/wiki/Deprecated#"+Bl.toLowerCase().replace(/[\.\(\)]/g,"")),Kl.prototype._search=function(e,t,r,n){return this.as._jsonRequest({cache:this.cache,method:"POST",url:t||"/1/indexes/"+encodeURIComponent(this.indexName)+"/query",body:{params:e},hostType:"read",fallback:{method:"GET",url:"/1/indexes/"+encodeURIComponent(this.indexName),body:{params:e}},callback:r,additionalUA:n})},Kl.prototype.getObject=function(e,t,r){1!==arguments.length&&"function"!=typeof t||(r=t,t=void 0);var n="";if(void 0!==t){n="?attributes=";for(var i=0;i<t.length;++i)0!==i&&(n+=","),n+=t[i]}return this.as._jsonRequest({method:"GET",url:"/1/indexes/"+encodeURIComponent(this.indexName)+"/"+encodeURIComponent(e)+n,hostType:"read",callback:r})},Kl.prototype.getObjects=function(e,t,r){var n=Jl;if(!Wl(e))throw new Error("Usage: index.getObjects(arrayOfObjectIDs[, callback])");var i=this;1!==arguments.length&&"function"!=typeof t||(r=t,t=void 0);var a={requests:n(e,function(e){var r={indexName:i.indexName,objectID:e};return t&&(r.attributesToRetrieve=t.join(",")),r})};return this.as._jsonRequest({method:"POST",url:"/1/indexes/*/objects",hostType:"read",body:a,callback:r})},Kl.prototype.as=null,Kl.prototype.indexName=null,Kl.prototype.typeAheadArgs=null,Kl.prototype.typeAheadValueOption=null;var Yl=1e3,Gl=60*Yl,Xl=60*Gl,Zl=24*Xl,ef=365.25*Zl,tf=function(e,t){t=t||{};var r,n=typeof e;if("string"===n&&e.length>0)return function(e){if((e=String(e)).length>100)return;var t=/^((?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|years?|yrs?|y)?$/i.exec(e);if(!t)return;var r=parseFloat(t[1]);switch((t[2]||"ms").toLowerCase()){case"years":case"year":case"yrs":case"yr":case"y":return r*ef;case"days":case"day":case"d":return r*Zl;case"hours":case"hour":case"hrs":case"hr":case"h":return r*Xl;case"minutes":case"minute":case"mins":case"min":case"m":return r*Gl;case"seconds":case"second":case"secs":case"sec":case"s":return r*Yl;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return r;default:return}}(e);if("number"===n&&!1===isNaN(e))return t.long?rf(r=e,Zl,"day")||rf(r,Xl,"hour")||rf(r,Gl,"minute")||rf(r,Yl,"second")||r+" ms":function(e){if(e>=Zl)return Math.round(e/Zl)+"d";if(e>=Xl)return Math.round(e/Xl)+"h";if(e>=Gl)return Math.round(e/Gl)+"m";if(e>=Yl)return Math.round(e/Yl)+"s";return e+"ms"}(e);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(e))};function rf(e,t,r){if(!(e<t))return e<1.5*t?Math.floor(e/t)+" "+r:Math.ceil(e/t)+" "+r+"s"}var nf,af=O(function(e,t){var r;function n(e){function n(){if(n.enabled){var e=n,i=+new Date,a=i-(r||i);e.diff=a,e.prev=r,e.curr=i,r=i;for(var o=new Array(arguments.length),s=0;s<o.length;s++)o[s]=arguments[s];o[0]=t.coerce(o[0]),"string"!=typeof o[0]&&o.unshift("%O");var c=0;o[0]=o[0].replace(/%([a-zA-Z%])/g,function(r,n){if("%%"===r)return r;c++;var i=t.formatters[n];if("function"==typeof i){var a=o[c];r=i.call(e,a),o.splice(c,1),c--}return r}),t.formatArgs.call(e,o),(n.log||t.log||console.log.bind(console)).apply(e,o)}}return n.namespace=e,n.enabled=t.enabled(e),n.useColors=t.useColors(),n.color=function(e){var r,n=0;for(r in e)n=(n<<5)-n+e.charCodeAt(r),n|=0;return t.colors[Math.abs(n)%t.colors.length]}(e),"function"==typeof t.init&&t.init(n),n}(t=e.exports=n.debug=n.default=n).coerce=function(e){return e instanceof Error?e.stack||e.message:e},t.disable=function(){t.enable("")},t.enable=function(e){t.save(e),t.names=[],t.skips=[];for(var r=("string"==typeof e?e:"").split(/[\s,]+/),n=r.length,i=0;i<n;i++)r[i]&&("-"===(e=r[i].replace(/\*/g,".*?"))[0]?t.skips.push(new RegExp("^"+e.substr(1)+"$")):t.names.push(new RegExp("^"+e+"$")))},t.enabled=function(e){var r,n;for(r=0,n=t.skips.length;r<n;r++)if(t.skips[r].test(e))return!1;for(r=0,n=t.names.length;r<n;r++)if(t.names[r].test(e))return!0;return!1},t.humanize=tf,t.names=[],t.skips=[],t.formatters={}}),of=(af.coerce,af.disable,af.enable,af.enabled,af.humanize,af.names,af.skips,af.formatters,O(function(e,t){function r(){var e;try{e=t.storage.debug}catch(e){}return!e&&void 0!==N&&"env"in N&&(e=N.env.DEBUG),e}(t=e.exports=af).log=function(){return"object"==typeof console&&console.log&&Function.prototype.apply.call(console.log,console,arguments)},t.formatArgs=function(e){var r=this.useColors;if(e[0]=(r?"%c":"")+this.namespace+(r?" %c":" ")+e[0]+(r?"%c ":" ")+"+"+t.humanize(this.diff),!r)return;var n="color: "+this.color;e.splice(1,0,n,"color: inherit");var i=0,a=0;e[0].replace(/%[a-zA-Z%]/g,function(e){"%%"!==e&&"%c"===e&&(a=++i)}),e.splice(a,0,n)},t.save=function(e){try{null==e?t.storage.removeItem("debug"):t.storage.debug=e}catch(e){}},t.load=r,t.useColors=function(){if("undefined"!=typeof window&&window.process&&"renderer"===window.process.type)return!0;return"undefined"!=typeof document&&document.documentElement&&document.documentElement.style&&document.documentElement.style.WebkitAppearance||"undefined"!=typeof window&&window.console&&(window.console.firebug||window.console.exception&&window.console.table)||"undefined"!=typeof navigator&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/)&&parseInt(RegExp.$1,10)>=31||"undefined"!=typeof navigator&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)},t.storage="undefined"!=typeof chrome&&void 0!==chrome.storage?chrome.storage.local:function(){try{return window.localStorage}catch(e){}}(),t.colors=["lightseagreen","forestgreen","goldenrod","dodgerblue","darkorchid","crimson"],t.formatters.j=function(e){try{return JSON.stringify(e)}catch(e){return"[UnexpectedJSONParseError]: "+e.message}},t.enable(r())})),sf=(of.log,of.formatArgs,of.save,of.load,of.useColors,of.storage,of.colors,of("algoliasearch:src/hostIndexState.js")),cf="algoliasearch-client-js",uf={state:{},set:function(e,t){return this.state[e]=t,this.state[e]},get:function(e){return this.state[e]||null}},lf={set:function(e,t){uf.set(e,t);try{var r=JSON.parse(E.localStorage[cf]);return r[e]=t,E.localStorage[cf]=JSON.stringify(r),r[e]}catch(t){return ff(e,t)}},get:function(e){try{return JSON.parse(E.localStorage[cf])[e]||null}catch(t){return ff(e,t)}}};function ff(e,t){return sf("localStorage failed with",t),function(){try{E.localStorage.removeItem(cf)}catch(e){}}(),(nf=uf).get(e)}nf=df()?lf:uf;var hf={get:pf,set:pf,supportsLocalStorage:df};function pf(e,t){return 1===arguments.length?nf.get(e):nf.set(e,t)}function df(){try{return"localStorage"in E&&null!==E.localStorage&&(E.localStorage[cf]||E.localStorage.setItem(cf,JSON.stringify({})),!0)}catch(e){return!1}}var mf=gf,vf=N.env.RESET_APP_DATA_TIMER&&parseInt(N.env.RESET_APP_DATA_TIMER,10)||12e4;function gf(e,t,r){var n=of("algoliasearch"),i=Nl,a=Wl,o=Jl,s="Usage: algoliasearch(applicationID, apiKey, opts)";if(!0!==r._allowEmptyCredentials&&!e)throw new Sl.AlgoliaSearchError("Please provide an application ID. "+s);if(!0!==r._allowEmptyCredentials&&!t)throw new Sl.AlgoliaSearchError("Please provide an API key. "+s);this.applicationID=e,this.apiKey=t,this.hosts={read:[],write:[]},r=r||{},this._timeouts=r.timeouts||{connect:1e3,read:2e3,write:3e4},r.timeout&&(this._timeouts.connect=this._timeouts.read=this._timeouts.write=r.timeout);var c=r.protocol||"https:";if(/:$/.test(c)||(c+=":"),"http:"!==c&&"https:"!==c)throw new Sl.AlgoliaSearchError("protocol must be `http:` or `https:` (was `"+r.protocol+"`)");if(this._checkAppIdData(),r.hosts)a(r.hosts)?(this.hosts.read=i(r.hosts),this.hosts.write=i(r.hosts)):(this.hosts.read=i(r.hosts.read),this.hosts.write=i(r.hosts.write));else{var u=o(this._shuffleResult,function(t){return e+"-"+t+".algolianet.com"}),l=(!1===r.dsn?"":"-dsn")+".algolia.net";this.hosts.read=[this.applicationID+l].concat(u),this.hosts.write=[this.applicationID+".algolia.net"].concat(u)}this.hosts.read=o(this.hosts.read,yf(c)),this.hosts.write=o(this.hosts.write,yf(c)),this.extraHeaders={},this.cache=r._cache||{},this._ua=r._ua,this._useCache=!(void 0!==r._useCache&&!r._cache)||r._useCache,this._useFallback=void 0===r.useFallback||r.useFallback,this._setTimeout=r._setTimeout,n("init done, %j",this)}function yf(e){return function(t){return e+"//"+t.toLowerCase()}}function bf(e){if(void 0===Array.prototype.toJSON)return JSON.stringify(e);var t=Array.prototype.toJSON;delete Array.prototype.toJSON;var r=JSON.stringify(e);return Array.prototype.toJSON=t,r}function Rf(e){var t={};for(var r in e){var n;if(Object.prototype.hasOwnProperty.call(e,r))n="x-algolia-api-key"===r||"x-algolia-application-id"===r?"**hidden for security purposes**":e[r],t[r]=n}return t}gf.prototype.initIndex=function(e){return new $l(this,e)},gf.prototype.setExtraHeader=function(e,t){this.extraHeaders[e.toLowerCase()]=t},gf.prototype.getExtraHeader=function(e){return this.extraHeaders[e.toLowerCase()]},gf.prototype.unsetExtraHeader=function(e){delete this.extraHeaders[e.toLowerCase()]},gf.prototype.addAlgoliaAgent=function(e){-1===this._ua.indexOf(";"+e)&&(this._ua+=";"+e)},gf.prototype._jsonRequest=function(e){this._checkAppIdData();var t,r,n=of("algoliasearch:"+e.url),i=e.additionalUA||"",a=e.cache,o=this,s=0,c=!1,u=o._useFallback&&o._request.fallback&&e.fallback;this.apiKey.length>500&&void 0!==e.body&&(void 0!==e.body.params||void 0!==e.body.requests)?(e.body.apiKey=this.apiKey,r=this._computeRequestHeaders({additionalUA:i,withApiKey:!1,headers:e.headers})):r=this._computeRequestHeaders({additionalUA:i,headers:e.headers}),void 0!==e.body&&(t=bf(e.body)),n("request start");var l=[];var f=function f(h,p){o._checkAppIdData();var d,m=new Date;if(o._useCache&&(d=e.url),o._useCache&&t&&(d+="_body_"+p.body),o._useCache&&a&&void 0!==a[d])return n("serving response from cache"),o._promise.resolve(JSON.parse(a[d]));if(s>=o.hosts[e.hostType].length)return!u||c?(n("could not get any response"),o._promise.reject(new Sl.AlgoliaSearchError("Cannot connect to the AlgoliaSearch API. Send an email to [email protected] to report and resolve the issue. Application id was: "+o.applicationID,{debugData:l}))):(n("switching to fallback"),s=0,p.method=e.fallback.method,p.url=e.fallback.url,p.jsonBody=e.fallback.body,p.jsonBody&&(p.body=bf(p.jsonBody)),r=o._computeRequestHeaders({additionalUA:i,headers:e.headers}),p.timeouts=o._getTimeoutsForRequest(e.hostType),o._setHostIndexByType(0,e.hostType),c=!0,f(o._request.fallback,p));var v=o._getHostByType(e.hostType),g=v+p.url,y={body:p.body,jsonBody:p.jsonBody,method:p.method,headers:r,timeouts:p.timeouts,debug:n};return n("method: %s, url: %s, headers: %j, timeouts: %d",y.method,g,y.headers,y.timeouts),h===o._request.fallback&&n("using fallback"),h.call(o,g,y).then(function(e){var i=e&&e.body&&e.body.message&&e.body.status||e.statusCode||e&&e.body&&200;n("received response: statusCode: %s, computed statusCode: %d, headers: %j",e.statusCode,i,e.headers);var c=2===Math.floor(i/100),u=new Date;if(l.push({currentHost:v,headers:Rf(r),content:t||null,contentLength:void 0!==t?t.length:null,method:p.method,timeouts:p.timeouts,url:p.url,startTime:m,endTime:u,duration:u-m,statusCode:i}),c)return o._useCache&&a&&(a[d]=e.responseText),e.body;if(4!==Math.floor(i/100))return s+=1,b();n("unrecoverable error");var f=new Sl.AlgoliaSearchError(e.body&&e.body.message,{debugData:l,statusCode:i});return o._promise.reject(f)},function(i){n("error: %s, stack: %s",i.message,i.stack);var a=new Date;return l.push({currentHost:v,headers:Rf(r),content:t||null,contentLength:void 0!==t?t.length:null,method:p.method,timeouts:p.timeouts,url:p.url,startTime:m,endTime:a,duration:a-m}),i instanceof Sl.AlgoliaSearchError||(i=new Sl.Unknown(i&&i.message,i)),s+=1,i instanceof Sl.Unknown||i instanceof Sl.UnparsableJSON||s>=o.hosts[e.hostType].length&&(c||!u)?(i.debugData=l,o._promise.reject(i)):i instanceof Sl.RequestTimeout?(n("retrying request with higher timeout"),o._incrementHostIndex(e.hostType),o._incrementTimeoutMultipler(),p.timeouts=o._getTimeoutsForRequest(e.hostType),f(h,p)):b()});function b(){return n("retrying request"),o._incrementHostIndex(e.hostType),f(h,p)}}(o._request,{url:e.url,method:e.method,body:t,jsonBody:e.body,timeouts:o._getTimeoutsForRequest(e.hostType)});if("function"!=typeof e.callback)return f;f.then(function(t){jl(function(){e.callback(null,t)},o._setTimeout||setTimeout)},function(t){jl(function(){e.callback(t)},o._setTimeout||setTimeout)})},gf.prototype._getSearchParams=function(e,t){if(void 0===e||null===e)return t;for(var r in e)null!==r&&void 0!==e[r]&&e.hasOwnProperty(r)&&(t+=""===t?"":"&",t+=r+"="+encodeURIComponent("[object Array]"===Object.prototype.toString.call(e[r])?bf(e[r]):e[r]));return t},gf.prototype._computeRequestHeaders=function(e){var t=_l,r={"x-algolia-agent":e.additionalUA?this._ua+";"+e.additionalUA:this._ua,"x-algolia-application-id":this.applicationID};return!1!==e.withApiKey&&(r["x-algolia-api-key"]=this.apiKey),this.userToken&&(r["x-algolia-usertoken"]=this.userToken),this.securityTags&&(r["x-algolia-tagfilters"]=this.securityTags),t(this.extraHeaders,function(e,t){r[t]=e}),e.headers&&t(e.headers,function(e,t){r[t]=e}),r},gf.prototype.search=function(e,t,r){var n=Jl;if(!Wl(e))throw new Error("Usage: client.search(arrayOfQueries[, callback])");"function"==typeof t?(r=t,t={}):void 0===t&&(t={});var i=this,a={requests:n(e,function(e){var t="";return void 0!==e.query&&(t+="query="+encodeURIComponent(e.query)),{indexName:e.indexName,params:i._getSearchParams(e.params,t)}})},o=n(a.requests,function(e,t){return t+"="+encodeURIComponent("/1/indexes/"+encodeURIComponent(e.indexName)+"?"+e.params)}).join("&"),s="/1/indexes/*/queries";return void 0!==t.strategy&&(s+="?strategy="+t.strategy),this._jsonRequest({cache:this.cache,method:"POST",url:s,body:a,hostType:"read",fallback:{method:"GET",url:"/1/indexes/*",body:{params:o}},callback:r})},gf.prototype.setSecurityTags=function(e){if("[object Array]"===Object.prototype.toString.call(e)){for(var t=[],r=0;r<e.length;++r)if("[object Array]"===Object.prototype.toString.call(e[r])){for(var n=[],i=0;i<e[r].length;++i)n.push(e[r][i]);t.push("("+n.join(",")+")")}else t.push(e[r]);e=t.join(",")}this.securityTags=e},gf.prototype.setUserToken=function(e){this.userToken=e},gf.prototype.clearCache=function(){this.cache={}},gf.prototype.setRequestTimeout=function(e){e&&(this._timeouts.connect=this._timeouts.read=this._timeouts.write=e)},gf.prototype.setTimeouts=function(e){this._timeouts=e},gf.prototype.getTimeouts=function(){return this._timeouts},gf.prototype._getAppIdData=function(){var e=hf.get(this.applicationID);return null!==e&&this._cacheAppIdData(e),e},gf.prototype._setAppIdData=function(e){return e.lastChange=(new Date).getTime(),this._cacheAppIdData(e),hf.set(this.applicationID,e)},gf.prototype._checkAppIdData=function(){var e=this._getAppIdData(),t=(new Date).getTime();return null===e||t-e.lastChange>vf?this._resetInitialAppIdData(e):e},gf.prototype._resetInitialAppIdData=function(e){var t=e||{};return t.hostIndexes={read:0,write:0},t.timeoutMultiplier=1,t.shuffleResult=t.shuffleResult||function(e){var t,r,n=e.length;for(;0!==n;)r=Math.floor(Math.random()*n),t=e[n-=1],e[n]=e[r],e[r]=t;return e}([1,2,3]),this._setAppIdData(t)},gf.prototype._cacheAppIdData=function(e){this._hostIndexes=e.hostIndexes,this._timeoutMultiplier=e.timeoutMultiplier,this._shuffleResult=e.shuffleResult},gf.prototype._partialAppIdDataUpdate=function(e){var t=_l,r=this._getAppIdData();return t(e,function(e,t){r[t]=e}),this._setAppIdData(r)},gf.prototype._getHostByType=function(e){return this.hosts[e][this._getHostIndexByType(e)]},gf.prototype._getTimeoutMultiplier=function(){return this._timeoutMultiplier},gf.prototype._getHostIndexByType=function(e){return this._hostIndexes[e]},gf.prototype._setHostIndexByType=function(e,t){var r=Nl(this._hostIndexes);return r[t]=e,this._partialAppIdDataUpdate({hostIndexes:r}),e},gf.prototype._incrementHostIndex=function(e){return this._setHostIndexByType((this._getHostIndexByType(e)+1)%this.hosts[e].length,e)},gf.prototype._incrementTimeoutMultipler=function(){var e=Math.max(this._timeoutMultiplier+1,4);return this._partialAppIdDataUpdate({timeoutMultiplier:e})},gf.prototype._getTimeoutsForRequest=function(e){return{connect:this._timeouts.connect*this._timeoutMultiplier,complete:this._timeouts[e]*this._timeoutMultiplier}};var _f="undefined"!=typeof window?window:void 0!==E?E:"undefined"!=typeof self?self:{},xf=O(function(e,t){e.exports=function(){function e(e){return"function"==typeof e}var t=Array.isArray?Array.isArray:function(e){return"[object Array]"===Object.prototype.toString.call(e)},r=0,n=void 0,i=void 0,a=function(e,t){h[r]=e,h[r+1]=t,2===(r+=2)&&(i?i(p):b())},o="undefined"!=typeof window?window:void 0,s=o||{},c=s.MutationObserver||s.WebKitMutationObserver,u="undefined"==typeof self&&void 0!==N&&"[object process]"==={}.toString.call(N),l="undefined"!=typeof Uint8ClampedArray&&"undefined"!=typeof importScripts&&"undefined"!=typeof MessageChannel;function f(){var e=setTimeout;return function(){return e(p,1)}}var h=new Array(1e3);function p(){for(var e=0;e<r;e+=2){var t=h[e],n=h[e+1];t(n),h[e]=void 0,h[e+1]=void 0}r=0}var d,v,g,y,b=void 0;function R(e,t){var r=this,n=new this.constructor(w);void 0===n[x]&&D(n);var i=r._state;if(i){var o=arguments[i-1];a(function(){return H(i,n,o,r._result)})}else q(r,n,e,t);return n}function _(e){if(e&&"object"==typeof e&&e.constructor===this)return e;var t=new this(w);return A(t,e),t}u?b=function(){return m(p)}:c?(v=0,g=new c(p),y=document.createTextNode(""),g.observe(y,{characterData:!0}),b=function(){y.data=v=++v%2}):l?((d=new MessageChannel).port1.onmessage=p,b=function(){return d.port2.postMessage(0)}):b=void 0===o?function(){try{var e=Function("return this")().require("vertx");return void 0!==(n=e.runOnLoop||e.runOnContext)?function(){n(p)}:f()}catch(e){return f()}}():f();var x=Math.random().toString(36).substring(2);function w(){}var S=void 0,j=1,F=2,P={error:null};function O(e){try{return e.then}catch(e){return P.error=e,P}}function T(t,r,n){r.constructor===t.constructor&&n===R&&r.constructor.resolve===_?function(e,t){t._state===j?I(e,t._result):t._state===F?k(e,t._result):q(t,void 0,function(t){return A(e,t)},function(t){return k(e,t)})}(t,r):n===P?(k(t,P.error),P.error=null):void 0===n?I(t,r):e(n)?function(e,t,r){a(function(e){var n=!1,i=function(e,t,r,n){try{e.call(t,r,n)}catch(e){return e}}(r,t,function(r){n||(n=!0,t!==r?A(e,r):I(e,r))},function(t){n||(n=!0,k(e,t))},e._label);!n&&i&&(n=!0,k(e,i))},e)}(t,r,n):I(t,r)}function A(e,t){var r,n;e===t?k(e,new TypeError("You cannot resolve a promise with itself")):(n=typeof(r=t),null===r||"object"!==n&&"function"!==n?I(e,t):T(e,t,O(t)))}function C(e){e._onerror&&e._onerror(e._result),M(e)}function I(e,t){e._state===S&&(e._result=t,e._state=j,0!==e._subscribers.length&&a(M,e))}function k(e,t){e._state===S&&(e._state=F,e._result=t,a(C,e))}function q(e,t,r,n){var i=e._subscribers,o=i.length;e._onerror=null,i[o]=t,i[o+j]=r,i[o+F]=n,0===o&&e._state&&a(M,e)}function M(e){var t=e._subscribers,r=e._state;if(0!==t.length){for(var n=void 0,i=void 0,a=e._result,o=0;o<t.length;o+=3)n=t[o],i=t[o+r],n?H(r,n,i,a):i(a);e._subscribers.length=0}}function H(t,r,n,i){var a=e(n),o=void 0,s=void 0,c=void 0,u=void 0;if(a){if((o=function(e,t){try{return e(t)}catch(e){return P.error=e,P}}(n,i))===P?(u=!0,s=o.error,o.error=null):c=!0,r===o)return void k(r,new TypeError("A promises callback cannot return that same promise."))}else o=i,c=!0;r._state!==S||(a&&c?A(r,o):u?k(r,s):t===j?I(r,o):t===F&&k(r,o))}var L=0;function D(e){e[x]=L++,e._state=void 0,e._result=void 0,e._subscribers=[]}var U=function(){function e(e,r){this._instanceConstructor=e,this.promise=new e(w),this.promise[x]||D(this.promise),t(r)?(this.length=r.length,this._remaining=r.length,this._result=new Array(this.length),0===this.length?I(this.promise,this._result):(this.length=this.length||0,this._enumerate(r),0===this._remaining&&I(this.promise,this._result))):k(this.promise,new Error("Array Methods must be provided an Array"))}return e.prototype._enumerate=function(e){for(var t=0;this._state===S&&t<e.length;t++)this._eachEntry(e[t],t)},e.prototype._eachEntry=function(e,t){var r=this._instanceConstructor,n=r.resolve;if(n===_){var i=O(e);if(i===R&&e._state!==S)this._settledAt(e._state,t,e._result);else if("function"!=typeof i)this._remaining--,this._result[t]=e;else if(r===B){var a=new r(w);T(a,e,i),this._willSettleAt(a,t)}else this._willSettleAt(new r(function(t){return t(e)}),t)}else this._willSettleAt(n(e),t)},e.prototype._settledAt=function(e,t,r){var n=this.promise;n._state===S&&(this._remaining--,e===F?k(n,r):this._result[t]=r),0===this._remaining&&I(n,this._result)},e.prototype._willSettleAt=function(e,t){var r=this;q(e,void 0,function(e){return r._settledAt(j,t,e)},function(e){return r._settledAt(F,t,e)})},e}(),B=function(){function e(t){this[x]=L++,this._result=this._state=void 0,this._subscribers=[],w!==t&&("function"!=typeof t&&function(){throw new TypeError("You must pass a resolver function as the first argument to the promise constructor")}(),this instanceof e?function(e,t){try{t(function(t){A(e,t)},function(t){k(e,t)})}catch(t){k(e,t)}}(this,t):function(){throw new TypeError("Failed to construct 'Promise': Please use the 'new' operator, this object constructor cannot be called as a function.")}())}return e.prototype.catch=function(e){return this.then(null,e)},e.prototype.finally=function(e){var t=this.constructor;return this.then(function(r){return t.resolve(e()).then(function(){return r})},function(r){return t.resolve(e()).then(function(){throw r})})},e}();return B.prototype.then=R,B.all=function(e){return new U(this,e).promise},B.race=function(e){var r=this;return t(e)?new r(function(t,n){for(var i=e.length,a=0;a<i;a++)r.resolve(e[a]).then(t,n)}):new r(function(e,t){return t(new TypeError("You must pass an array to race."))})},B.resolve=_,B.reject=function(e){var t=new this(w);return k(t,e),t},B._setScheduler=function(e){i=e},B._setAsap=function(e){a=e},B._asap=a,B.polyfill=function(){var e=void 0;if(void 0!==E)e=E;else if("undefined"!=typeof self)e=self;else try{e=Function("return this")()}catch(e){throw new Error("polyfill failed because global object is unavailable in this environment")}var t=e.Promise;if(t){var r=null;try{r=Object.prototype.toString.call(t.resolve())}catch(e){}if("[object Promise]"===r&&!t.cast)return}e.Promise=B},B.Promise=B,B}()}),wf=function(e){switch(typeof e){case"string":return e;case"boolean":return e?"true":"false";case"number":return isFinite(e)?e:"";default:return""}},Sf=function(e,t,r,n){return t=t||"&",r=r||"=",null===e&&(e=void 0),"object"==typeof e?Ff(Pf(e),function(n){var i=encodeURIComponent(wf(n))+r;return jf(e[n])?Ff(e[n],function(e){return i+encodeURIComponent(wf(e))}).join(t):i+encodeURIComponent(wf(e[n]))}).join(t):n?encodeURIComponent(wf(n))+r+encodeURIComponent(wf(e)):""},jf=Array.isArray||function(e){return"[object Array]"===Object.prototype.toString.call(e)};function Ff(e,t){if(e.map)return e.map(t);for(var r=[],n=0;n<e.length;n++)r.push(t(e[n],n));return r}var Pf=Object.keys||function(e){var t=[];for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&t.push(r);return t},Nf=function(e,t){/\?/.test(e)?e+="&":e+="?";return e+Sf(t)};var Ef=function(e,t,r){if("GET"!==t.method)return void r(new Error("Method "+t.method+" "+e+" is not supported by JSONP."));t.debug("JSONP: start");var n=!1,i=!1;Of+=1;var a=document.getElementsByTagName("head")[0],o=document.createElement("script"),s="algoliaJSONP_"+Of,c=!1;window[s]=function(e){!function(){try{delete window[s],delete window[s+"_loaded"]}catch(e){window[s]=window[s+"_loaded"]=void 0}}(),i?t.debug("JSONP: Late answer, ignoring"):(n=!0,f(),r(null,{body:e}))},e+="&callback="+s,t.jsonBody&&t.jsonBody.params&&(e+="&"+t.jsonBody.params);var u=setTimeout(function(){t.debug("JSONP: Script timeout"),i=!0,f(),r(new Sl.RequestTimeout)},t.timeouts.complete);function l(){t.debug("JSONP: success"),c||i||(c=!0,n||(t.debug("JSONP: Fail. Script loaded but did not call the callback"),f(),r(new Sl.JSONPScriptFail)))}function f(){clearTimeout(u),o.onload=null,o.onreadystatechange=null,o.onerror=null,a.removeChild(o)}o.onreadystatechange=function(){"loaded"!==this.readyState&&"complete"!==this.readyState||l()},o.onload=l,o.onerror=function(){if(t.debug("JSONP: Script error"),c||i)return;f(),r(new Sl.JSONPScriptError)},o.async=!0,o.defer=!0,o.src=e,a.appendChild(o)},Of=0;var Tf=function(e){return function(t,r,n){var i=Nl;(n=n&&i(n)||{}).hosts=n.hosts||["places-dsn.algolia.net","places-1.algolianet.com","places-2.algolianet.com","places-3.algolianet.com"],0!==arguments.length&&"object"!=typeof t&&void 0!==t||(t="",r="",n._allowEmptyCredentials=!0);var a=e(t,r,n),o=a.initIndex("places");return o.search=Fl("query","/1/places/query"),o.getObject=function(e,t){return this.as._jsonRequest({method:"GET",url:"/1/places/"+encodeURIComponent(e),hostType:"read",callback:t})},o}};var Af=_f.Promise||xf.Promise,Cf=function(e,t){var r=yl,n=Sl,i=Nf,a=Ef,o=Tf;function s(e,t,r){return(r=Nl(r||{}))._ua=r._ua||s.ua,new u(e,t,r)}t=t||"",s.version="3.26.0",s.ua="Algolia for vanilla JavaScript "+t+s.version,s.initPlaces=o(s),_f.__algolia={debug:of,algoliasearch:s};var c={hasXMLHttpRequest:"XMLHttpRequest"in _f,hasXDomainRequest:"XDomainRequest"in _f};function u(){e.apply(this,arguments)}return c.hasXMLHttpRequest&&(c.cors="withCredentials"in new XMLHttpRequest),r(u,e),u.prototype._request=function(e,t){return new Af(function(r,a){if(c.cors||c.hasXDomainRequest){e=i(e,t.headers);var o,s,u=t.body,l=c.cors?new XMLHttpRequest:new XDomainRequest,f=!1;o=setTimeout(h,t.timeouts.connect),l.onprogress=function(){f||p()},"onreadystatechange"in l&&(l.onreadystatechange=function(){!f&&l.readyState>1&&p()}),l.onload=function(){if(!s){var e;clearTimeout(o);try{e={body:JSON.parse(l.responseText),responseText:l.responseText,statusCode:l.status,headers:l.getAllResponseHeaders&&l.getAllResponseHeaders()||{}}}catch(t){e=new n.UnparsableJSON({more:l.responseText})}e instanceof n.UnparsableJSON?a(e):r(e)}},l.onerror=function(e){s||(clearTimeout(o),a(new n.Network({more:e})))},l instanceof XMLHttpRequest?l.open(t.method,e,!0):l.open(t.method,e),c.cors&&(u&&("POST"===t.method?l.setRequestHeader("content-type","application/x-www-form-urlencoded"):l.setRequestHeader("content-type","application/json")),l.setRequestHeader("accept","application/json")),l.send(u)}else a(new n.Network("CORS not supported"));function h(){s=!0,l.abort(),a(new n.RequestTimeout)}function p(){f=!0,clearTimeout(o),o=setTimeout(h,t.timeouts.complete)}})},u.prototype._request.fallback=function(e,t){return e=i(e,t.headers),new Af(function(r,n){a(e,t,function(e,t){e?n(e):r(t)})})},u.prototype._promise={reject:function(e){return Af.reject(e)},resolve:function(e){return Af.resolve(e)},delay:function(e){return new Af(function(t){setTimeout(t,e)})}},s}(mf,"(lite) "),If=200;var kf=function(e,t,r,n){var i=-1,a=za,o=!0,s=e.length,c=[],u=t.length;if(!s)return c;r&&(t=ln(t,cr(r))),n?(a=Va,o=!1):t.length>=If&&(a=dt,o=!1,t=new ht(t));e:for(;++i<s;){var l=e[i],f=null==r?l:r(l);if(l=n||0!==l?l:0,o&&f==f){for(var h=u;h--;)if(t[h]===f)continue e;c.push(l)}else a(t,f,n)||c.push(l)}return c},qf=$a(function(e,t){return Ka(e)?kf(e,Pa(t,1,Ka,!0)):[]}),Mf=Object.prototype.hasOwnProperty;var Hf=function(e,t){return null!=e&&Mf.call(e,t)};var Lf=function(e,t){return null!=e&&xn(e,t,Hf)};function Df(e){if(!e.displayName)throw new Error("`createConnector` requires you to provide a `displayName` property.");var n=Lf(e,"refine"),i=Lf(e,"searchForFacetValues"),a=Lf(e,"getSearchParameters"),o=Lf(e,"getMetadata"),s=Lf(e,"transitionState"),c=Lf(e,"cleanUp"),u=a||o||s;return function(l){var f,h,p;return h=f=function(t){function f(e,t){al(this,f);var r=fl(this,(f.__proto__||Object.getPrototypeOf(f)).call(this,e,t));p.call(r);var n=t.ais,i=n.store,a=n.widgetsManager;return r.state={props:r.getProvidedProps(cl({},e,{canRender:!1})),canRender:!1},r.unsubscribe=i.subscribe(function(){r.state.canRender&&r.setState({props:r.getProvidedProps(cl({},r.props,{canRender:r.state.canRender}))})}),u&&(r.unregisterWidget=a.registerWidget(r)),r}return ul(f,t),ol(f,[{key:"getMetadata",value:function(t){return o?e.getMetadata.call(this,this.props,t):{}}},{key:"getSearchParameters",value:function(t){return a?e.getSearchParameters.call(this,t,this.props,this.context.ais.store.getState().widgets):null}},{key:"transitionState",value:function(t,r){return s?e.transitionState.call(this,this.props,t,r):r}},{key:"componentDidMount",value:function(){this.setState({canRender:!0})}},{key:"componentWillMount",value:function(){e.getSearchParameters&&this.context.ais.onSearchParameters(e.getSearchParameters,this.context,this.props)}},{key:"componentWillReceiveProps",value:function(t){go(this.props,t)||(this.setState({props:this.getProvidedProps(t)}),u&&(this.context.ais.widgetsManager.update(),e.transitionState&&this.context.ais.onSearchStateChange(e.transitionState.call(this,t,this.context.ais.store.getState().widgets,this.context.ais.store.getState().widgets))))}},{key:"componentWillUnmount",value:function(){if(this.unsubscribe(),u&&(this.unregisterWidget(),c)){var t=e.cleanUp.call(this,this.props,this.context.ais.store.getState().widgets);this.context.ais.store.setState(cl({},this.context.ais.store.getState(),{widgets:t})),this.context.ais.onSearchStateChange(function e(t){return Object.keys(t).forEach(function(r){var n=t[r];Gn(n)&&wa(n)?delete t[r]:wa(n)&&e(n)}),t}(t))}}},{key:"shouldComponentUpdate",value:function(e,t){var r=Zu(this.props,e);return null===this.state.props||null===t.props?this.state.props!==t.props||!r:!r||!Zu(this.state.props,t.props)}},{key:"render",value:function(){if(null===this.state.props)return null;var e=n?{refine:this.refine,createURL:this.createURL}:{},t=i?{searchForItems:this.searchForFacetValues}:{};return r.createElement(l,cl({},this.props,this.state.props,e,t))}}]),f}(t.Component),f.displayName=e.displayName+"("+el(l)+")",f.defaultClassNames=l.defaultClassNames,f.propTypes=e.propTypes,f.defaultProps=e.defaultProps,f.contextTypes={ais:L.object.isRequired,multiIndexContext:L.object},p=function(){var t=this;this.getProvidedProps=function(r){var n=t.context.ais.store.getState(),i=n.results,a=n.searching,o=n.error,s=n.widgets,c=n.metadata,u=n.resultsFacetValues,l={results:i,searching:a,error:o,searchingForFacetValues:n.searchingForFacetValues,isSearchStalled:n.isSearchStalled};return e.getProvidedProps.call(t,r,s,l,c,u)},this.refine=function(){for(var r,n=arguments.length,i=Array(n),a=0;a<n;a++)i[a]=arguments[a];t.context.ais.onInternalStateUpdate((r=e.refine).call.apply(r,[t,t.props,t.context.ais.store.getState().widgets].concat(i)))},this.searchForFacetValues=function(){for(var r=arguments.length,n=Array(r),i=0;i<r;i++)n[i]=arguments[i];t.context.ais.onSearchForFacetValues(e.searchForFacetValues.apply(e,[t.props,t.context.ais.store.getState().widgets].concat(n)))},this.createURL=function(){for(var r,n=arguments.length,i=Array(n),a=0;a<n;a++)i[a]=arguments[a];return t.context.ais.createHrefForState((r=e.refine).call.apply(r,[t,t.props,t.context.ais.store.getState().widgets].concat(i)))},this.cleanUp=function(){for(var r,n=arguments.length,i=Array(n),a=0;a<n;a++)i[a]=arguments[a];return(r=e.cleanUp).call.apply(r,[t].concat(i))}},h}}function Uf(e){return e&&e.multiIndexContext?e.multiIndexContext.targetedIndex:e.ais.mainTargetedIndex}function Bf(e,t){return e.results&&!e.results.hits?e.results[Uf(t)]?e.results[Uf(t)]:null:e.results?e.results:null}function Qf(e){return e&&e.multiIndexContext}function zf(e,t,r,n,i){return Qf(r)?i?function(e,t,r,n,i){var a,o=Uf(r),s=n?{page:1}:void 0,c=Lf(e,"indices."+o)?cl({},e.indices,sl({},o,cl({},e.indices[o],(sl(a={},i,cl({},e.indices[o][i],t)),sl(a,"page",1),a)))):cl({},e.indices,sl({},o,cl(sl({},i,t),s)));return cl({},e,{indices:c})}(e,t,r,n,i):function(e,t,r,n){var i=n?{page:1}:void 0,a=Uf(r),o=Lf(e,"indices."+a)?cl({},e.indices,sl({},a,cl({},e.indices[a],t,i))):cl({},e.indices,sl({},a,cl({},t,i)));return cl({},e,{indices:o})}(e,t,r,n):(e.indices&&n&&Object.keys(e.indices).forEach(function(t){e=zf(e,{page:1},{multiIndexContext:{targetedIndex:t}},!0,i)}),i?function(e,t,r,n){var i=r?{page:1}:void 0;return cl({},e,sl({},n,cl({},e[n],t)),i)}(e,t,n,i):function(e,t,r){var n=r?{page:1}:void 0;return cl({},e,t,n)}(e,t,n))}function Vf(e){var t=e.match(/^([^.]*)\.(.*)/);return{namespace:t&&t[1],attributeName:t&&t[2]}}function Wf(e,t,r,n,i,a){var o=Uf(r),s=Vf(n),c=s.namespace,u=s.attributeName;if(Qf(r)&&t.indices&&c&&t.indices[""+o]&&Lf(t.indices[""+o][c],""+u)||Qf(r)&&t.indices&&Lf(t,"indices."+o+"."+n)||!Qf(r)&&c&&Lf(t[c],u)||!Qf(r)&&Lf(t,n)){return a(Qf(r)?c?Rn(t.indices[""+o][c],u):Rn(t.indices[o],n):c?Rn(t[c],u):Rn(t,n))}return e.defaultRefinement?e.defaultRefinement:i}function Jf(e,t,r){var n=Uf(t),i=Vf(r),a=i.namespace,o=i.attributeName;return Qf(t)&&Boolean(e.indices)?a?cl({},e,{indices:cl({},e.indices,sl({},n,cl({},e.indices[n],sl({},a,Da(e.indices[n][a],""+o)))))}):Da(e,"indices."+n+"."+r):a?cl({},e,sl({},a,Da(e[a],""+o))):Da(e,""+r)}var $f=Df({displayName:"AlgoliaConfigure",getProvidedProps:function(){return{}},getSearchParameters:function(e,t){var r=Da(t,"children");return e.setQueryParameters(r)},transitionState:function(e,t,r){var n="configure",i=Da(e,"children"),a=this._props?qf(_r(this._props),_r(e)):[];return this._props=e,zf(r,sl({},n,cl({},Da(r[n],a),i)),this.context)},cleanUp:function(e,t){var r="configure",n=Uf(this.context),i=Qf(this.context)&&t.indices?t.indices[n]:t,a=(i&&i[r]?Object.keys(i[r]):[]).reduce(function(t,n){return e[n]||(t[n]=i[r][n]),t},{});return zf(t,sl({},r,a),this.context)}})(function(){return null}),Kf=Df({displayName:"AlgoliaCurrentRefinements",propTypes:{transformItems:L.func},getProvidedProps:function(e,t,r,n){var i=n.reduce(function(t,r){return void 0!==r.items&&(e.clearsQuery||"query"!==r.id)?e.clearsQuery&&"query"===r.id&&""===r.items[0].currentRefinement?t:t.concat(r.items.map(function(e){return cl({},e,{id:r.id,index:r.index})})):t},[]);return{items:e.transformItems?e.transformItems(i):i,canRefine:i.length>0}},refine:function(e,t,r){return(r instanceof Array?r.map(function(e){return e.value}):[r]).reduce(function(e,t){return t(e)},t)}}),Yf=function(e){function t(){return al(this,t),fl(this,(t.__proto__||Object.getPrototypeOf(t)).apply(this,arguments))}return ul(t,e),ol(t,[{key:"componentWillMount",value:function(){this.context.setCanRefine&&this.context.setCanRefine(this.props.canRefine)}},{key:"componentWillReceiveProps",value:function(e){this.context.setCanRefine&&this.props.canRefine!==e.canRefine&&this.context.setCanRefine(e.canRefine)}},{key:"render",value:function(){return this.props.children}}]),t}(t.Component);Yf.propTypes={children:L.node.isRequired,canRefine:L.bool.isRequired},Yf.contextTypes={setCanRefine:L.func};var Gf=O(function(e){!function(){var t={}.hasOwnProperty;function r(){for(var e=[],n=0;n<arguments.length;n++){var i=arguments[n];if(i){var a=typeof i;if("string"===a||"number"===a)e.push(i);else if(Array.isArray(i))e.push(r.apply(null,i));else if("object"===a)for(var o in i)t.call(i,o)&&i[o]&&e.push(o)}}return e.join(" ")}e.exports?e.exports=r:window.classNames=r}()}),Xf=(L.shape({register:L.func.isRequired,swap:L.func.isRequired,unregister:L.func.isRequired}),L.shape({createURL:L.func.isRequired,setState:L.func.isRequired,getState:L.func.isRequired,unlisten:L.func.isRequired}),function(e){return function(t,r,n){var i=t[r];if(i){var a=!0,o=!1,s=void 0;try{for(var c,u=Object.keys(i)[Symbol.iterator]();!(a=(c=u.next()).done);a=!0){var l=c.value;if(-1===e.indexOf(l))return new Error("Unknown `"+r+"` key `"+l+"`. Check the render method of `"+n+"`.")}}catch(e){o=!0,s=e}finally{try{!a&&u.return&&u.return()}finally{if(o)throw s}}}}});function Zf(e){return function(t){function n(n){var i=n.translations,a=ll(n,["translations"]);return r.createElement(t,cl({translate:function(t){for(var r=arguments.length,n=Array(r>1?r-1:0),a=1;a<r;a++)n[a-1]=arguments[a];var o=i&&Lf(i,t)?i[t]:e[t];return"function"==typeof o?o.apply(void 0,n):o}},a))}return n.displayName="Translatable("+el(t)+")",n.propTypes={translations:Xf(Object.keys(e))},n}}var eh=function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"ais";return function(){for(var r=arguments.length,n=Array(r),i=0;i<r;i++)n[i]=arguments[i];var a=n.filter(function(e){return e||""===e}).map(function(r){var n=t+"-"+e;return r?n+"-"+r:n});return Gf(a)}},th=eh("CurrentRefinements"),rh=function(e){var t=e.items,n=e.canRefine,i=e.refine,a=e.translate,o=e.className;return r.createElement("div",{className:Gf(th("",!n&&"-noRefinement"),o)},r.createElement("ul",{className:th("list",!n&&"list--noRefinement")},t.map(function(e){return r.createElement("li",{key:e.label,className:th("item")},r.createElement("span",{className:th("label")},e.label),e.items?e.items.map(function(e){return r.createElement("span",{key:e.label,className:th("category")},r.createElement("span",{className:th("categoryLabel")},e.label),r.createElement("button",{className:th("delete"),onClick:function(){return i(e.value)}},a("clearFilter",e)))}):r.createElement("span",{className:th("category")},r.createElement("button",{className:th("delete"),onClick:function(){return i(e.value)}},a("clearFilter",e))))})))},nh=L.arrayOf(L.shape({label:L.string.isRequired,value:L.func.isRequired,items:function(){return nh.apply(void 0,arguments)}}));rh.propTypes={items:nh.isRequired,canRefine:L.bool.isRequired,refine:L.func.isRequired,translate:L.func.isRequired,className:L.string},rh.defaultProps={className:""};var ih=Zf({clearFilter:"✕"})(rh),ah=Kf(function(e){return r.createElement(Yf,e,r.createElement(ih,e))}),oh=function(e){return e.attributes[0]},sh="hierarchicalMenu";function ch(e,t,r){return Wf(e,t,r,sh+"."+oh(e),null,function(e){return""===e?null:e})}function uh(e,t,r,n){return e.map(function(e){return{label:e.name,value:function(e,t,r,n){var i=t.id,a=t.attributes,o=t.separator,s=t.rootPath,c=t.showParentLevel,u=ch(t,r,n);return null===u?e:new Xu({hierarchicalFacets:[{name:i,attributes:a,separator:o,rootPath:s,showParentLevel:c}]}).toggleHierarchicalFacetRefinement(i,u).toggleHierarchicalFacetRefinement(i,e).getHierarchicalRefinement(i)[0]}(e.path,t,r,n),count:e.count,isRefined:e.isRefined,items:e.data&&uh(e.data,t,r,n)}})}function lh(e,t,r,n){var i=oh(e);return zf(t,sl({},i,r||""),n,!0,sh)}var fh=["name:asc"],hh=Df({displayName:"AlgoliaHierarchicalMenu",propTypes:{attributes:function(e,t,r){if(!Array.isArray(e[t])||e[t].some(function(e){return"string"!=typeof e})||e[t].length<1)return new Error("Invalid prop "+t+" supplied to "+r+". Expected an Array of Strings")},separator:L.string,rootPath:L.string,showParentLevel:L.bool,defaultRefinement:L.string,showMore:L.bool,limit:L.number,showMoreLimit:L.number,transformItems:L.func},defaultProps:{showMore:!1,limit:10,showMoreLimit:20,separator:" > ",rootPath:null,showParentLevel:!0},getProvidedProps:function(e,t,r){var n=e.showMore,i=e.limit,a=e.showMoreLimit,o=oh(e),s=Bf(r,this.context);if(!(Boolean(s)&&Boolean(s.getFacetByName(o))))return{items:[],currentRefinement:ch(e,t,this.context),canRefine:!1};var c=n?a:i,u=s.getFacetValues(o,{sortBy:fh}),l=u.data?uh(u.data,e,t,this.context):[];return{items:function e(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:[],r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:10;return t.slice(0,r).map(function(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return Array.isArray(t.items)?cl({},t,{items:e(t.items,r)}):t})}(e.transformItems?e.transformItems(l):l,c),currentRefinement:ch(e,t,this.context),canRefine:l.length>0}},refine:function(e,t,r){return lh(e,t,r,this.context)},cleanUp:function(e,t){return function(e,t,r){return Jf(t,r,sh+"."+oh(e))}(e,t,this.context)},getSearchParameters:function(e,t,r){var n=t.attributes,i=t.separator,a=t.rootPath,o=t.showParentLevel,s=t.showMore,c=t.limit,u=t.showMoreLimit,l=oh(t),f=s?u:c;e=e.addHierarchicalFacet({name:l,attributes:n,separator:i,rootPath:a,showParentLevel:o}).setQueryParameters({maxValuesPerFacet:Math.max(e.maxValuesPerFacet||0,f)});var h=ch(t,r,this.context);return null!==h&&(e=e.toggleHierarchicalFacetRefinement(l,h)),e},getMetadata:function(e,t){var r=this,n=e.attributes[0],i=oh(e),a=ch(e,t,this.context);return{id:i,index:Uf(this.context),items:a?[{label:n+": "+a,attribute:n,value:function(t){return lh(e,t,"",r.context)},currentRefinement:a}]:[]}}}),ph=eh("SearchBox"),dh=r.createElement("svg",{width:"18",height:"18",viewBox:"0 0 38 38",xmlns:"http://www.w3.org/2000/svg",stroke:"#444",className:ph("loadingIcon")},r.createElement("g",{fill:"none",fillRule:"evenodd"},r.createElement("g",{transform:"translate(1 1)",strokeWidth:"2"},r.createElement("circle",{strokeOpacity:".5",cx:"18",cy:"18",r:"18"}),r.createElement("path",{d:"M36 18c0-9.94-8.06-18-18-18"},r.createElement("animateTransform",{attributeName:"transform",type:"rotate",from:"0 18 18",to:"360 18 18",dur:"1s",repeatCount:"indefinite"}))))),mh=r.createElement("svg",{className:ph("resetIcon"),xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 20 20",width:"10",height:"10"},r.createElement("path",{d:"M8.114 10L.944 2.83 0 1.885 1.886 0l.943.943L10 8.113l7.17-7.17.944-.943L20 1.886l-.943.943-7.17 7.17 7.17 7.17.943.944L18.114 20l-.943-.943-7.17-7.17-7.17 7.17-.944.943L0 18.114l.943-.943L8.113 10z"})),vh=r.createElement("svg",{className:ph("submitIcon"),xmlns:"http://www.w3.org/2000/svg",width:"10",height:"10",viewBox:"0 0 40 40"},r.createElement("path",{d:"M26.804 29.01c-2.832 2.34-6.465 3.746-10.426 3.746C7.333 32.756 0 25.424 0 16.378 0 7.333 7.333 0 16.378 0c9.046 0 16.378 7.333 16.378 16.378 0 3.96-1.406 7.594-3.746 10.426l10.534 10.534c.607.607.61 1.59-.004 2.202-.61.61-1.597.61-2.202.004L26.804 29.01zm-10.426.627c7.323 0 13.26-5.936 13.26-13.26 0-7.32-5.937-13.257-13.26-13.257C9.056 3.12 3.12 9.056 3.12 16.378c0 7.323 5.936 13.26 13.258 13.26z"})),gh=function(e){function t(e){al(this,t);var r=fl(this,(t.__proto__||Object.getPrototypeOf(t)).call(this));return r.getQuery=function(){return r.props.searchAsYouType?r.props.currentRefinement:r.state.query},r.onInputMount=function(e){r.input=e,r.props.__inputRef&&r.props.__inputRef(e)},r.onKeyDown=function(e){if(r.props.focusShortcuts){var t=r.props.focusShortcuts.map(function(e){return"string"==typeof e?e.toUpperCase().charCodeAt(0):e}),n=e.target||e.srcElement,i=n.tagName;if(!n.isContentEditable&&"INPUT"!==i&&"SELECT"!==i&&"TEXTAREA"!==i){var a=e.which||e.keyCode;-1!==t.indexOf(a)&&(r.input.focus(),e.stopPropagation(),e.preventDefault())}}},r.onSubmit=function(e){e.preventDefault(),e.stopPropagation(),r.input.blur();var t=r.props,n=t.refine;return t.searchAsYouType||n(r.getQuery()),!1},r.onChange=function(e){var t=r.props,n=t.searchAsYouType,i=t.refine,a=t.onChange,o=e.target.value;n?i(o):r.setState({query:o}),a&&a(e)},r.onReset=function(e){var t=r.props,n=t.searchAsYouType,i=t.refine,a=t.onReset;i(""),r.input.focus(),n||r.setState({query:""}),a&&a(e)},r.state={query:e.searchAsYouType?null:e.currentRefinement},r}return ul(t,e),ol(t,[{key:"componentDidMount",value:function(){document.addEventListener("keydown",this.onKeyDown)}},{key:"componentWillUnmount",value:function(){document.removeEventListener("keydown",this.onKeyDown)}},{key:"componentWillReceiveProps",value:function(e){e.searchAsYouType||e.currentRefinement===this.props.currentRefinement||this.setState({query:e.currentRefinement})}},{key:"render",value:function(){var e=this,t=this.props,n=t.className,i=t.translate,a=t.autoFocus,o=t.loadingIndicator,s=t.submit,c=t.reset,u=this.getQuery(),l=Object.keys(this.props).reduce(function(t,r){return-1===["onsubmit","onreset","onchange"].indexOf(r.toLowerCase())&&0===r.indexOf("on")?cl({},t,sl({},r,e.props[r])):t},{}),f=this.props.showLoadingIndicator&&this.props.isSearchStalled;return r.createElement("div",{className:Gf(ph(""),n)},r.createElement("form",{noValidate:!0,onSubmit:this.props.onSubmit?this.props.onSubmit:this.onSubmit,onReset:this.onReset,className:ph("form",f&&"form--stalledSearch"),action:"",role:"search"},r.createElement("input",cl({ref:this.onInputMount,type:"search",placeholder:i("placeholder"),autoFocus:a,autoComplete:"off",autoCorrect:"off",autoCapitalize:"off",spellCheck:"false",required:!0,maxLength:"512",value:u,onChange:this.onChange},l,{className:ph("input")})),r.createElement("button",{type:"submit",title:i("submitTitle"),className:ph("submit")},s),r.createElement("button",{type:"reset",title:i("resetTitle"),className:ph("reset"),hidden:!u||f},c),this.props.showLoadingIndicator&&r.createElement("span",{hidden:!f,className:ph("loadingIndicator")},o)))}}]),t}(t.Component);gh.propTypes={currentRefinement:L.string,className:L.string,refine:L.func.isRequired,translate:L.func.isRequired,loadingIndicator:L.node,reset:L.node,submit:L.node,focusShortcuts:L.arrayOf(L.oneOfType([L.string,L.number])),autoFocus:L.bool,searchAsYouType:L.bool,onSubmit:L.func,onReset:L.func,onChange:L.func,isSearchStalled:L.bool,showLoadingIndicator:L.bool,__inputRef:L.func},gh.defaultProps={currentRefinement:"",className:"",focusShortcuts:["s","/"],autoFocus:!1,searchAsYouType:!0,showLoadingIndicator:!1,isSearchStalled:!1,loadingIndicator:dh,reset:mh,submit:vh};var yh=Zf({resetTitle:"Clear the search query.",submitTitle:"Submit your search query.",placeholder:"Search here…"})(gh),bh=L.arrayOf(L.shape({value:L.any,label:L.node.isRequired,items:function(){return bh.apply(void 0,arguments)}})),Rh=function(e){function t(){al(this,t);var e=fl(this,(t.__proto__||Object.getPrototypeOf(t)).call(this));return e.onShowMoreClick=function(){e.setState(function(e){return{extended:!e.extended}})},e.getLimit=function(){var t=e.props,r=t.limit,n=t.showMoreLimit;return e.state.extended?n:r},e.resetQuery=function(){e.setState({query:""})},e.renderItem=function(t,n){var i=t.items&&r.createElement("ul",{className:e.props.cx("list","list--child")},t.items.slice(0,e.getLimit()).map(function(r){return e.renderItem(r,t)}));return r.createElement("li",{key:t.key||t.label,className:e.props.cx("item",t.isRefined&&"item--selected",t.noRefinement&&"item--noRefinement",i&&"item--parent")},e.props.renderItem(t,n),i)},e.state={extended:!1,query:""},e}return ul(t,e),ol(t,[{key:"renderShowMore",value:function(){var e=this.props,t=e.showMore,n=e.translate,i=e.cx,a=this.state.extended,o=this.props.limit>=this.props.items.length;return t?r.createElement("button",{disabled:o,className:i("showMore",o&&"showMore--disabled"),onClick:this.onShowMoreClick},n("showMore",a)):null}},{key:"renderSearchBox",value:function(){var e=this,t=this.props,n=t.cx,i=t.searchForItems,a=t.isFromSearch,o=t.translate,s=t.items,c=t.selectItem,u=0===s.length&&""!==this.state.query?r.createElement("div",{className:n("noResults")},o("noResults")):null;return r.createElement("div",{className:n("searchBox")},r.createElement(yh,{currentRefinement:this.state.query,refine:function(t){e.setState({query:t}),i(t)},focusShortcuts:[],translate:o,onSubmit:function(t){t.preventDefault(),t.stopPropagation(),a&&c(s[0],e.resetQuery)}}),u)}},{key:"render",value:function(){var e=this,t=this.props,n=t.cx,i=t.items,a=t.className,o=t.searchable,s=t.canRefine,c=o?this.renderSearchBox():null,u=Gf(n("",!s&&"-noRefinement"),a);return 0===i.length?r.createElement("div",{className:u},c):r.createElement("div",{className:u},c,r.createElement("ul",{className:n("list",!s&&"list--noRefinement")},i.slice(0,this.getLimit()).map(function(t){return e.renderItem(t,e.resetQuery)})),this.renderShowMore())}}]),t}(t.Component);Rh.propTypes={cx:L.func.isRequired,translate:L.func,items:bh,renderItem:L.func.isRequired,selectItem:L.func,className:L.string,showMore:L.bool,limit:L.number,showMoreLimit:L.number,show:L.func,searchForItems:L.func,searchable:L.bool,isFromSearch:L.bool,canRefine:L.bool},Rh.defaultProps={className:"",isFromSearch:!1};var _h=function(e){function t(){var e,r,n;al(this,t);for(var i=arguments.length,a=Array(i),o=0;o<i;o++)a[o]=arguments[o];return r=n=fl(this,(e=t.__proto__||Object.getPrototypeOf(t)).call.apply(e,[this].concat(a))),n.onClick=function(e){var t,r;(r=1===(t=e).button,Boolean(r||t.altKey||t.ctrlKey||t.metaKey||t.shiftKey))||(n.props.onClick(),e.preventDefault())},fl(n,r)}return ul(t,e),ol(t,[{key:"render",value:function(){return r.createElement("a",cl({},Da(this.props,"onClick"),{onClick:this.onClick}))}}]),t}(t.Component);_h.propTypes={onClick:L.func.isRequired};var xh=eh("HierarchicalMenu"),wh=L.arrayOf(L.shape({label:L.string.isRequired,value:L.string,count:L.number.isRequired,items:function(){return wh.apply(void 0,arguments)}})),Sh=function(e){function t(){var e,n,i;al(this,t);for(var a=arguments.length,o=Array(a),s=0;s<a;s++)o[s]=arguments[s];return n=i=fl(this,(e=t.__proto__||Object.getPrototypeOf(t)).call.apply(e,[this].concat(o))),i.renderItem=function(e){var t=i.props,n=t.createURL,a=t.refine;return r.createElement(_h,{className:xh("link"),onClick:function(){return a(e.value)},href:n(e.value)},r.createElement("span",{className:xh("label")},e.label)," ",r.createElement("span",{className:xh("count")},e.count))},fl(i,n)}return ul(t,e),ol(t,[{key:"render",value:function(){return r.createElement(Rh,cl({renderItem:this.renderItem,cx:xh},ku(this.props,["translate","items","showMore","limit","showMoreLimit","isEmpty","canRefine","className"])))}}]),t}(t.Component);Sh.propTypes={translate:L.func.isRequired,refine:L.func.isRequired,createURL:L.func.isRequired,canRefine:L.bool.isRequired,items:wh,showMore:L.bool,className:L.string,limit:L.number,showMoreLimit:L.number,transformItems:L.func},Sh.defaultProps={className:""};var jh=Zf({showMore:function(e){return e?"Show less":"Show more"}})(Sh),Fh=hh(function(e){return r.createElement(Yf,e,r.createElement(jh,e))});function Ph(e){var t=e.preTag,r=e.postTag,n=e.highlightedValue,i=(void 0===n?"":n).split(t),a=i.shift(),o=""===a?[]:[{value:a,isHighlighted:!1}];if(r===t){var s=!0;i.forEach(function(e){o.push({value:e,isHighlighted:s}),s=!s})}else i.forEach(function(e){var t=e.split(r);o.push({value:t[0],isHighlighted:!0}),""!==t[1]&&o.push({value:t[1],isHighlighted:!1})});return o}var Nh=function(e){var t=e.attribute,r=e.hit,n=e.highlightProperty;return function(e){var t=e.preTag,r=void 0===t?"<em>":t,n=e.postTag,i=void 0===n?"</em>":n,a=e.highlightProperty,o=e.attribute,s=e.hit;if(!s)throw new Error("`hit`, the matching record, must be provided");var c=Rn(s[a],o,{});return Array.isArray(c)?c.map(function(e){return Ph({preTag:r,postTag:i,highlightedValue:e.value})}):Ph({preTag:r,postTag:i,highlightedValue:c.value})}({attribute:t,hit:r,preTag:il.highlightPreTag,postTag:il.highlightPostTag,highlightProperty:n})},Eh=Df({displayName:"AlgoliaHighlighter",propTypes:{},getProvidedProps:function(){return{highlight:Nh}}});function Oh(e,t){return"split-"+e+"-"+t}var Th=function(e){var t=e.cx,n=e.value,i=e.highlightedTagName,a=e.isHighlighted,o=e.nonHighlightedTagName,s=a?i:o,c=a?"highlighted":"nonHighlighted";return r.createElement(s,{className:t(c)},n)};Th.propTypes={cx:L.func.isRequired,value:L.string.isRequired,isHighlighted:L.bool.isRequired,highlightedTagName:L.string.isRequired,nonHighlightedTagName:L.string.isRequired};var Ah=function(e){var t=e.cx,n=e.hit,i=e.attribute,a=e.highlight,o=e.highlightProperty,s=e.tagName,c=e.nonHighlightedTagName,u=e.separator,l=e.className,f=a({hit:n,attribute:i,highlightProperty:o});return r.createElement("span",{className:Gf(t(""),l)},f.map(function(e,a){if(Array.isArray(e)){var o=a===f.length-1;return r.createElement("span",{key:Oh(a,n[i][a])},e.map(function(e,n){return r.createElement(Th,{cx:t,key:Oh(n,e.value),value:e.value,highlightedTagName:s,nonHighlightedTagName:c,isHighlighted:e.isHighlighted})}),!o&&r.createElement("span",{className:t("separator")},u))}return r.createElement(Th,{cx:t,key:Oh(a,e.value),value:e.value,highlightedTagName:s,nonHighlightedTagName:c,isHighlighted:e.isHighlighted})}))};Ah.propTypes={cx:L.func.isRequired,hit:L.object.isRequired,attribute:L.string.isRequired,highlight:L.func.isRequired,highlightProperty:L.string.isRequired,tagName:L.string,nonHighlightedTagName:L.string,className:L.string,separator:L.node},Ah.defaultProps={tagName:"em",nonHighlightedTagName:"span",className:"",separator:", "};var Ch=eh("Highlight"),Ih=Eh(function(e){return r.createElement(Ah,cl({},e,{highlightProperty:"_highlightResult",cx:Ch}))}),kh=eh("Snippet"),qh=Eh(function(e){return r.createElement(Ah,cl({},e,{highlightProperty:"_snippetResult",cx:kh}))}),Mh=Df({displayName:"AlgoliaHits",getProvidedProps:function(e,t,r){var n=Bf(r,this.context);return{hits:n?n.hits:[]}},getSearchParameters:function(e){return e}}),Hh=eh("Hits"),Lh=function(e){var t=e.hits,n=e.className,i=e.hitComponent;return r.createElement("div",{className:Gf(Hh(""),n)},r.createElement("ul",{className:Hh("list")},t.map(function(e){return r.createElement("li",{className:Hh("item"),key:e.objectID},r.createElement(i,{hit:e}))})))};Lh.propTypes={hits:L.arrayOf(L.object).isRequired,className:L.string,hitComponent:L.func},Lh.defaultProps={className:"",hitComponent:function(e){return r.createElement("div",{style:{borderBottom:"1px solid #bbb",paddingBottom:"5px",marginBottom:"5px",wordBreak:"break-all"}},JSON.stringify(e).slice(0,100),"...")}};var Dh=Mh(Lh);function Uh(e,t,r){return Wf(e,t,r,"hitsPerPage",null,function(e){return"string"==typeof e?parseInt(e,10):e})}var Bh=Df({displayName:"AlgoliaHitsPerPage",propTypes:{defaultRefinement:L.number.isRequired,items:L.arrayOf(L.shape({label:L.string,value:L.number.isRequired})).isRequired,transformItems:L.func},getProvidedProps:function(e,t){var r=Uh(e,t,this.context),n=e.items.map(function(e){return e.value===r?cl({},e,{isRefined:!0}):cl({},e,{isRefined:!1})});return{items:e.transformItems?e.transformItems(n):n,currentRefinement:r}},refine:function(e,t,r){return zf(t,sl({},"hitsPerPage",r),this.context,!0)},cleanUp:function(e,t){return Jf(t,this.context,"hitsPerPage")},getSearchParameters:function(e,t,r){return e.setHitsPerPage(Uh(t,r,this.context))},getMetadata:function(){return{id:"hitsPerPage"}}}),Qh=function(e){function t(){var e,r,n;al(this,t);for(var i=arguments.length,a=Array(i),o=0;o<i;o++)a[o]=arguments[o];return r=n=fl(this,(e=t.__proto__||Object.getPrototypeOf(t)).call.apply(e,[this].concat(a))),n.onChange=function(e){n.props.onSelect(e.target.value)},fl(n,r)}return ul(t,e),ol(t,[{key:"render",value:function(){var e=this.props,t=e.cx,n=e.items,i=e.selectedItem;return r.createElement("select",{className:t("select"),value:i,onChange:this.onChange},n.map(function(e){return r.createElement("option",{className:t("option"),key:Lf(e,"key")?e.key:e.value,disabled:e.disabled,value:e.value},Lf(e,"label")?e.label:e.value)}))}}]),t}(t.Component);Qh.propTypes={cx:L.func.isRequired,onSelect:L.func.isRequired,items:L.arrayOf(L.shape({value:L.oneOfType([L.string,L.number]).isRequired,key:L.oneOfType([L.string,L.number]),label:L.string,disabled:L.bool})).isRequired,selectedItem:L.oneOfType([L.string,L.number]).isRequired};var zh=eh("HitsPerPage"),Vh=function(e){function t(){return al(this,t),fl(this,(t.__proto__||Object.getPrototypeOf(t)).apply(this,arguments))}return ul(t,e),ol(t,[{key:"render",value:function(){var e=this.props,t=e.items,n=e.currentRefinement,i=e.refine,a=e.className;return r.createElement("div",{className:Gf(zh(""),a)},r.createElement(Qh,{onSelect:i,selectedItem:n,items:t,cx:zh}))}}]),t}(t.Component);Vh.propTypes={items:L.arrayOf(L.shape({value:L.number.isRequired,label:L.string})).isRequired,currentRefinement:L.number.isRequired,refine:L.func.isRequired,className:L.string},Vh.defaultProps={className:""};var Wh=Bh(Vh);function Jh(e,t,r){return Wf(e,t,r,"page",1,function(e){return"string"==typeof e&&(e=parseInt(e,10)),e})}var $h=Df({displayName:"AlgoliaInfiniteHits",getProvidedProps:function(e,t,r){var n=Bf(r,this.context);if(this._allResults=this._allResults||[],!n)return{hits:[],hasMore:!1};var i=n.hits,a=n.page,o=n.nbPages;0===a?this._allResults=i:a>this.previousPage?this._allResults=[].concat(pl(this._allResults),pl(i)):a<this.previousPage&&(this._allResults=i);var s=a<o-1;return this.previousPage=a,{hits:this._allResults,hasMore:s}},getSearchParameters:function(e,t,r){return e.setQueryParameters({page:Jh(t,r,this.context)-1})},refine:function(e,t){var r=Jh(e,t,this.context)+1;return zf(t,sl({},"page",r),this.context,!1)}}),Kh=eh("InfiniteHits"),Yh=function(e){function t(){return al(this,t),fl(this,(t.__proto__||Object.getPrototypeOf(t)).apply(this,arguments))}return ul(t,e),ol(t,[{key:"render",value:function(){var e=this.props,t=e.hitComponent,n=e.hits,i=e.hasMore,a=e.refine,o=e.translate,s=e.className;return r.createElement("div",{className:Gf(Kh(""),s)},r.createElement("ul",{className:Kh("list")},n.map(function(e){return r.createElement("li",{key:e.objectID,className:Kh("item")},r.createElement(t,{hit:e}))})),r.createElement("button",{className:Kh("loadMore",!i&&"loadMore--disabled"),onClick:function(){return a()},disabled:!i},o("loadMore")))}}]),t}(t.Component);Yh.propTypes={hits:L.arrayOf(L.object).isRequired,hasMore:L.bool.isRequired,refine:L.func.isRequired,translate:L.func.isRequired,className:L.string,hitComponent:L.oneOfType([L.string,L.func])},Yh.defaultProps={className:"",hitComponent:function(e){return r.createElement("div",{style:{borderBottom:"1px solid #bbb",paddingBottom:"5px",marginBottom:"5px",wordBreak:"break-all"}},JSON.stringify(e).slice(0,100),"...")}};var Gh=$h(Zf({loadMore:"Load more"})(Yh)),Xh="menu";function Zh(e){return e.attribute}function ep(e,t,r){return Wf(e,t,r,Xh+"."+Zh(e),null,function(e){return""===e?null:e})}function tp(e,t,r,n){return e===ep(t,r,n)?"":e}function rp(e){var t=e.showMore,r=e.limit,n=e.showMoreLimit;return t?n:r}function np(e,t,r,n){var i=Zh(e);return zf(t,sl({},i,r||""),n,!0,Xh)}var ip=["count:desc","name:asc"],ap=Df({displayName:"AlgoliaMenu",propTypes:{attribute:L.string.isRequired,showMore:L.bool,limit:L.number,showMoreLimit:L.number,defaultRefinement:L.string,transformItems:L.func,searchable:L.bool},defaultProps:{showMore:!1,limit:10,showMoreLimit:20},getProvidedProps:function(e,t,r,n,i){var a=this,o=e.attribute,s=e.searchable,c=Bf(r,this.context),u=Boolean(c)&&Boolean(c.getFacetByName(o)),l=Boolean(i&&i[o]&&""!==i.query);if(s&&this.context.multiIndexContext)throw new Error("react-instantsearch: searching in *List is not available when used inside a multi index context");if(!u)return{items:[],currentRefinement:ep(e,t,this.context),isFromSearch:l,searchable:s,canRefine:u};var f=l?i[o].map(function(r){return{label:r.value,value:tp(r.value,e,t,a.context),_highlightResult:{label:{value:r.highlighted}},count:r.count,isRefined:r.isRefined}}):c.getFacetValues(o,{sortBy:ip}).map(function(r){return{label:r.name,value:tp(r.name,e,t,a.context),count:r.count,isRefined:r.isRefined}}),h=s&&!l?ds(f,["isRefined","count","label"],["desc","desc","asc"]):f;return{items:(e.transformItems?e.transformItems(h):h).slice(0,rp(e)),currentRefinement:ep(e,t,this.context),isFromSearch:l,searchable:s,canRefine:f.length>0}},refine:function(e,t,r){return np(e,t,r,this.context)},searchForFacetValues:function(e,t,r){return{facetName:e.attribute,query:r,maxFacetHits:rp(e)}},cleanUp:function(e,t){return function(e,t,r){return Jf(t,r,Xh+"."+Zh(e))}(e,t,this.context)},getSearchParameters:function(e,t,r){var n=t.attribute;e=(e=e.setQueryParameters({maxValuesPerFacet:Math.max(e.maxValuesPerFacet||0,rp(t))})).addDisjunctiveFacet(n);var i=ep(t,r,this.context);return null!==i&&(e=e.addDisjunctiveFacetRefinement(n,i)),e},getMetadata:function(e,t){var r=this,n=Zh(e),i=ep(e,t,this.context);return{id:n,index:Uf(this.context),items:null===i?[]:[{label:e.attribute+": "+i,attribute:e.attribute,value:function(t){return np(e,t,"",r.context)},currentRefinement:i}]}}}),op=eh("Menu"),sp=function(e){function t(){var e,n,i;al(this,t);for(var a=arguments.length,o=Array(a),s=0;s<a;s++)o[s]=arguments[s];return n=i=fl(this,(e=t.__proto__||Object.getPrototypeOf(t)).call.apply(e,[this].concat(o))),i.renderItem=function(e,t){var n=i.props.createURL,a=i.props.isFromSearch?r.createElement(Ih,{attribute:"label",hit:e}):e.label;return r.createElement(_h,{className:op("link"),onClick:function(){return i.selectItem(e,t)},href:n(e.value)},r.createElement("span",{className:op("label")},a)," ",r.createElement("span",{className:op("count")},e.count))},i.selectItem=function(e,t){t(),i.props.refine(e.value)},fl(i,n)}return ul(t,e),ol(t,[{key:"render",value:function(){return r.createElement(Rh,cl({renderItem:this.renderItem,selectItem:this.selectItem,cx:op},ku(this.props,["translate","items","showMore","limit","showMoreLimit","isFromSearch","searchForItems","searchable","canRefine","className"])))}}]),t}(t.Component);sp.propTypes={translate:L.func.isRequired,refine:L.func.isRequired,searchForItems:L.func.isRequired,searchable:L.bool,createURL:L.func.isRequired,items:L.arrayOf(L.shape({label:L.string.isRequired,value:L.string.isRequired,count:L.number.isRequired,isRefined:L.bool.isRequired})),isFromSearch:L.bool.isRequired,canRefine:L.bool.isRequired,showMore:L.bool,limit:L.number,showMoreLimit:L.number,transformItems:L.func,className:L.string},sp.defaultProps={className:""};var cp=Zf({showMore:function(e){return e?"Show less":"Show more"},noResults:"No results",submit:null,reset:null,resetTitle:"Clear the search query.",submitTitle:"Submit your search query.",placeholder:"Search here…"})(sp),up=ap(function(e){return r.createElement(Yf,e,r.createElement(cp,e))}),lp=eh("MenuSelect"),fp=function(e){function t(){var e,r,n;al(this,t);for(var i=arguments.length,a=Array(i),o=0;o<i;o++)a[o]=arguments[o];return r=n=fl(this,(e=t.__proto__||Object.getPrototypeOf(t)).call.apply(e,[this].concat(a))),n.handleSelectChange=function(e){var t=e.target.value;n.props.refine("ais__see__all__option"===t?"":t)},fl(n,r)}return ul(t,e),ol(t,[{key:"render",value:function(){var e=this.props,t=e.items,n=e.canRefine,i=e.translate,a=e.className;return r.createElement("div",{className:Gf(lp("",!n&&"-noRefinement"),a)},r.createElement("select",{value:this.selectedValue,onChange:this.handleSelectChange,className:lp("select")},r.createElement("option",{value:"ais__see__all__option",className:lp("option")},i("seeAllOption")),t.map(function(e){return r.createElement("option",{key:e.value,value:e.value,className:lp("option")},e.label," (",e.count,")")})))}},{key:"selectedValue",get:function(){return(Jn(this.props.items,{isRefined:!0})||{value:"ais__see__all__option"}).value}}]),t}(t.Component);fp.propTypes={items:L.arrayOf(L.shape({label:L.string.isRequired,value:L.string.isRequired,count:L.oneOfType([L.number.isRequired,L.string.isRequired]),isRefined:L.bool.isRequired})).isRequired,canRefine:L.bool.isRequired,refine:L.func.isRequired,translate:L.func.isRequired,className:L.string},fp.defaultProps={className:""};var hp=Zf({seeAllOption:"See all"})(fp),pp=ap(function(e){return r.createElement(Yf,e,r.createElement(hp,e))});function dp(e){return void 0===e.start&&void 0===e.end?"":(e.start?e.start:"")+":"+(e.end?e.end:"")}var mp="multiRange";function vp(e){return e.attribute}function gp(e,t,r){return Wf(e,t,r,mp+"."+vp(e),"",function(e){return""===e?"":e})}function yp(e,t,r,n){return zf(t,sl({},vp(e),r),n,!0,mp)}var bp=Df({displayName:"AlgoliaNumericMenu",propTypes:{id:L.string,attribute:L.string.isRequired,items:L.arrayOf(L.shape({label:L.node,start:L.number,end:L.number})).isRequired,transformItems:L.func},getProvidedProps:function(e,t,r){var n=e.attribute,i=gp(e,t,this.context),a=Bf(r,this.context),o=e.items.map(function(t){var r=dp(t);return{label:t.label,value:r,isRefined:r===i,noRefinement:!!a&&function(e,t,r){var n=t.getFacetByName(e)?t.getFacetStats(e):null,i=r.split(":"),a=0===Number(i[0])||""===r?Number.NEGATIVE_INFINITY:Number(i[0]),o=0===Number(i[1])||""===r?Number.POSITIVE_INFINITY:Number(i[1]);return!(Boolean(n)&&(function(e,t,r){return e.min>t&&e.min<r||e.max>t&&e.max<r}(n,a,o)||function(e,t,r){return t>e.min&&t<e.max||r>e.min&&r<e.max}(n,a,o)))}(vp(e),a,r)}}),s=a&&a.getFacetByName(n)?a.getFacetStats(n):null,c=Jn(o,function(e){return!0===e.isRefined});return o.some(function(e){return""===e.value})||o.push({value:"",isRefined:Gn(c),noRefinement:!s,label:"All"}),{items:e.transformItems?e.transformItems(o):o,currentRefinement:i,canRefine:o.length>0&&o.some(function(e){return!1===e.noRefinement})}},refine:function(e,t,r){return yp(e,t,r,this.context)},cleanUp:function(e,t){return function(e,t,r){return Jf(t,r,mp+"."+vp(e))}(e,t,this.context)},getSearchParameters:function(e,t,r){var n=t.attribute,i=function(e){if(0===e.length)return{start:null,end:null};var t=e.split(":"),r=hl(t,2),n=r[0],i=r[1];return{start:n.length>0?parseInt(n,10):null,end:i.length>0?parseInt(i,10):null}}(gp(t,r,this.context)),a=i.start,o=i.end;return e=e.addDisjunctiveFacet(n),a&&(e=e.addNumericRefinement(n,">=",a)),o&&(e=e.addNumericRefinement(n,"<=",o)),e},getMetadata:function(e,t){var r=this,n=vp(e),i=gp(e,t,this.context),a=[],o=Uf(this.context);if(""!==i){var s=Jn(e.items,function(e){return dp(e)===i}).label;a.push({label:e.attribute+": "+s,attribute:e.attribute,currentRefinement:s,value:function(t){return yp(e,t,"",r.context)}})}return{id:n,index:o,items:a}}}),Rp=eh("NumericMenu"),_p=function(e){function t(){var e,n,i;al(this,t);for(var a=arguments.length,o=Array(a),s=0;s<a;s++)o[s]=arguments[s];return n=i=fl(this,(e=t.__proto__||Object.getPrototypeOf(t)).call.apply(e,[this].concat(o))),i.renderItem=function(e){var t=i.props,n=t.refine,a=t.translate;return r.createElement("label",{className:Rp("label")},r.createElement("input",{className:Rp("radio"),type:"radio",checked:e.isRefined,disabled:e.noRefinement,onChange:function(){return n(e.value)}}),r.createElement("span",{className:Rp("labelText")},""===e.value?a("all"):e.label))},fl(i,n)}return ul(t,e),ol(t,[{key:"render",value:function(){var e=this.props,t=e.items,n=e.canRefine,i=e.className;return r.createElement(Rh,{renderItem:this.renderItem,showMore:!1,canRefine:n,cx:Rp,items:t.map(function(e){return cl({},e,{key:e.value})}),className:i})}}]),t}(t.Component);_p.propTypes={items:L.arrayOf(L.shape({label:L.node.isRequired,value:L.string.isRequired,isRefined:L.bool.isRequired,noRefinement:L.bool.isRequired})).isRequired,canRefine:L.bool.isRequired,refine:L.func.isRequired,translate:L.func.isRequired,className:L.string},_p.defaultProps={className:""};var xp=Zf({all:"All"})(_p),wp=bp(function(e){return r.createElement(Yf,e,r.createElement(xp,e))});function Sp(e,t,r){return Wf(e,t,r,"page",1,function(e){return"string"==typeof e?parseInt(e,10):e})}var jp=Df({displayName:"AlgoliaPagination",getProvidedProps:function(e,t,r){var n=Bf(r,this.context);if(!n)return null;var i=n.nbPages;return{nbPages:i,currentRefinement:Sp(e,t,this.context),canRefine:i>1}},refine:function(e,t,r){return function(e,t,r,n){return zf(t,sl({},"page",r),n,!1)}(0,t,r,this.context)},cleanUp:function(e,t){return Jf(t,this.context,"page")},getSearchParameters:function(e,t,r){return e.setPage(Sp(t,r,this.context)-1)},getMetadata:function(){return{id:"page"}}}),Fp=Math.ceil,Pp=Math.max;var Np=function(e,t,r,n){for(var i=-1,a=Pp(Fp((t-e)/(r||1)),0),o=Array(a);a--;)o[n?a:++i]=e,e+=r;return o};var Ep=function(e){return function(t,r,n){return n&&"number"!=typeof n&&Uo(t,r,n)&&(r=n=void 0),t=Qn(t),void 0===r?(r=t,t=0):r=Qn(r),n=void 0===n?t<r?1:-1:Qn(n),Np(t,r,n,e)}}(),Op=function(e){function t(){return al(this,t),fl(this,(t.__proto__||Object.getPrototypeOf(t)).apply(this,arguments))}return ul(t,e),ol(t,[{key:"render",value:function(){var e=this.props,t=e.cx,n=e.createURL,i=e.items,a=e.onSelect,o=e.canRefine;return r.createElement("ul",{className:t("list",!o&&"list--noRefinement")},i.map(function(e){return r.createElement("li",{key:Lf(e,"key")?e.key:e.value,className:t("item",e.selected&&!e.disabled&&"item--selected",e.disabled&&"item--disabled",e.modifier)},e.disabled?r.createElement("span",{className:t("link")},Lf(e,"label")?e.label:e.value):r.createElement(_h,{className:t("link",e.selected&&"link--selected"),"aria-label":e.ariaLabel,href:n(e.value),onClick:function(){return a(e.value)}},Lf(e,"label")?e.label:e.value))}))}}]),t}(t.Component);Op.propTypes={cx:L.func.isRequired,createURL:L.func.isRequired,items:L.arrayOf(L.shape({value:L.oneOfType([L.string,L.number,L.object]).isRequired,key:L.oneOfType([L.string,L.number]),label:L.node,modifier:L.string,ariaLabel:L.string,disabled:L.bool})),onSelect:L.func.isRequired,canRefine:L.bool.isRequired};var Tp=eh("Pagination");function Ap(e,t,r){var n=function(e,t){return Math.min(2*e+1,t)}(r,t);if(n===t)return Ep(1,t+1);var i=function(e,t,r,n){return e<=t?e:e>=r-t?n-(r-e):t+1}(e,r,t,n);return Ep(e-i+1,e+(n-i)+1)}var Cp=function(e){function t(){return al(this,t),fl(this,(t.__proto__||Object.getPrototypeOf(t)).apply(this,arguments))}return ul(t,e),ol(t,[{key:"getItem",value:function(e,t,r){var n,i=this.props,a=i.nbPages,o=i.totalPages,s=i.translate;return{key:e+"."+r,modifier:e,disabled:r<1||r>=Math.min(o,a),label:s(t,r),value:r,ariaLabel:s("aria"+(n=t,0===n.length?"":""+n[0].toUpperCase()+n.slice(1)),r)}}},{key:"render",value:function(){var e=this.props,t=e.listComponent,n=e.nbPages,i=e.totalPages,a=e.currentRefinement,o=e.padding,s=e.showFirst,c=e.showPrevious,u=e.showNext,l=e.showLast,f=e.refine,h=e.createURL,p=e.canRefine,d=e.translate,m=e.className,v=ll(e,["listComponent","nbPages","totalPages","currentRefinement","padding","showFirst","showPrevious","showNext","showLast","refine","createURL","canRefine","translate","className"]),g=Math.min(n,i),y=g,b=[];return s&&b.push({key:"first",modifier:"item--firstPage",disabled:1===a,label:d("first"),value:1,ariaLabel:d("ariaFirst")}),c&&b.push({key:"previous",modifier:"item--previousPage",disabled:1===a,label:d("previous"),value:a-1,ariaLabel:d("ariaPrevious")}),b=b.concat(Ap(a,g,o).map(function(e){return{key:e,modifier:"item--page",label:d("page",e),value:e,selected:e===a,ariaLabel:d("ariaPage",e)}})),u&&b.push({key:"next",modifier:"item--nextPage",disabled:a===y||y<=1,label:d("next"),value:a+1,ariaLabel:d("ariaNext")}),l&&b.push({key:"last",modifier:"item--lastPage",disabled:a===y||y<=1,label:d("last"),value:y,ariaLabel:d("ariaLast")}),r.createElement("div",{className:Gf(Tp("",!p&&"-noRefinement"),m)},r.createElement(t,cl({},v,{cx:Tp,items:b,onSelect:f,createURL:h,canRefine:p})))}}]),t}(t.Component);Cp.propTypes={nbPages:L.number.isRequired,currentRefinement:L.number.isRequired,refine:L.func.isRequired,createURL:L.func.isRequired,canRefine:L.bool.isRequired,translate:L.func.isRequired,listComponent:L.func,showFirst:L.bool,showPrevious:L.bool,showNext:L.bool,showLast:L.bool,padding:L.number,totalPages:L.number,className:L.string},Cp.defaultProps={listComponent:Op,showFirst:!0,showPrevious:!0,showNext:!0,showLast:!1,padding:3,totalPages:1/0,className:""};var Ip=Zf({previous:"‹",next:"›",first:"«",last:"»",page:function(e){return e.toString()},ariaPrevious:"Previous page",ariaNext:"Next page",ariaFirst:"First page",ariaLast:"Last page",ariaPage:function(e){return"Page "+e.toString()}})(Cp),kp=jp(function(e){return r.createElement(Yf,e,r.createElement(Ip,e))}),qp=Df({displayName:"AlgoliaPoweredBy",propTypes:{},getProvidedProps:function(e){return{url:"https://www.algolia.com/?utm_source=react-instantsearch&utm_medium=website&utm_content="+(e.canRender?location.hostname:"")+"&utm_campaign=poweredby"}}}),Mp=eh("PoweredBy"),Hp=function(){return r.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",baseProfile:"basic",viewBox:"0 0 1366 362",width:"100",height:"27",className:Mp("logo")},r.createElement("linearGradient",{id:"g",x1:"428.258",x2:"434.145",y1:"404.15",y2:"409.85",gradientUnits:"userSpaceOnUse",gradientTransform:"matrix(94.045 0 0 -94.072 -40381.527 38479.52)"},r.createElement("stop",{offset:"0",stopColor:"#00AEFF"}),r.createElement("stop",{offset:"1",stopColor:"#3369E7"})),r.createElement("path",{d:"M61.8 15.4h242.8c23.9 0 43.4 19.4 43.4 43.4v242.9c0 23.9-19.4 43.4-43.4 43.4H61.8c-23.9 0-43.4-19.4-43.4-43.4v-243c0-23.9 19.4-43.3 43.4-43.3z",fill:"url(#g)"}),r.createElement("path",{d:"M187 98.7c-51.4 0-93.1 41.7-93.1 93.2S135.6 285 187 285s93.1-41.7 93.1-93.2-41.6-93.1-93.1-93.1zm0 158.8c-36.2 0-65.6-29.4-65.6-65.6s29.4-65.6 65.6-65.6 65.6 29.4 65.6 65.6-29.3 65.6-65.6 65.6zm0-117.8v48.9c0 1.4 1.5 2.4 2.8 1.7l43.4-22.5c1-.5 1.3-1.7.8-2.7-9-15.8-25.7-26.6-45-27.3-1 0-2 .8-2 1.9zm-60.8-35.9l-5.7-5.7c-5.6-5.6-14.6-5.6-20.2 0l-6.8 6.8c-5.6 5.6-5.6 14.6 0 20.2l5.6 5.6c.9.9 2.2.7 3-.2 3.3-4.5 6.9-8.8 10.9-12.8 4.1-4.1 8.3-7.7 12.9-11 1-.6 1.1-2 .3-2.9zM217.5 89V77.7c0-7.9-6.4-14.3-14.3-14.3h-33.3c-7.9 0-14.3 6.4-14.3 14.3v11.6c0 1.3 1.2 2.2 2.5 1.9 9.3-2.7 19.1-4.1 29-4.1 9.5 0 18.9 1.3 28 3.8 1.2.3 2.4-.6 2.4-1.9z",fill:"#FFFFFF"}),r.createElement("path",{d:"M842.5 267.6c0 26.7-6.8 46.2-20.5 58.6-13.7 12.4-34.6 18.6-62.8 18.6-10.3 0-31.7-2-48.8-5.8l6.3-31c14.3 3 33.2 3.8 43.1 3.8 15.7 0 26.9-3.2 33.6-9.6s10-15.9 10-28.5v-6.4c-3.9 1.9-9 3.8-15.3 5.8-6.3 1.9-13.6 2.9-21.8 2.9-10.8 0-20.6-1.7-29.5-5.1-8.9-3.4-16.6-8.4-22.9-15-6.3-6.6-11.3-14.9-14.8-24.8s-5.3-27.6-5.3-40.6c0-12.2 1.9-27.5 5.6-37.7 3.8-10.2 9.2-19 16.5-26.3 7.2-7.3 16-12.9 26.3-17s22.4-6.7 35.5-6.7c12.7 0 24.4 1.6 35.8 3.5 11.4 1.9 21.1 3.9 29 6.1v155.2zm-108.7-77.2c0 16.4 3.6 34.6 10.8 42.2 7.2 7.6 16.5 11.4 27.9 11.4 6.2 0 12.1-.9 17.6-2.6 5.5-1.7 9.9-3.7 13.4-6.1v-97.1c-2.8-.6-14.5-3-25.8-3.3-14.2-.4-25 5.4-32.6 14.7-7.5 9.3-11.3 25.6-11.3 40.8zm294.3 0c0 13.2-1.9 23.2-5.8 34.1s-9.4 20.2-16.5 27.9c-7.1 7.7-15.6 13.7-25.6 17.9s-25.4 6.6-33.1 6.6c-7.7-.1-23-2.3-32.9-6.6-9.9-4.3-18.4-10.2-25.5-17.9-7.1-7.7-12.6-17-16.6-27.9s-6-20.9-6-34.1c0-13.2 1.8-25.9 5.8-36.7 4-10.8 9.6-20 16.8-27.7s15.8-13.6 25.6-17.8c9.9-4.2 20.8-6.2 32.6-6.2s22.7 2.1 32.7 6.2c10 4.2 18.6 10.1 25.6 17.8 7.1 7.7 12.6 16.9 16.6 27.7 4.2 10.8 6.3 23.5 6.3 36.7zm-40 .1c0-16.9-3.7-31-10.9-40.8-7.2-9.9-17.3-14.8-30.2-14.8-12.9 0-23 4.9-30.2 14.8-7.2 9.9-10.7 23.9-10.7 40.8 0 17.1 3.6 28.6 10.8 38.5 7.2 10 17.3 14.9 30.2 14.9 12.9 0 23-5 30.2-14.9 7.2-10 10.8-21.4 10.8-38.5zm127.1 86.4c-64.1.3-64.1-51.8-64.1-60.1L1051 32l39.1-6.2v183.6c0 4.7 0 34.5 25.1 34.6v32.9zm68.9 0h-39.3V108.1l39.3-6.2v175zm-19.7-193.5c13.1 0 23.8-10.6 23.8-23.7S1177.6 36 1164.4 36s-23.8 10.6-23.8 23.7 10.7 23.7 23.8 23.7zm117.4 18.6c12.9 0 23.8 1.6 32.6 4.8 8.8 3.2 15.9 7.7 21.1 13.4s8.9 13.5 11.1 21.7c2.3 8.2 3.4 17.2 3.4 27.1v100.6c-6 1.3-15.1 2.8-27.3 4.6s-25.9 2.7-41.1 2.7c-10.1 0-19.4-1-27.7-2.9-8.4-1.9-15.5-5-21.5-9.3-5.9-4.3-10.5-9.8-13.9-16.6-3.3-6.8-5-16.4-5-26.4 0-9.6 1.9-15.7 5.6-22.3 3.8-6.6 8.9-12 15.3-16.2 6.5-4.2 13.9-7.2 22.4-9s17.4-2.7 26.6-2.7c4.3 0 8.8.3 13.6.8s9.8 1.4 15.2 2.7v-6.4c0-4.5-.5-8.8-1.6-12.8-1.1-4.1-3-7.6-5.6-10.7-2.7-3.1-6.2-5.5-10.6-7.2s-10-3-16.7-3c-9 0-17.2 1.1-24.7 2.4-7.5 1.3-13.7 2.8-18.4 4.5l-4.7-32.1c4.9-1.7 12.2-3.4 21.6-5.1s19.5-2.6 30.3-2.6zm3.3 141.9c12 0 20.9-.7 27.1-1.9v-39.8c-2.2-.6-5.3-1.3-9.4-1.9-4.1-.6-8.6-1-13.6-1-4.3 0-8.7.3-13.1 1-4.4.6-8.4 1.8-11.9 3.5s-6.4 4.1-8.5 7.2c-2.2 3.1-3.2 4.9-3.2 9.6 0 9.2 3.2 14.5 9 18 5.9 3.6 13.7 5.3 23.6 5.3zM512.9 103c12.9 0 23.8 1.6 32.6 4.8 8.8 3.2 15.9 7.7 21.1 13.4 5.3 5.8 8.9 13.5 11.1 21.7 2.3 8.2 3.4 17.2 3.4 27.1v100.6c-6 1.3-15.1 2.8-27.3 4.6-12.2 1.8-25.9 2.7-41.1 2.7-10.1 0-19.4-1-27.7-2.9-8.4-1.9-15.5-5-21.5-9.3-5.9-4.3-10.5-9.8-13.9-16.6-3.3-6.8-5-16.4-5-26.4 0-9.6 1.9-15.7 5.6-22.3 3.8-6.6 8.9-12 15.3-16.2 6.5-4.2 13.9-7.2 22.4-9s17.4-2.7 26.6-2.7c4.3 0 8.8.3 13.6.8 4.7.5 9.8 1.4 15.2 2.7v-6.4c0-4.5-.5-8.8-1.6-12.8-1.1-4.1-3-7.6-5.6-10.7-2.7-3.1-6.2-5.5-10.6-7.2-4.4-1.7-10-3-16.7-3-9 0-17.2 1.1-24.7 2.4-7.5 1.3-13.7 2.8-18.4 4.5l-4.7-32.1c4.9-1.7 12.2-3.4 21.6-5.1 9.4-1.8 19.5-2.6 30.3-2.6zm3.4 142c12 0 20.9-.7 27.1-1.9v-39.8c-2.2-.6-5.3-1.3-9.4-1.9-4.1-.6-8.6-1-13.6-1-4.3 0-8.7.3-13.1 1-4.4.6-8.4 1.8-11.9 3.5s-6.4 4.1-8.5 7.2c-2.2 3.1-3.2 4.9-3.2 9.6 0 9.2 3.2 14.5 9 18s13.7 5.3 23.6 5.3zm158.5 31.9c-64.1.3-64.1-51.8-64.1-60.1L610.6 32l39.1-6.2v183.6c0 4.7 0 34.5 25.1 34.6v32.9z",fill:"#182359"}))},Lp=function(e){function t(){return al(this,t),fl(this,(t.__proto__||Object.getPrototypeOf(t)).apply(this,arguments))}return ul(t,e),ol(t,[{key:"render",value:function(){var e=this.props,t=e.url,n=e.translate,i=e.className;return r.createElement("div",{className:Gf(Mp(""),i)},r.createElement("span",{className:Mp("text")},n("searchBy"))," ",r.createElement("a",{href:t,target:"_blank",className:Mp("link"),"aria-label":"Algolia"},r.createElement(Hp,null)))}}]),t}(t.Component);Lp.propTypes={url:L.string.isRequired,translate:L.func.isRequired,className:L.string};var Dp=qp(Zf({searchBy:"Search by"})(Lp)),Up=re.isFinite;var Bp=function(e){return"number"==typeof e&&Up(e)};function Qp(e){return e.attribute}var zp="range";function Vp(e,t,r,n){var i=Wf(e,t,n,zp+"."+Qp(e),{},function(e){var t=e.min,r=e.max;return"string"==typeof t&&(t=parseInt(t,10)),"string"==typeof r&&(r=parseInt(r,10)),{min:t,max:r}}),a=void 0!==e.min,o=void 0!==e.max,s=void 0!==i.min,c=void 0!==i.max;if(a&&s&&i.min<r.min)throw Error("You can't provide min value lower than range.");if(o&&c&&i.max>r.max)throw Error("You can't provide max value greater than range.");return a&&!s&&(i.min=r.min),o&&!c&&(i.max=r.max),i}function Wp(e,t){return{min:void 0!==e.min?e.min:t.min,max:void 0!==e.max?e.max:t.max}}function Jp(e,t,r,n){return e||r!==n?e&&t?r:n:void 0}function $p(e,t,r,n,i){var a=r.min,o=r.max,s=n.min,c=n.max,u=void 0===a||""===a,l=void 0===o||""===o,f=u?void 0:parseFloat(a),h=l?void 0:parseFloat(o),p=u||Bp(f),d=l||Bp(h);if(!p||!d)throw Error("You can't provide non finite values to the range connector.");if(f<s)throw Error("You can't provide min value lower than range.");if(h>c)throw Error("You can't provide max value greater than range.");var m=Qp(e);return zf(t,sl({},m,{min:Jp(void 0!==e.min,u,s,f),max:Jp(void 0!==e.max,l,c,h)}),i,!0,zp)}var Kp=Df({displayName:"AlgoliaRange",propTypes:{id:L.string,attribute:L.string.isRequired,defaultRefinement:L.shape({min:L.number,max:L.number}),min:L.number,max:L.number,precision:L.number,header:L.node,footer:L.node},defaultProps:{precision:0},getProvidedProps:function(e,t,r){var n=e.attribute,i=e.precision,a=e.min,o=e.max,s=Bf(r,this.context),c=s&&s.getFacetByName(n),u=c&&s.getFacetStats(n)||{},l=(c?s.getFacetValues(n):[]).map(function(e){return{value:e.name,count:e.count}}),f=function(e,t,r){var n=Math.pow(10,r),i=void 0;i=Bp(e.min)?e.min:Bp(t.min)?t.min:void 0;var a=void 0;return a=Bp(e.max)?e.max:Bp(t.max)?t.max:void 0,{min:void 0!==i?Math.floor(i*n)/n:i,max:void 0!==a?Math.ceil(a*n)/n:a}}({min:a,max:o},u,i),h=f.min,p=f.max;this._currentRange={min:h,max:p};var d=Vp(e,t,this._currentRange,this.context);return{min:h,max:p,canRefine:l.length>0,currentRefinement:Wp(d,this._currentRange),count:l,precision:i}},refine:function(e,t,r){return $p(e,t,r,this._currentRange,this.context)},cleanUp:function(e,t){return function(e,t,r){return Jf(t,r,zp+"."+Qp(e))}(e,t,this.context)},getSearchParameters:function(e,t,r){var n=t.attribute,i=Vp(t,r,this._currentRange,this.context),a=i.min,o=i.max;return e=e.addDisjunctiveFacet(n),void 0!==a&&(e=e.addNumericRefinement(n,">=",a)),void 0!==o&&(e=e.addNumericRefinement(n,"<=",o)),e},getMetadata:function(e,t){var r=this,n=this._currentRange,i=n.min,a=n.max,o=Vp(e,t,this._currentRange,this.context),s=o.min,c=o.max,u=[],l=void 0!==s,f=void 0!==c;if(l&&s!==i||f&&c!==a){var h=[l?s+" <= ":"",e.attribute,f?" <= "+c:""];u.push({label:h.join(""),attribute:e.attribute,value:function(t){return $p(e,t,{},r._currentRange,r.context)},currentRefinement:Wp({min:s,max:c},{min:i,max:a})})}return{id:Qp(e),index:Uf(this.context),items:u}}}),Yp=eh("RangeInput"),Gp=function(e){function t(e){al(this,t);var r=fl(this,(t.__proto__||Object.getPrototypeOf(t)).call(this,e));return r.onSubmit=function(e){e.preventDefault(),r.props.refine({min:r.state.from,max:r.state.to})},r.state=r.normalizeStateForRendering(e),r}return ul(t,e),ol(t,[{key:"componentWillReceiveProps",value:function(e){!e.canRefine||this.props.canRefine===e.canRefine&&this.props.currentRefinement.min===e.currentRefinement.min&&this.props.currentRefinement.max===e.currentRefinement.max||this.setState(this.normalizeStateForRendering(e))}},{key:"normalizeStateForRendering",value:function(e){var t=e.canRefine,r=e.min,n=e.max,i=e.currentRefinement,a=i.min,o=i.max;return{from:t&&void 0!==a&&a!==r?a:"",to:t&&void 0!==o&&o!==n?o:""}}},{key:"normalizeRangeForRendering",value:function(e){var t=e.canRefine,r=e.min,n=e.max,i=void 0!==r,a=void 0!==n;return{min:t&&i&&a?r:"",max:t&&i&&a?n:""}}},{key:"render",value:function(){var e=this,t=this.state,n=t.from,i=t.to,a=this.props,o=a.precision,s=a.translate,c=a.canRefine,u=a.className,l=this.normalizeRangeForRendering(this.props),f=l.min,h=l.max,p=1/Math.pow(10,o);return r.createElement("div",{className:Gf(Yp("",!c&&"-noRefinement"),u)},r.createElement("form",{className:Yp("form"),onSubmit:this.onSubmit},r.createElement("input",{className:Yp("input","input--min"),type:"number",min:f,max:h,value:n,step:p,placeholder:f,disabled:!c,onChange:function(t){return e.setState({from:t.currentTarget.value})}}),r.createElement("span",{className:Yp("separator")},s("separator")),r.createElement("input",{className:Yp("input","input--max"),type:"number",min:f,max:h,value:i,step:p,placeholder:h,disabled:!c,onChange:function(t){return e.setState({to:t.currentTarget.value})}}),r.createElement("button",{className:Yp("submit"),type:"submit"},s("submit"))))}}]),t}(t.Component);Gp.propTypes={canRefine:L.bool.isRequired,precision:L.number.isRequired,translate:L.func.isRequired,refine:L.func.isRequired,min:L.number,max:L.number,currentRefinement:L.shape({min:L.number,max:L.number}),className:L.string},Gp.defaultProps={currentRefinement:{},className:""};var Xp=Zf({submit:"ok",separator:"to"})(Gp),Zp=Kp(function(e){return r.createElement(Yf,e,r.createElement(Xp,e))}),ed=4294967295;var td=function(e){return e?Lc(zn(e),0,ed):0};var rd=function(e,t,r,n){var i=e.length;for((r=zn(r))<0&&(r=-r>i?0:i+r),(n=void 0===n||n>i?i:zn(n))<0&&(n+=i),n=r>n?0:td(n);r<n;)e[r++]=t;return e};var nd=function(e,t,r,n){var i=null==e?0:e.length;return i?(r&&"number"!=typeof r&&Uo(e,t,r)&&(r=0,n=i),rd(e,t,r,n)):[]},id=eh("RatingMenu"),ad=function(e){function t(){return al(this,t),fl(this,(t.__proto__||Object.getPrototypeOf(t)).apply(this,arguments))}return ul(t,e),ol(t,[{key:"onClick",value:function(e,t,r){r.preventDefault(),r.stopPropagation(),e===this.props.currentRefinement.min&&t===this.props.currentRefinement.max?this.props.refine({min:this.props.min,max:this.props.max}):this.props.refine({min:e,max:t})}},{key:"buildItem",value:function(e){for(var t=e.max,n=e.lowerBound,i=e.count,a=e.translate,o=e.createURL,s=e.isLastSelectableItem,c=!i,u=this.props.currentRefinement.min<n,l=s&&u||!c&&n===this.props.currentRefinement.min&&t===this.props.currentRefinement.max,f=[],h=0,p=0;p<t;p++)p<n&&h++,f.push([r.createElement("svg",{key:p,className:id("starIcon",p>=n?"starIcon--empty":"starIcon--full"),"aria-hidden":"true",width:"24",height:"24"},r.createElement("use",{xlinkHref:"#"+id(p>=n?"starEmptySymbol":"starSymbol")}))," "]);var d=c||s&&l?{}:{href:o({min:n,max:t}),onClick:this.onClick.bind(this,n,t)};return r.createElement("li",{key:n,className:id("item",l&&"item--selected",c&&"item--disabled")},r.createElement("a",cl({className:id("link"),"aria-label":""+h+a("ratingLabel")},d),f,r.createElement("span",{className:id("label"),"aria-hidden":"true"},a("ratingLabel"))," ",r.createElement("span",{className:id("count")},i)))}},{key:"render",value:function(){var e=this,t=this.props,n=t.min,i=t.max,a=t.translate,o=t.count,s=t.createURL,c=t.canRefine,u=t.className,l=void 0!==n&&n>=0?n:1,f=void 0!==i&&i>=0?i:0,h=f-l+1,p=Math.max(h,0),d=o.map(function(e){return cl({},e,{value:parseFloat(e.value)})}).filter(function(e){return e.value>=l&&e.value<=f}),m=nd(new Array(p),null).map(function(e,t){return Jn(d,function(e){return e.value===f-t})||{value:f-t,count:0,total:0}}).reduce(function(e,t,r){return e.concat(cl({},t,{total:0===r?t.count:e[r-1].total+t.count}))},[]),v=m.map(function(t,r){return e.buildItem({lowerBound:t.value,count:t.total,isLastSelectableItem:m.length-1===r,max:f,translate:a,createURL:s})});return r.createElement("div",{className:Gf(id("",!c&&"-noRefinement"),u)},r.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",style:{display:"none"}},r.createElement("symbol",{id:id("starSymbol"),viewBox:"0 0 24 24"},r.createElement("path",{d:"M12 .288l2.833 8.718h9.167l-7.417 5.389 2.833 8.718-7.416-5.388-7.417 5.388 2.833-8.718-7.416-5.389h9.167z"})),r.createElement("symbol",{id:id("starEmptySymbol"),viewBox:"0 0 24 24"},r.createElement("path",{d:"M12 6.76l1.379 4.246h4.465l-3.612 2.625 1.379 4.246-3.611-2.625-3.612 2.625 1.379-4.246-3.612-2.625h4.465l1.38-4.246zm0-6.472l-2.833 8.718h-9.167l7.416 5.389-2.833 8.718 7.417-5.388 7.416 5.388-2.833-8.718 7.417-5.389h-9.167l-2.833-8.718z"}))),r.createElement("ul",{className:id("list",!c&&"list--noRefinement")},v))}}]),t}(t.Component);ad.propTypes={translate:L.func.isRequired,refine:L.func.isRequired,createURL:L.func.isRequired,min:L.number,max:L.number,currentRefinement:L.shape({min:L.number,max:L.number}),count:L.arrayOf(L.shape({value:L.string,count:L.number})),canRefine:L.bool.isRequired,className:L.string},ad.defaultProps={className:""};var od=Zf({ratingLabel:" & Up"})(ad),sd=Kp(function(e){return r.createElement(Yf,e,r.createElement(od,e))}),cd="refinementList";function ud(e){return e.attribute}function ld(e,t,r){return Wf(e,t,r,cd+"."+ud(e),[],function(e){return"string"==typeof e?""===e?[]:[e]:e})}function fd(e,t,r,n){var i=ld(t,r,n);return-1===i.indexOf(e)?i.concat([e]):i.filter(function(t){return t!==e})}function hd(e){var t=e.showMore,r=e.limit,n=e.showMoreLimit;return t?n:r}function pd(e,t,r,n){var i=ud(e);return zf(t,sl({},i,r.length>0?r:""),n,!0,cd)}var dd=["isRefined","count:desc","name:asc"],md=Df({displayName:"AlgoliaRefinementList",propTypes:{id:L.string,attribute:L.string.isRequired,operator:L.oneOf(["and","or"]),showMore:L.bool,limit:L.number,showMoreLimit:L.number,defaultRefinement:L.arrayOf(L.oneOfType([L.string,L.number])),searchable:L.bool,transformItems:L.func},defaultProps:{operator:"or",showMore:!1,limit:10,showMoreLimit:20},getProvidedProps:function(e,t,r,n,i){var a=this,o=e.attribute,s=e.searchable,c=Bf(r,this.context),u=Boolean(c)&&Boolean(c.getFacetByName(o)),l=Boolean(i&&i[o]&&""!==i.query);if(s&&this.context.multiIndexContext)throw new Error("react-instantsearch: searching in *List is not available when used inside a multi index context");if(!u)return{items:[],currentRefinement:ld(e,t,this.context),canRefine:u,isFromSearch:l,searchable:s};var f=l?i[o].map(function(r){return{label:r.value,value:fd(r.value,e,t,a.context),_highlightResult:{label:{value:r.highlighted}},count:r.count,isRefined:r.isRefined}}):c.getFacetValues(o,{sortBy:dd}).map(function(r){return{label:r.name,value:fd(r.name,e,t,a.context),count:r.count,isRefined:r.isRefined}});return{items:(e.transformItems?e.transformItems(f):f).slice(0,hd(e)),currentRefinement:ld(e,t,this.context),isFromSearch:l,searchable:s,canRefine:f.length>0}},refine:function(e,t,r){return pd(e,t,r,this.context)},searchForFacetValues:function(e,t,r){return{facetName:e.attribute,query:r,maxFacetHits:hd(e)}},cleanUp:function(e,t){return function(e,t,r){return Jf(t,r,cd+"."+ud(e))}(e,t,this.context)},getSearchParameters:function(e,t,r){var n=t.attribute,i="and"===t.operator?"addFacet":"addDisjunctiveFacet",a=i+"Refinement";return e=(e=e.setQueryParameters({maxValuesPerFacet:Math.max(e.maxValuesPerFacet||0,hd(t))}))[i](n),ld(t,r,this.context).reduce(function(e,t){return e[a](n,t)},e)},getMetadata:function(e,t){var r=ud(e),n=this.context;return{id:r,index:Uf(this.context),items:ld(e,t,n).length>0?[{attribute:e.attribute,label:e.attribute+": ",currentRefinement:ld(e,t,n),value:function(t){return pd(e,t,[],n)},items:ld(e,t,n).map(function(r){return{label:""+r,value:function(i){var a=ld(e,i,n).filter(function(e){return e!==r});return pd(e,t,a,n)}}})}]:[]}}}),vd=eh("RefinementList"),gd=function(e){function t(){var e,n,i;al(this,t);for(var a=arguments.length,o=Array(a),s=0;s<a;s++)o[s]=arguments[s];return n=i=fl(this,(e=t.__proto__||Object.getPrototypeOf(t)).call.apply(e,[this].concat(o))),i.state={query:""},i.selectItem=function(e,t){t(),i.props.refine(e.value)},i.renderItem=function(e,t){var n=i.props.isFromSearch?r.createElement(Ih,{attribute:"label",hit:e}):e.label;return r.createElement("label",{className:vd("label")},r.createElement("input",{className:vd("checkbox"),type:"checkbox",checked:e.isRefined,onChange:function(){return i.selectItem(e,t)}}),r.createElement("span",{className:vd("labelText")},n)," ",r.createElement("span",{className:vd("count")},e.count.toLocaleString()))},fl(i,n)}return ul(t,e),ol(t,[{key:"render",value:function(){return r.createElement(Rh,cl({renderItem:this.renderItem,selectItem:this.selectItem,cx:vd},ku(this.props,["translate","items","showMore","limit","showMoreLimit","isFromSearch","searchForItems","searchable","canRefine","className"]),{query:this.state.query}))}}]),t}(t.Component);gd.propTypes={translate:L.func.isRequired,refine:L.func.isRequired,searchForItems:L.func.isRequired,searchable:L.bool,createURL:L.func.isRequired,items:L.arrayOf(L.shape({label:L.string.isRequired,value:L.arrayOf(L.string).isRequired,count:L.number.isRequired,isRefined:L.bool.isRequired})),isFromSearch:L.bool.isRequired,canRefine:L.bool.isRequired,showMore:L.bool,limit:L.number,showMoreLimit:L.number,transformItems:L.func,className:L.string},gd.defaultProps={className:""};var yd=Zf({showMore:function(e){return e?"Show less":"Show more"},noResults:"No results",submit:null,reset:null,resetTitle:"Clear the search query.",submitTitle:"Submit your search query.",placeholder:"Search here…"})(gd),bd=md(function(e){return r.createElement(Yf,e,r.createElement(yd,e))}),Rd=eh("ClearRefinements"),_d=function(e){function t(){return al(this,t),fl(this,(t.__proto__||Object.getPrototypeOf(t)).apply(this,arguments))}return ul(t,e),ol(t,[{key:"render",value:function(){var e=this.props,t=e.items,n=e.canRefine,i=e.refine,a=e.translate,o=e.className;return r.createElement("div",{className:Gf(Rd(""),o)},r.createElement("button",{className:Rd("button",!n&&"button--disabled"),onClick:function(){return i(t)},disabled:!n},a("reset")))}}]),t}(t.Component);_d.propTypes={items:L.arrayOf(L.object).isRequired,canRefine:L.bool.isRequired,refine:L.func.isRequired,translate:L.func.isRequired,className:L.string},_d.defaultProps={className:""};var xd=Zf({reset:"Clear all filters"})(_d),wd=Kf(function(e){return r.createElement(Yf,e,r.createElement(xd,e))}),Sd=Df({displayName:"AlgoliaScrollTo",propTypes:{scrollOn:L.string},defaultProps:{scrollOn:"page"},getProvidedProps:function(e,t){var r=e.scrollOn,n=Wf(e,t,this.context,r,null,function(e){return e});if(this._prevSearchState||(this._prevSearchState={}),Qf(this.context)){var i=Uf(this.context);t=t.indices?t.indices[i]:{}}var a=Da(Da(t,"configure"),r),o=Zu(this._prevSearchState,a);return this._prevSearchState=a,{value:n,hasNotChanged:o}}}),jd=eh("ScrollTo"),Fd=function(e){function t(){return al(this,t),fl(this,(t.__proto__||Object.getPrototypeOf(t)).apply(this,arguments))}return ul(t,e),ol(t,[{key:"componentDidUpdate",value:function(e){var t=this.props,r=t.value,n=t.hasNotChanged;r!==e.value&&n&&this.el.scrollIntoView()}},{key:"render",value:function(){var e=this;return r.createElement("div",{ref:function(t){return e.el=t},className:jd("")},this.props.children)}}]),t}(t.Component);Fd.propTypes={value:L.any,children:L.node,hasNotChanged:L.bool};var Pd=Sd(Fd);function Nd(e,t,r){return Wf(e,t,r,"query","",function(e){return e||""})}function Ed(e,t,r,n){return zf(t,sl({},"query",r),n,!0)}var Od=Df({displayName:"AlgoliaSearchBox",propTypes:{defaultRefinement:L.string},getProvidedProps:function(e,t,r){return{currentRefinement:Nd(e,t,this.context),isSearchStalled:r.isSearchStalled}},refine:function(e,t,r){return Ed(0,t,r,this.context)},cleanUp:function(e,t){return function(e,t,r){return Jf(t,r,"query")}(0,t,this.context)},getSearchParameters:function(e,t,r){return e.setQuery(Nd(t,r,this.context))},getMetadata:function(e,t){var r=this,n=Nd(e,t,this.context);return{id:"query",index:Uf(this.context),items:null===n?[]:[{label:"query: "+n,value:function(e){return Ed(0,e,"",r.context)},currentRefinement:n}]}}})(yh);function Td(e,t,r){return Wf(e,t,r,"sortBy",null,function(e){return e||null})}var Ad=Df({displayName:"AlgoliaSortBy",propTypes:{defaultRefinement:L.string,items:L.arrayOf(L.shape({label:L.string,value:L.string.isRequired})).isRequired,transformItems:L.func},getProvidedProps:function(e,t){var r=Td(e,t,this.context),n=e.items.map(function(e){return e.value===r?cl({},e,{isRefined:!0}):cl({},e,{isRefined:!1})});return{items:e.transformItems?e.transformItems(n):n,currentRefinement:r}},refine:function(e,t,r){return zf(t,sl({},"sortBy",r),this.context,!0)},cleanUp:function(e,t){return Jf(t,this.context,"sortBy")},getSearchParameters:function(e,t,r){var n=Td(t,r,this.context);return e.setIndex(n)},getMetadata:function(){return{id:"sortBy"}}}),Cd=eh("SortBy"),Id=function(e){function t(){return al(this,t),fl(this,(t.__proto__||Object.getPrototypeOf(t)).apply(this,arguments))}return ul(t,e),ol(t,[{key:"render",value:function(){var e=this.props,t=e.items,n=e.currentRefinement,i=e.refine,a=e.className;return r.createElement("div",{className:Gf(Cd(""),a)},r.createElement(Qh,{cx:Cd,items:t,selectedItem:n,onSelect:i}))}}]),t}(t.Component);Id.propTypes={items:L.arrayOf(L.shape({label:L.string,value:L.string.isRequired})).isRequired,currentRefinement:L.string.isRequired,refine:L.func.isRequired,className:L.string},Id.defaultProps={className:""};var kd=Ad(Id),qd=Df({displayName:"AlgoliaStats",getProvidedProps:function(e,t,r){var n=Bf(r,this.context);return n?{nbHits:n.nbHits,processingTimeMS:n.processingTimeMS}:null}}),Md=eh("Stats"),Hd=function(e){function t(){return al(this,t),fl(this,(t.__proto__||Object.getPrototypeOf(t)).apply(this,arguments))}return ul(t,e),ol(t,[{key:"render",value:function(){var e=this.props,t=e.translate,n=e.nbHits,i=e.processingTimeMS,a=e.className;return r.createElement("div",{className:Gf(Md(""),a)},r.createElement("span",{className:Md("text")},t("stats",n,i)))}}]),t}(t.Component);Hd.propTypes={translate:L.func.isRequired,nbHits:L.number.isRequired,processingTimeMS:L.number.isRequired,className:L.string},Hd.defaultProps={className:""};var Ld=qd(Zf({stats:function(e,t){return e.toLocaleString()+" results found in "+t.toLocaleString()+"ms"}})(Hd));function Dd(e){return e.attribute}var Ud="toggle";function Bd(e,t,r){return Wf(e,t,r,Ud+"."+Dd(e),!1,function(e){return e||!1})}function Qd(e,t,r,n){var i=Dd(e);return zf(t,sl({},i,r||!1),n,!0,Ud)}var zd=Df({displayName:"AlgoliaToggle",propTypes:{label:L.string,filter:L.func,attribute:L.string,value:L.any,defaultRefinement:L.bool},getProvidedProps:function(e,t){return{currentRefinement:Bd(e,t,this.context)}},refine:function(e,t,r){return Qd(e,t,r,this.context)},cleanUp:function(e,t){return function(e,t,r){return Jf(t,r,Ud+"."+Dd(e))}(e,t,this.context)},getSearchParameters:function(e,t,r){var n=t.attribute,i=t.value,a=t.filter;return Bd(t,r,this.context)&&(n&&(e=e.addFacet(n).addFacetRefinement(n,i)),a&&(e=a(e))),e},getMetadata:function(e,t){var r=this,n=Dd(e),i=Bd(e,t,this.context),a=[],o=Uf(this.context);return i&&a.push({label:e.label,currentRefinement:i,attribute:e.attribute,value:function(t){return Qd(e,t,!1,r.context)}}),{id:n,index:o,items:a}}}),Vd=eh("ToggleRefinement"),Wd=function(e){var t=e.currentRefinement,n=e.label,i=e.refine,a=e.className;return r.createElement("div",{className:Gf(Vd(""),a)},r.createElement("label",{className:Vd("label")},r.createElement("input",{className:Vd("checkbox"),type:"checkbox",checked:t,onChange:function(e){return i(e.target.checked)}}),r.createElement("span",{className:Vd("labelText")},n)))};Wd.propTypes={currentRefinement:L.bool.isRequired,label:L.string.isRequired,refine:L.func.isRequired,className:L.string},Wd.defaultProps={className:""};var Jd=zd(Wd),$d=eh("Panel"),Kd=function(e){function t(){var e,r,n;al(this,t);for(var i=arguments.length,a=Array(i),o=0;o<i;o++)a[o]=arguments[o];return r=n=fl(this,(e=t.__proto__||Object.getPrototypeOf(t)).call.apply(e,[this].concat(a))),n.state={canRefine:!0},n.setCanRefine=function(e){n.setState({canRefine:e})},fl(n,r)}return ul(t,e),ol(t,[{key:"getChildContext",value:function(){return{setCanRefine:this.setCanRefine}}},{key:"render",value:function(){var e=this.props,t=e.children,n=e.className,i=e.header,a=e.footer,o=this.state.canRefine;return r.createElement("div",{className:Gf($d("",!o&&"-noRefinement"),n)},i&&r.createElement("div",{className:$d("header")},i),r.createElement("div",{className:$d("body")},t),a&&r.createElement("div",{className:$d("footer")},a))}}]),t}(t.Component);Kd.propTypes={children:L.node.isRequired,className:L.string,header:L.node,footer:L.node},Kd.childContextTypes={setCanRefine:L.func.isRequired},Kd.defaultProps={className:"",header:null,footer:null};var Yd=function(e){return e.attributes[0]},Gd="hierarchicalMenu";var Xd=Df({displayName:"AlgoliaBreadcrumb",propTypes:{attributes:function(e,t,r){if(!Array.isArray(e[t])||e[t].some(function(e){return"string"!=typeof e})||e[t].length<1)return new Error("Invalid prop "+t+" supplied to "+r+". Expected an Array of Strings")},transformItems:L.func},getProvidedProps:function(e,t,r){var n=Yd(e),i=Bf(r,this.context);if(!(Boolean(i)&&Boolean(i.getFacetByName(n))))return{items:[],canRefine:!1};var a=i.getFacetValues(n),o=a.data?function e(t){return t.reduce(function(t,r){return r.isRefined&&(t.push({label:r.name,value:r.path}),r.data&&(t=t.concat(e(r.data)))),t},[])}(a.data):[],s=e.transformItems?e.transformItems(o):o;return{canRefine:s.length>0,items:s}},refine:function(e,t,r){return function(e,t,r,n){var i=Yd(e);return zf(t,sl({},i,r||""),n,!0,Gd)}(e,t,r,this.context)}}),Zd=eh("Breadcrumb"),em=L.arrayOf(L.shape({label:L.string.isRequired,value:L.string.isRequired})),tm=function(e){function t(){return al(this,t),fl(this,(t.__proto__||Object.getPrototypeOf(t)).apply(this,arguments))}return ul(t,e),ol(t,[{key:"render",value:function(){var e=this.props,t=e.canRefine,n=e.createURL,i=e.items,a=e.refine,o=e.rootURL,s=e.separator,c=e.translate,u=e.className,l=t?r.createElement("li",{className:Zd("item")},r.createElement(_h,{className:Zd("link"),onClick:function(){return o?null:a()},href:o||n()},c("rootLabel"))):null,f=i.map(function(e,t){var o=t===i.length-1;return r.createElement("li",{className:Zd("item",o&&"item--selected"),key:t},r.createElement("span",{className:Zd("separator")},s),o?e.label:r.createElement(_h,{className:Zd("link"),onClick:function(){return a(e.value)},href:n(e.value)},e.label))});return r.createElement("div",{className:Gf(Zd("",!t&&"-noRefinement"),u)},r.createElement("ul",{className:Zd("list")},l,f))}}]),t}(t.Component);tm.propTypes={canRefine:L.bool.isRequired,createURL:L.func.isRequired,items:em,refine:L.func.isRequired,rootURL:L.string,separator:L.node,translate:L.func.isRequired,className:L.string},tm.defaultProps={rootURL:null,separator:" > ",className:""};var rm,nm,im=Zf({rootLabel:"Home"})(tm),am=Xd(function(e){return r.createElement(Yf,e,r.createElement(im,e))}),om=function(e,n){var i,a;return a=i=function(t){function n(){var t;al(this,n);for(var r=arguments.length,i=Array(r),a=0;a<r;a++)i[a]=arguments[a];var o=fl(this,(t=n.__proto__||Object.getPrototypeOf(n)).call.apply(t,[this].concat(i)));return o.client=o.props.algoliaClient||e(o.props.appId,o.props.apiKey),o.client.addAlgoliaAgent("react-instantsearch "+vl),o}return ul(n,t),ol(n,[{key:"componentWillReceiveProps",value:function(t){var r=this.props;t.algoliaClient?this.client=t.algoliaClient:r.appId===t.appId&&r.apiKey===t.apiKey||(this.client=e(t.appId,t.apiKey)),this.client.addAlgoliaAgent("react-instantsearch "+vl)}},{key:"render",value:function(){return r.createElement(ml,{createURL:this.props.createURL,indexName:this.props.indexName,searchState:this.props.searchState,onSearchStateChange:this.props.onSearchStateChange,onSearchParameters:this.props.onSearchParameters,root:this.props.root,algoliaClient:this.client,refresh:this.props.refresh,resultsState:this.props.resultsState},this.props.children)}}]),n}(t.Component),i.propTypes={algoliaClient:L.object,appId:L.string,apiKey:L.string,children:L.oneOfType([L.arrayOf(L.node),L.node]),indexName:L.string.isRequired,createURL:L.func,searchState:L.object,refresh:L.bool.isRequired,onSearchStateChange:L.func,onSearchParameters:L.func,resultsState:L.oneOfType([L.object,L.array]),root:L.shape({Root:L.oneOfType([L.string,L.func]).isRequired,props:L.object})},i.defaultProps={refresh:!1,root:n},a}(Cf,{Root:"div",props:{className:"ais-InstantSearch__root"}}),sm=(rm={Root:"div",props:{className:"ais-MultiIndex__root"}},(nm=function(e){var t=e.indexName,n=e.root,i=e.children;return r.createElement(gl,{indexName:t,root:n},i)}).propTypes={indexName:L.string.isRequired,root:L.shape({Root:L.oneOfType([L.string,L.func]).isRequired,props:L.object}),children:L.node},nm.defaultProps={root:rm},nm);e.InstantSearch=om,e.Index=sm,e.Configure=$f,e.CurrentRefinements=ah,e.HierarchicalMenu=Fh,e.Highlight=Ih,e.Snippet=qh,e.Hits=Dh,e.HitsPerPage=Wh,e.InfiniteHits=Gh,e.Menu=up,e.MenuSelect=pp,e.NumericMenu=wp,e.Pagination=kp,e.PoweredBy=Dp,e.RangeInput=Zp,e.RangeSlider=function(){return r.createElement("div",null,"We do not provide any Slider, see the documentation to learn how to connect one easily:",r.createElement("a",{target:"_blank",rel:"noopener noreferrer",href:"https://community.algolia.com/react-instantsearch/widgets/RangeSlider.html"},"https://community.algolia.com/react-instantsearch/widgets/RangeSlider.html"))},e.RatingMenu=sd,e.RefinementList=bd,e.ClearRefinements=wd,e.ScrollTo=Pd,e.SearchBox=Od,e.SortBy=kd,e.Stats=Ld,e.ToggleRefinement=Jd,e.Panel=Kd,e.Breadcrumb=am,Object.defineProperty(e,"__esModule",{value:!0})}); //# sourceMappingURL=Dom.min.js.map
tools/jruby-1.7.11/lib/ruby/1.9/rdoc/generator/template/darkfish/js/jquery.js
savaki/gocd
/*! * jQuery JavaScript Library v1.6.2 * http://jquery.com/ * * Copyright 2011, John Resig * Dual licensed under the MIT or GPL Version 2 licenses. * http://jquery.org/license * * Includes Sizzle.js * http://sizzlejs.com/ * Copyright 2011, The Dojo Foundation * Released under the MIT, BSD, and GPL Licenses. * * Date: Thu Jun 30 14:16:56 2011 -0400 */ (function(a,b){function cv(a){return f.isWindow(a)?a:a.nodeType===9?a.defaultView||a.parentWindow:!1}function cs(a){if(!cg[a]){var b=c.body,d=f("<"+a+">").appendTo(b),e=d.css("display");d.remove();if(e==="none"||e===""){ch||(ch=c.createElement("iframe"),ch.frameBorder=ch.width=ch.height=0),b.appendChild(ch);if(!ci||!ch.createElement)ci=(ch.contentWindow||ch.contentDocument).document,ci.write((c.compatMode==="CSS1Compat"?"<!doctype html>":"")+"<html><body>"),ci.close();d=ci.createElement(a),ci.body.appendChild(d),e=f.css(d,"display"),b.removeChild(ch)}cg[a]=e}return cg[a]}function cr(a,b){var c={};f.each(cm.concat.apply([],cm.slice(0,b)),function(){c[this]=a});return c}function cq(){cn=b}function cp(){setTimeout(cq,0);return cn=f.now()}function cf(){try{return new a.ActiveXObject("Microsoft.XMLHTTP")}catch(b){}}function ce(){try{return new a.XMLHttpRequest}catch(b){}}function b$(a,c){a.dataFilter&&(c=a.dataFilter(c,a.dataType));var d=a.dataTypes,e={},g,h,i=d.length,j,k=d[0],l,m,n,o,p;for(g=1;g<i;g++){if(g===1)for(h in a.converters)typeof h=="string"&&(e[h.toLowerCase()]=a.converters[h]);l=k,k=d[g];if(k==="*")k=l;else if(l!=="*"&&l!==k){m=l+" "+k,n=e[m]||e["* "+k];if(!n){p=b;for(o in e){j=o.split(" ");if(j[0]===l||j[0]==="*"){p=e[j[1]+" "+k];if(p){o=e[o],o===!0?n=p:p===!0&&(n=o);break}}}}!n&&!p&&f.error("No conversion from "+m.replace(" "," to ")),n!==!0&&(c=n?n(c):p(o(c)))}}return c}function bZ(a,c,d){var e=a.contents,f=a.dataTypes,g=a.responseFields,h,i,j,k;for(i in g)i in d&&(c[g[i]]=d[i]);while(f[0]==="*")f.shift(),h===b&&(h=a.mimeType||c.getResponseHeader("content-type"));if(h)for(i in e)if(e[i]&&e[i].test(h)){f.unshift(i);break}if(f[0]in d)j=f[0];else{for(i in d){if(!f[0]||a.converters[i+" "+f[0]]){j=i;break}k||(k=i)}j=j||k}if(j){j!==f[0]&&f.unshift(j);return d[j]}}function bY(a,b,c,d){if(f.isArray(b))f.each(b,function(b,e){c||bC.test(a)?d(a,e):bY(a+"["+(typeof e=="object"||f.isArray(e)?b:"")+"]",e,c,d)});else if(!c&&b!=null&&typeof b=="object")for(var e in b)bY(a+"["+e+"]",b[e],c,d);else d(a,b)}function bX(a,c,d,e,f,g){f=f||c.dataTypes[0],g=g||{},g[f]=!0;var h=a[f],i=0,j=h?h.length:0,k=a===bR,l;for(;i<j&&(k||!l);i++)l=h[i](c,d,e),typeof l=="string"&&(!k||g[l]?l=b:(c.dataTypes.unshift(l),l=bX(a,c,d,e,l,g)));(k||!l)&&!g["*"]&&(l=bX(a,c,d,e,"*",g));return l}function bW(a){return function(b,c){typeof b!="string"&&(c=b,b="*");if(f.isFunction(c)){var d=b.toLowerCase().split(bN),e=0,g=d.length,h,i,j;for(;e<g;e++)h=d[e],j=/^\+/.test(h),j&&(h=h.substr(1)||"*"),i=a[h]=a[h]||[],i[j?"unshift":"push"](c)}}}function bA(a,b,c){var d=b==="width"?a.offsetWidth:a.offsetHeight,e=b==="width"?bv:bw;if(d>0){c!=="border"&&f.each(e,function(){c||(d-=parseFloat(f.css(a,"padding"+this))||0),c==="margin"?d+=parseFloat(f.css(a,c+this))||0:d-=parseFloat(f.css(a,"border"+this+"Width"))||0});return d+"px"}d=bx(a,b,b);if(d<0||d==null)d=a.style[b]||0;d=parseFloat(d)||0,c&&f.each(e,function(){d+=parseFloat(f.css(a,"padding"+this))||0,c!=="padding"&&(d+=parseFloat(f.css(a,"border"+this+"Width"))||0),c==="margin"&&(d+=parseFloat(f.css(a,c+this))||0)});return d+"px"}function bm(a,b){b.src?f.ajax({url:b.src,async:!1,dataType:"script"}):f.globalEval((b.text||b.textContent||b.innerHTML||"").replace(be,"/*$0*/")),b.parentNode&&b.parentNode.removeChild(b)}function bl(a){f.nodeName(a,"input")?bk(a):"getElementsByTagName"in a&&f.grep(a.getElementsByTagName("input"),bk)}function bk(a){if(a.type==="checkbox"||a.type==="radio")a.defaultChecked=a.checked}function bj(a){return"getElementsByTagName"in a?a.getElementsByTagName("*"):"querySelectorAll"in a?a.querySelectorAll("*"):[]}function bi(a,b){var c;if(b.nodeType===1){b.clearAttributes&&b.clearAttributes(),b.mergeAttributes&&b.mergeAttributes(a),c=b.nodeName.toLowerCase();if(c==="object")b.outerHTML=a.outerHTML;else if(c!=="input"||a.type!=="checkbox"&&a.type!=="radio"){if(c==="option")b.selected=a.defaultSelected;else if(c==="input"||c==="textarea")b.defaultValue=a.defaultValue}else a.checked&&(b.defaultChecked=b.checked=a.checked),b.value!==a.value&&(b.value=a.value);b.removeAttribute(f.expando)}}function bh(a,b){if(b.nodeType===1&&!!f.hasData(a)){var c=f.expando,d=f.data(a),e=f.data(b,d);if(d=d[c]){var g=d.events;e=e[c]=f.extend({},d);if(g){delete e.handle,e.events={};for(var h in g)for(var i=0,j=g[h].length;i<j;i++)f.event.add(b,h+(g[h][i].namespace?".":"")+g[h][i].namespace,g[h][i],g[h][i].data)}}}}function bg(a,b){return f.nodeName(a,"table")?a.getElementsByTagName("tbody")[0]||a.appendChild(a.ownerDocument.createElement("tbody")):a}function W(a,b,c){b=b||0;if(f.isFunction(b))return f.grep(a,function(a,d){var e=!!b.call(a,d,a);return e===c});if(b.nodeType)return f.grep(a,function(a,d){return a===b===c});if(typeof b=="string"){var d=f.grep(a,function(a){return a.nodeType===1});if(R.test(b))return f.filter(b,d,!c);b=f.filter(b,d)}return f.grep(a,function(a,d){return f.inArray(a,b)>=0===c})}function V(a){return!a||!a.parentNode||a.parentNode.nodeType===11}function N(a,b){return(a&&a!=="*"?a+".":"")+b.replace(z,"`").replace(A,"&")}function M(a){var b,c,d,e,g,h,i,j,k,l,m,n,o,p=[],q=[],r=f._data(this,"events");if(!(a.liveFired===this||!r||!r.live||a.target.disabled||a.button&&a.type==="click")){a.namespace&&(n=new RegExp("(^|\\.)"+a.namespace.split(".").join("\\.(?:.*\\.)?")+"(\\.|$)")),a.liveFired=this;var s=r.live.slice(0);for(i=0;i<s.length;i++)g=s[i],g.origType.replace(x,"")===a.type?q.push(g.selector):s.splice(i--,1);e=f(a.target).closest(q,a.currentTarget);for(j=0,k=e.length;j<k;j++){m=e[j];for(i=0;i<s.length;i++){g=s[i];if(m.selector===g.selector&&(!n||n.test(g.namespace))&&!m.elem.disabled){h=m.elem,d=null;if(g.preType==="mouseenter"||g.preType==="mouseleave")a.type=g.preType,d=f(a.relatedTarget).closest(g.selector)[0],d&&f.contains(h,d)&&(d=h);(!d||d!==h)&&p.push({elem:h,handleObj:g,level:m.level})}}}for(j=0,k=p.length;j<k;j++){e=p[j];if(c&&e.level>c)break;a.currentTarget=e.elem,a.data=e.handleObj.data,a.handleObj=e.handleObj,o=e.handleObj.origHandler.apply(e.elem,arguments);if(o===!1||a.isPropagationStopped()){c=e.level,o===!1&&(b=!1);if(a.isImmediatePropagationStopped())break}}return b}}function K(a,c,d){var e=f.extend({},d[0]);e.type=a,e.originalEvent={},e.liveFired=b,f.event.handle.call(c,e),e.isDefaultPrevented()&&d[0].preventDefault()}function E(){return!0}function D(){return!1}function m(a,c,d){var e=c+"defer",g=c+"queue",h=c+"mark",i=f.data(a,e,b,!0);i&&(d==="queue"||!f.data(a,g,b,!0))&&(d==="mark"||!f.data(a,h,b,!0))&&setTimeout(function(){!f.data(a,g,b,!0)&&!f.data(a,h,b,!0)&&(f.removeData(a,e,!0),i.resolve())},0)}function l(a){for(var b in a)if(b!=="toJSON")return!1;return!0}function k(a,c,d){if(d===b&&a.nodeType===1){var e="data-"+c.replace(j,"$1-$2").toLowerCase();d=a.getAttribute(e);if(typeof d=="string"){try{d=d==="true"?!0:d==="false"?!1:d==="null"?null:f.isNaN(d)?i.test(d)?f.parseJSON(d):d:parseFloat(d)}catch(g){}f.data(a,c,d)}else d=b}return d}var c=a.document,d=a.navigator,e=a.location,f=function(){function J(){if(!e.isReady){try{c.documentElement.doScroll("left")}catch(a){setTimeout(J,1);return}e.ready()}}var e=function(a,b){return new e.fn.init(a,b,h)},f=a.jQuery,g=a.$,h,i=/^(?:[^<]*(<[\w\W]+>)[^>]*$|#([\w\-]*)$)/,j=/\S/,k=/^\s+/,l=/\s+$/,m=/\d/,n=/^<(\w+)\s*\/?>(?:<\/\1>)?$/,o=/^[\],:{}\s]*$/,p=/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g,q=/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g,r=/(?:^|:|,)(?:\s*\[)+/g,s=/(webkit)[ \/]([\w.]+)/,t=/(opera)(?:.*version)?[ \/]([\w.]+)/,u=/(msie) ([\w.]+)/,v=/(mozilla)(?:.*? rv:([\w.]+))?/,w=/-([a-z])/ig,x=function(a,b){return b.toUpperCase()},y=d.userAgent,z,A,B,C=Object.prototype.toString,D=Object.prototype.hasOwnProperty,E=Array.prototype.push,F=Array.prototype.slice,G=String.prototype.trim,H=Array.prototype.indexOf,I={};e.fn=e.prototype={constructor:e,init:function(a,d,f){var g,h,j,k;if(!a)return this;if(a.nodeType){this.context=this[0]=a,this.length=1;return this}if(a==="body"&&!d&&c.body){this.context=c,this[0]=c.body,this.selector=a,this.length=1;return this}if(typeof a=="string"){a.charAt(0)!=="<"||a.charAt(a.length-1)!==">"||a.length<3?g=i.exec(a):g=[null,a,null];if(g&&(g[1]||!d)){if(g[1]){d=d instanceof e?d[0]:d,k=d?d.ownerDocument||d:c,j=n.exec(a),j?e.isPlainObject(d)?(a=[c.createElement(j[1])],e.fn.attr.call(a,d,!0)):a=[k.createElement(j[1])]:(j=e.buildFragment([g[1]],[k]),a=(j.cacheable?e.clone(j.fragment):j.fragment).childNodes);return e.merge(this,a)}h=c.getElementById(g[2]);if(h&&h.parentNode){if(h.id!==g[2])return f.find(a);this.length=1,this[0]=h}this.context=c,this.selector=a;return this}return!d||d.jquery?(d||f).find(a):this.constructor(d).find(a)}if(e.isFunction(a))return f.ready(a);a.selector!==b&&(this.selector=a.selector,this.context=a.context);return e.makeArray(a,this)},selector:"",jquery:"1.6.2",length:0,size:function(){return this.length},toArray:function(){return F.call(this,0)},get:function(a){return a==null?this.toArray():a<0?this[this.length+a]:this[a]},pushStack:function(a,b,c){var d=this.constructor();e.isArray(a)?E.apply(d,a):e.merge(d,a),d.prevObject=this,d.context=this.context,b==="find"?d.selector=this.selector+(this.selector?" ":"")+c:b&&(d.selector=this.selector+"."+b+"("+c+")");return d},each:function(a,b){return e.each(this,a,b)},ready:function(a){e.bindReady(),A.done(a);return this},eq:function(a){return a===-1?this.slice(a):this.slice(a,+a+1)},first:function(){return this.eq(0)},last:function(){return this.eq(-1)},slice:function(){return this.pushStack(F.apply(this,arguments),"slice",F.call(arguments).join(","))},map:function(a){return this.pushStack(e.map(this,function(b,c){return a.call(b,c,b)}))},end:function(){return this.prevObject||this.constructor(null)},push:E,sort:[].sort,splice:[].splice},e.fn.init.prototype=e.fn,e.extend=e.fn.extend=function(){var a,c,d,f,g,h,i=arguments[0]||{},j=1,k=arguments.length,l=!1;typeof i=="boolean"&&(l=i,i=arguments[1]||{},j=2),typeof i!="object"&&!e.isFunction(i)&&(i={}),k===j&&(i=this,--j);for(;j<k;j++)if((a=arguments[j])!=null)for(c in a){d=i[c],f=a[c];if(i===f)continue;l&&f&&(e.isPlainObject(f)||(g=e.isArray(f)))?(g?(g=!1,h=d&&e.isArray(d)?d:[]):h=d&&e.isPlainObject(d)?d:{},i[c]=e.extend(l,h,f)):f!==b&&(i[c]=f)}return i},e.extend({noConflict:function(b){a.$===e&&(a.$=g),b&&a.jQuery===e&&(a.jQuery=f);return e},isReady:!1,readyWait:1,holdReady:function(a){a?e.readyWait++:e.ready(!0)},ready:function(a){if(a===!0&&!--e.readyWait||a!==!0&&!e.isReady){if(!c.body)return setTimeout(e.ready,1);e.isReady=!0;if(a!==!0&&--e.readyWait>0)return;A.resolveWith(c,[e]),e.fn.trigger&&e(c).trigger("ready").unbind("ready")}},bindReady:function(){if(!A){A=e._Deferred();if(c.readyState==="complete")return setTimeout(e.ready,1);if(c.addEventListener)c.addEventListener("DOMContentLoaded",B,!1),a.addEventListener("load",e.ready,!1);else if(c.attachEvent){c.attachEvent("onreadystatechange",B),a.attachEvent("onload",e.ready);var b=!1;try{b=a.frameElement==null}catch(d){}c.documentElement.doScroll&&b&&J()}}},isFunction:function(a){return e.type(a)==="function"},isArray:Array.isArray||function(a){return e.type(a)==="array"},isWindow:function(a){return a&&typeof a=="object"&&"setInterval"in a},isNaN:function(a){return a==null||!m.test(a)||isNaN(a)},type:function(a){return a==null?String(a):I[C.call(a)]||"object"},isPlainObject:function(a){if(!a||e.type(a)!=="object"||a.nodeType||e.isWindow(a))return!1;if(a.constructor&&!D.call(a,"constructor")&&!D.call(a.constructor.prototype,"isPrototypeOf"))return!1;var c;for(c in a);return c===b||D.call(a,c)},isEmptyObject:function(a){for(var b in a)return!1;return!0},error:function(a){throw a},parseJSON:function(b){if(typeof b!="string"||!b)return null;b=e.trim(b);if(a.JSON&&a.JSON.parse)return a.JSON.parse(b);if(o.test(b.replace(p,"@").replace(q,"]").replace(r,"")))return(new Function("return "+b))();e.error("Invalid JSON: "+b)},parseXML:function(b,c,d){a.DOMParser?(d=new DOMParser,c=d.parseFromString(b,"text/xml")):(c=new ActiveXObject("Microsoft.XMLDOM"),c.async="false",c.loadXML(b)),d=c.documentElement,(!d||!d.nodeName||d.nodeName==="parsererror")&&e.error("Invalid XML: "+b);return c},noop:function(){},globalEval:function(b){b&&j.test(b)&&(a.execScript||function(b){a.eval.call(a,b)})(b)},camelCase:function(a){return a.replace(w,x)},nodeName:function(a,b){return a.nodeName&&a.nodeName.toUpperCase()===b.toUpperCase()},each:function(a,c,d){var f,g=0,h=a.length,i=h===b||e.isFunction(a);if(d){if(i){for(f in a)if(c.apply(a[f],d)===!1)break}else for(;g<h;)if(c.apply(a[g++],d)===!1)break}else if(i){for(f in a)if(c.call(a[f],f,a[f])===!1)break}else for(;g<h;)if(c.call(a[g],g,a[g++])===!1)break;return a},trim:G?function(a){return a==null?"":G.call(a)}:function(a){return a==null?"":(a+"").replace(k,"").replace(l,"")},makeArray:function(a,b){var c=b||[];if(a!=null){var d=e.type(a);a.length==null||d==="string"||d==="function"||d==="regexp"||e.isWindow(a)?E.call(c,a):e.merge(c,a)}return c},inArray:function(a,b){if(H)return H.call(b,a);for(var c=0,d=b.length;c<d;c++)if(b[c]===a)return c;return-1},merge:function(a,c){var d=a.length,e=0;if(typeof c.length=="number")for(var f=c.length;e<f;e++)a[d++]=c[e];else while(c[e]!==b)a[d++]=c[e++];a.length=d;return a},grep:function(a,b,c){var d=[],e;c=!!c;for(var f=0,g=a.length;f<g;f++)e=!!b(a[f],f),c!==e&&d.push(a[f]);return d},map:function(a,c,d){var f,g,h=[],i=0,j=a.length,k=a instanceof e||j!==b&&typeof j=="number"&&(j>0&&a[0]&&a[j-1]||j===0||e.isArray(a));if(k)for(;i<j;i++)f=c(a[i],i,d),f!=null&&(h[h.length]=f);else for(g in a)f=c(a[g],g,d),f!=null&&(h[h.length]=f);return h.concat.apply([],h)},guid:1,proxy:function(a,c){if(typeof c=="string"){var d=a[c];c=a,a=d}if(!e.isFunction(a))return b;var f=F.call(arguments,2),g=function(){return a.apply(c,f.concat(F.call(arguments)))};g.guid=a.guid=a.guid||g.guid||e.guid++;return g},access:function(a,c,d,f,g,h){var i=a.length;if(typeof c=="object"){for(var j in c)e.access(a,j,c[j],f,g,d);return a}if(d!==b){f=!h&&f&&e.isFunction(d);for(var k=0;k<i;k++)g(a[k],c,f?d.call(a[k],k,g(a[k],c)):d,h);return a}return i?g(a[0],c):b},now:function(){return(new Date).getTime()},uaMatch:function(a){a=a.toLowerCase();var b=s.exec(a)||t.exec(a)||u.exec(a)||a.indexOf("compatible")<0&&v.exec(a)||[];return{browser:b[1]||"",version:b[2]||"0"}},sub:function(){function a(b,c){return new a.fn.init(b,c)}e.extend(!0,a,this),a.superclass=this,a.fn=a.prototype=this(),a.fn.constructor=a,a.sub=this.sub,a.fn.init=function(d,f){f&&f instanceof e&&!(f instanceof a)&&(f=a(f));return e.fn.init.call(this,d,f,b)},a.fn.init.prototype=a.fn;var b=a(c);return a},browser:{}}),e.each("Boolean Number String Function Array Date RegExp Object".split(" "),function(a,b){I["[object "+b+"]"]=b.toLowerCase()}),z=e.uaMatch(y),z.browser&&(e.browser[z.browser]=!0,e.browser.version=z.version),e.browser.webkit&&(e.browser.safari=!0),j.test(" ")&&(k=/^[\s\xA0]+/,l=/[\s\xA0]+$/),h=e(c),c.addEventListener?B=function(){c.removeEventListener("DOMContentLoaded",B,!1),e.ready()}:c.attachEvent&&(B=function(){c.readyState==="complete"&&(c.detachEvent("onreadystatechange",B),e.ready())});return e}(),g="done fail isResolved isRejected promise then always pipe".split(" "),h=[].slice;f.extend({_Deferred:function(){var a=[],b,c,d,e={done:function(){if(!d){var c=arguments,g,h,i,j,k;b&&(k=b,b=0);for(g=0,h=c.length;g<h;g++)i=c[g],j=f.type(i),j==="array"?e.done.apply(e,i):j==="function"&&a.push(i);k&&e.resolveWith(k[0],k[1])}return this},resolveWith:function(e,f){if(!d&&!b&&!c){f=f||[],c=1;try{while(a[0])a.shift().apply(e,f)}finally{b=[e,f],c=0}}return this},resolve:function(){e.resolveWith(this,arguments);return this},isResolved:function(){return!!c||!!b},cancel:function(){d=1,a=[];return this}};return e},Deferred:function(a){var b=f._Deferred(),c=f._Deferred(),d;f.extend(b,{then:function(a,c){b.done(a).fail(c);return this},always:function(){return b.done.apply(b,arguments).fail.apply(this,arguments)},fail:c.done,rejectWith:c.resolveWith,reject:c.resolve,isRejected:c.isResolved,pipe:function(a,c){return f.Deferred(function(d){f.each({done:[a,"resolve"],fail:[c,"reject"]},function(a,c){var e=c[0],g=c[1],h;f.isFunction(e)?b[a](function(){h=e.apply(this,arguments),h&&f.isFunction(h.promise)?h.promise().then(d.resolve,d.reject):d[g](h)}):b[a](d[g])})}).promise()},promise:function(a){if(a==null){if(d)return d;d=a={}}var c=g.length;while(c--)a[g[c]]=b[g[c]];return a}}),b.done(c.cancel).fail(b.cancel),delete b.cancel,a&&a.call(b,b);return b},when:function(a){function i(a){return function(c){b[a]=arguments.length>1?h.call(arguments,0):c,--e||g.resolveWith(g,h.call(b,0))}}var b=arguments,c=0,d=b.length,e=d,g=d<=1&&a&&f.isFunction(a.promise)?a:f.Deferred();if(d>1){for(;c<d;c++)b[c]&&f.isFunction(b[c].promise)?b[c].promise().then(i(c),g.reject):--e;e||g.resolveWith(g,b)}else g!==a&&g.resolveWith(g,d?[a]:[]);return g.promise()}}),f.support=function(){var a=c.createElement("div"),b=c.documentElement,d,e,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u;a.setAttribute("className","t"),a.innerHTML=" <link/><table></table><a href='/a' style='top:1px;float:left;opacity:.55;'>a</a><input type='checkbox'/>",d=a.getElementsByTagName("*"),e=a.getElementsByTagName("a")[0];if(!d||!d.length||!e)return{};g=c.createElement("select"),h=g.appendChild(c.createElement("option")),i=a.getElementsByTagName("input")[0],k={leadingWhitespace:a.firstChild.nodeType===3,tbody:!a.getElementsByTagName("tbody").length,htmlSerialize:!!a.getElementsByTagName("link").length,style:/top/.test(e.getAttribute("style")),hrefNormalized:e.getAttribute("href")==="/a",opacity:/^0.55$/.test(e.style.opacity),cssFloat:!!e.style.cssFloat,checkOn:i.value==="on",optSelected:h.selected,getSetAttribute:a.className!=="t",submitBubbles:!0,changeBubbles:!0,focusinBubbles:!1,deleteExpando:!0,noCloneEvent:!0,inlineBlockNeedsLayout:!1,shrinkWrapBlocks:!1,reliableMarginRight:!0},i.checked=!0,k.noCloneChecked=i.cloneNode(!0).checked,g.disabled=!0,k.optDisabled=!h.disabled;try{delete a.test}catch(v){k.deleteExpando=!1}!a.addEventListener&&a.attachEvent&&a.fireEvent&&(a.attachEvent("onclick",function(){k.noCloneEvent=!1}),a.cloneNode(!0).fireEvent("onclick")),i=c.createElement("input"),i.value="t",i.setAttribute("type","radio"),k.radioValue=i.value==="t",i.setAttribute("checked","checked"),a.appendChild(i),l=c.createDocumentFragment(),l.appendChild(a.firstChild),k.checkClone=l.cloneNode(!0).cloneNode(!0).lastChild.checked,a.innerHTML="",a.style.width=a.style.paddingLeft="1px",m=c.getElementsByTagName("body")[0],o=c.createElement(m?"div":"body"),p={visibility:"hidden",width:0,height:0,border:0,margin:0},m&&f.extend(p,{position:"absolute",left:-1e3,top:-1e3});for(t in p)o.style[t]=p[t];o.appendChild(a),n=m||b,n.insertBefore(o,n.firstChild),k.appendChecked=i.checked,k.boxModel=a.offsetWidth===2,"zoom"in a.style&&(a.style.display="inline",a.style.zoom=1,k.inlineBlockNeedsLayout=a.offsetWidth===2,a.style.display="",a.innerHTML="<div style='width:4px;'></div>",k.shrinkWrapBlocks=a.offsetWidth!==2),a.innerHTML="<table><tr><td style='padding:0;border:0;display:none'></td><td>t</td></tr></table>",q=a.getElementsByTagName("td"),u=q[0].offsetHeight===0,q[0].style.display="",q[1].style.display="none",k.reliableHiddenOffsets=u&&q[0].offsetHeight===0,a.innerHTML="",c.defaultView&&c.defaultView.getComputedStyle&&(j=c.createElement("div"),j.style.width="0",j.style.marginRight="0",a.appendChild(j),k.reliableMarginRight=(parseInt((c.defaultView.getComputedStyle(j,null)||{marginRight:0}).marginRight,10)||0)===0),o.innerHTML="",n.removeChild(o);if(a.attachEvent)for(t in{submit:1,change:1,focusin:1})s="on"+t,u=s in a,u||(a.setAttribute(s,"return;"),u=typeof a[s]=="function"),k[t+"Bubbles"]=u;o=l=g=h=m=j=a=i=null;return k}(),f.boxModel=f.support.boxModel;var i=/^(?:\{.*\}|\[.*\])$/,j=/([a-z])([A-Z])/g;f.extend({cache:{},uuid:0,expando:"jQuery"+(f.fn.jquery+Math.random()).replace(/\D/g,""),noData:{embed:!0,object:"clsid:D27CDB6E-AE6D-11cf-96B8-444553540000",applet:!0},hasData:function(a){a=a.nodeType?f.cache[a[f.expando]]:a[f.expando];return!!a&&!l(a)},data:function(a,c,d,e){if(!!f.acceptData(a)){var g=f.expando,h=typeof c=="string",i,j=a.nodeType,k=j?f.cache:a,l=j?a[f.expando]:a[f.expando]&&f.expando;if((!l||e&&l&&!k[l][g])&&h&&d===b)return;l||(j?a[f.expando]=l=++f.uuid:l=f.expando),k[l]||(k[l]={},j||(k[l].toJSON=f.noop));if(typeof c=="object"||typeof c=="function")e?k[l][g]=f.extend(k[l][g],c):k[l]=f.extend(k[l],c);i=k[l],e&&(i[g]||(i[g]={}),i=i[g]),d!==b&&(i[f.camelCase(c)]=d);if(c==="events"&&!i[c])return i[g]&&i[g].events;return h?i[f.camelCase(c)]||i[c]:i}},removeData:function(b,c,d){if(!!f.acceptData(b)){var e=f.expando,g=b.nodeType,h=g?f.cache:b,i=g?b[f.expando]:f.expando;if(!h[i])return;if(c){var j=d?h[i][e]:h[i];if(j){delete j[c];if(!l(j))return}}if(d){delete h[i][e];if(!l(h[i]))return}var k=h[i][e];f.support.deleteExpando||h!=a?delete h[i]:h[i]=null,k?(h[i]={},g||(h[i].toJSON=f.noop),h[i][e]=k):g&&(f.support.deleteExpando?delete b[f.expando]:b.removeAttribute?b.removeAttribute(f.expando):b[f.expando]=null)}},_data:function(a,b,c){return f.data(a,b,c,!0)},acceptData:function(a){if(a.nodeName){var b=f.noData[a.nodeName.toLowerCase()];if(b)return b!==!0&&a.getAttribute("classid")===b}return!0}}),f.fn.extend({data:function(a,c){var d=null;if(typeof a=="undefined"){if(this.length){d=f.data(this[0]);if(this[0].nodeType===1){var e=this[0].attributes,g;for(var h=0,i=e.length;h<i;h++)g=e[h].name,g.indexOf("data-")===0&&(g=f.camelCase(g.substring(5)),k(this[0],g,d[g]))}}return d}if(typeof a=="object")return this.each(function(){f.data(this,a)});var j=a.split(".");j[1]=j[1]?"."+j[1]:"";if(c===b){d=this.triggerHandler("getData"+j[1]+"!",[j[0]]),d===b&&this.length&&(d=f.data(this[0],a),d=k(this[0],a,d));return d===b&&j[1]?this.data(j[0]):d}return this.each(function(){var b=f(this),d=[j[0],c];b.triggerHandler("setData"+j[1]+"!",d),f.data(this,a,c),b.triggerHandler("changeData"+j[1]+"!",d)})},removeData:function(a){return this.each(function(){f.removeData(this,a)})}}),f.extend({_mark:function(a,c){a&&(c=(c||"fx")+"mark",f.data(a,c,(f.data(a,c,b,!0)||0)+1,!0))},_unmark:function(a,c,d){a!==!0&&(d=c,c=a,a=!1);if(c){d=d||"fx";var e=d+"mark",g=a?0:(f.data(c,e,b,!0)||1)-1;g?f.data(c,e,g,!0):(f.removeData(c,e,!0),m(c,d,"mark"))}},queue:function(a,c,d){if(a){c=(c||"fx")+"queue";var e=f.data(a,c,b,!0);d&&(!e||f.isArray(d)?e=f.data(a,c,f.makeArray(d),!0):e.push(d));return e||[]}},dequeue:function(a,b){b=b||"fx";var c=f.queue(a,b),d=c.shift(),e;d==="inprogress"&&(d=c.shift()),d&&(b==="fx"&&c.unshift("inprogress"),d.call(a,function(){f.dequeue(a,b)})),c.length||(f.removeData(a,b+"queue",!0),m(a,b,"queue"))}}),f.fn.extend({queue:function(a,c){typeof a!="string"&&(c=a,a="fx");if(c===b)return f.queue(this[0],a);return this.each(function(){var b=f.queue(this,a,c);a==="fx"&&b[0]!=="inprogress"&&f.dequeue(this,a)})},dequeue:function(a){return this.each(function(){f.dequeue(this,a)})},delay:function(a,b){a=f.fx?f.fx.speeds[a]||a:a,b=b||"fx";return this.queue(b,function(){var c=this;setTimeout(function(){f.dequeue(c,b)},a)})},clearQueue:function(a){return this.queue(a||"fx",[])},promise:function(a,c){function m(){--h||d.resolveWith(e,[e])}typeof a!="string"&&(c=a,a=b),a=a||"fx";var d=f.Deferred(),e=this,g=e.length,h=1,i=a+"defer",j=a+"queue",k=a+"mark",l;while(g--)if(l=f.data(e[g],i,b,!0)||(f.data(e[g],j,b,!0)||f.data(e[g],k,b,!0))&&f.data(e[g],i,f._Deferred(),!0))h++,l.done(m);m();return d.promise()}});var n=/[\n\t\r]/g,o=/\s+/,p=/\r/g,q=/^(?:button|input)$/i,r=/^(?:button|input|object|select|textarea)$/i,s=/^a(?:rea)?$/i,t=/^(?:autofocus|autoplay|async|checked|controls|defer|disabled|hidden|loop|multiple|open|readonly|required|scoped|selected)$/i,u=/\:|^on/,v,w;f.fn.extend({attr:function(a,b){return f.access(this,a,b,!0,f.attr)},removeAttr:function(a){return this.each(function(){f.removeAttr(this,a)})},prop:function(a,b){return f.access(this,a,b,!0,f.prop)},removeProp:function(a){a=f.propFix[a]||a;return this.each(function(){try{this[a]=b,delete this[a]}catch(c){}})},addClass:function(a){var b,c,d,e,g,h,i;if(f.isFunction(a))return this.each(function(b){f(this).addClass(a.call(this,b,this.className))});if(a&&typeof a=="string"){b=a.split(o);for(c=0,d=this.length;c<d;c++){e=this[c];if(e.nodeType===1)if(!e.className&&b.length===1)e.className=a;else{g=" "+e.className+" ";for(h=0,i=b.length;h<i;h++)~g.indexOf(" "+b[h]+" ")||(g+=b[h]+" ");e.className=f.trim(g)}}}return this},removeClass:function(a){var c,d,e,g,h,i,j;if(f.isFunction(a))return this.each(function(b){f(this).removeClass(a.call(this,b,this.className))});if(a&&typeof a=="string"||a===b){c=(a||"").split(o);for(d=0,e=this.length;d<e;d++){g=this[d];if(g.nodeType===1&&g.className)if(a){h=(" "+g.className+" ").replace(n," ");for(i=0,j=c.length;i<j;i++)h=h.replace(" "+c[i]+" "," ");g.className=f.trim(h)}else g.className=""}}return this},toggleClass:function(a,b){var c=typeof a,d=typeof b=="boolean";if(f.isFunction(a))return this.each(function(c){f(this).toggleClass(a.call(this,c,this.className,b),b)});return this.each(function(){if(c==="string"){var e,g=0,h=f(this),i=b,j=a.split(o);while(e=j[g++])i=d?i:!h.hasClass(e),h[i?"addClass":"removeClass"](e)}else if(c==="undefined"||c==="boolean")this.className&&f._data(this,"__className__",this.className),this.className=this.className||a===!1?"":f._data(this,"__className__")||""})},hasClass:function(a){var b=" "+a+" ";for(var c=0,d=this.length;c<d;c++)if((" "+this[c].className+" ").replace(n," ").indexOf(b)>-1)return!0;return!1},val:function(a){var c,d,e=this[0];if(!arguments.length){if(e){c=f.valHooks[e.nodeName.toLowerCase()]||f.valHooks[e.type];if(c&&"get"in c&&(d=c.get(e,"value"))!==b)return d;d=e.value;return typeof d=="string"?d.replace(p,""):d==null?"":d}return b}var g=f.isFunction(a);return this.each(function(d){var e=f(this),h;if(this.nodeType===1){g?h=a.call(this,d,e.val()):h=a,h==null?h="":typeof h=="number"?h+="":f.isArray(h)&&(h=f.map(h,function(a){return a==null?"":a+""})),c=f.valHooks[this.nodeName.toLowerCase()]||f.valHooks[this.type];if(!c||!("set"in c)||c.set(this,h,"value")===b)this.value=h}})}}),f.extend({valHooks:{option:{get:function(a){var b=a.attributes.value;return!b||b.specified?a.value:a.text}},select:{get:function(a){var b,c=a.selectedIndex,d=[],e=a.options,g=a.type==="select-one";if(c<0)return null;for(var h=g?c:0,i=g?c+1:e.length;h<i;h++){var j=e[h];if(j.selected&&(f.support.optDisabled?!j.disabled:j.getAttribute("disabled")===null)&&(!j.parentNode.disabled||!f.nodeName(j.parentNode,"optgroup"))){b=f(j).val();if(g)return b;d.push(b)}}if(g&&!d.length&&e.length)return f(e[c]).val();return d},set:function(a,b){var c=f.makeArray(b);f(a).find("option").each(function(){this.selected=f.inArray(f(this).val(),c)>=0}),c.length||(a.selectedIndex=-1);return c}}},attrFn:{val:!0,css:!0,html:!0,text:!0,data:!0,width:!0,height:!0,offset:!0},attrFix:{tabindex:"tabIndex"},attr:function(a,c,d,e){var g=a.nodeType;if(!a||g===3||g===8||g===2)return b;if(e&&c in f.attrFn)return f(a)[c](d);if(!("getAttribute"in a))return f.prop(a,c,d);var h,i,j=g!==1||!f.isXMLDoc(a);j&&(c=f.attrFix[c]||c,i=f.attrHooks[c],i||(t.test(c)?i=w:v&&c!=="className"&&(f.nodeName(a,"form")||u.test(c))&&(i=v)));if(d!==b){if(d===null){f.removeAttr(a,c);return b}if(i&&"set"in i&&j&&(h=i.set(a,d,c))!==b)return h;a.setAttribute(c,""+d);return d}if(i&&"get"in i&&j&&(h=i.get(a,c))!==null)return h;h=a.getAttribute(c);return h===null?b:h},removeAttr:function(a,b){var c;a.nodeType===1&&(b=f.attrFix[b]||b,f.support.getSetAttribute?a.removeAttribute(b):(f.attr(a,b,""),a.removeAttributeNode(a.getAttributeNode(b))),t.test(b)&&(c=f.propFix[b]||b)in a&&(a[c]=!1))},attrHooks:{type:{set:function(a,b){if(q.test(a.nodeName)&&a.parentNode)f.error("type property can't be changed");else if(!f.support.radioValue&&b==="radio"&&f.nodeName(a,"input")){var c=a.value;a.setAttribute("type",b),c&&(a.value=c);return b}}},tabIndex:{get:function(a){var c=a.getAttributeNode("tabIndex");return c&&c.specified?parseInt(c.value,10):r.test(a.nodeName)||s.test(a.nodeName)&&a.href?0:b}},value:{get:function(a,b){if(v&&f.nodeName(a,"button"))return v.get(a,b);return b in a?a.value:null},set:function(a,b,c){if(v&&f.nodeName(a,"button"))return v.set(a,b,c);a.value=b}}},propFix:{tabindex:"tabIndex",readonly:"readOnly","for":"htmlFor","class":"className",maxlength:"maxLength",cellspacing:"cellSpacing",cellpadding:"cellPadding",rowspan:"rowSpan",colspan:"colSpan",usemap:"useMap",frameborder:"frameBorder",contenteditable:"contentEditable"},prop:function(a,c,d){var e=a.nodeType;if(!a||e===3||e===8||e===2)return b;var g,h,i=e!==1||!f.isXMLDoc(a);i&&(c=f.propFix[c]||c,h=f.propHooks[c]);return d!==b?h&&"set"in h&&(g=h.set(a,d,c))!==b?g:a[c]=d:h&&"get"in h&&(g=h.get(a,c))!==b?g:a[c]},propHooks:{}}),w={get:function(a,c){return f.prop(a,c)?c.toLowerCase():b},set:function(a,b,c){var d;b===!1?f.removeAttr(a,c):(d=f.propFix[c]||c,d in a&&(a[d]=!0),a.setAttribute(c,c.toLowerCase()));return c}},f.support.getSetAttribute||(f.attrFix=f.propFix,v=f.attrHooks.name=f.attrHooks.title=f.valHooks.button={get:function(a,c){var d;d=a.getAttributeNode(c);return d&&d.nodeValue!==""?d.nodeValue:b},set:function(a,b,c){var d=a.getAttributeNode(c);if(d){d.nodeValue=b;return b}}},f.each(["width","height"],function(a,b){f.attrHooks[b]=f.extend(f.attrHooks[b],{set:function(a,c){if(c===""){a.setAttribute(b,"auto");return c}}})})),f.support.hrefNormalized||f.each(["href","src","width","height"],function(a,c){f.attrHooks[c]=f.extend(f.attrHooks[c],{get:function(a){var d=a.getAttribute(c,2);return d===null?b:d}})}),f.support.style||(f.attrHooks.style={get:function(a){return a.style.cssText.toLowerCase()||b},set:function(a,b){return a.style.cssText=""+b}}),f.support.optSelected||(f.propHooks.selected=f.extend(f.propHooks.selected,{get:function(a){var b=a.parentNode;b&&(b.selectedIndex,b.parentNode&&b.parentNode.selectedIndex)}})),f.support.checkOn||f.each(["radio","checkbox"],function(){f.valHooks[this]={get:function(a){return a.getAttribute("value")===null?"on":a.value}}}),f.each(["radio","checkbox"],function(){f.valHooks[this]=f.extend(f.valHooks[this],{set:function(a,b){if(f.isArray(b))return a.checked=f.inArray(f(a).val(),b)>=0}})});var x=/\.(.*)$/,y=/^(?:textarea|input|select)$/i,z=/\./g,A=/ /g,B=/[^\w\s.|`]/g,C=function(a){return a.replace(B,"\\$&")};f.event={add:function(a,c,d,e){if(a.nodeType!==3&&a.nodeType!==8){if(d===!1)d=D;else if(!d)return;var g,h;d.handler&&(g=d,d=g.handler),d.guid||(d.guid=f.guid++);var i=f._data(a);if(!i)return;var j=i.events,k=i.handle;j||(i.events=j={}),k||(i.handle=k=function(a){return typeof f!="undefined"&&(!a||f.event.triggered!==a.type)?f.event.handle.apply(k.elem,arguments):b}),k.elem=a,c=c.split(" ");var l,m=0,n;while(l=c[m++]){h=g?f.extend({},g):{handler:d,data:e},l.indexOf(".")>-1?(n=l.split("."),l=n.shift(),h.namespace=n.slice(0).sort().join(".")):(n=[],h.namespace=""),h.type=l,h.guid||(h.guid=d.guid);var o=j[l],p=f.event.special[l]||{};if(!o){o=j[l]=[];if(!p.setup||p.setup.call(a,e,n,k)===!1)a.addEventListener?a.addEventListener(l,k,!1):a.attachEvent&&a.attachEvent("on"+l,k)}p.add&&(p.add.call(a,h),h.handler.guid||(h.handler.guid=d.guid)),o.push(h),f.event.global[l]=!0}a=null}},global:{},remove:function(a,c,d,e){if(a.nodeType!==3&&a.nodeType!==8){d===!1&&(d=D);var g,h,i,j,k=0,l,m,n,o,p,q,r,s=f.hasData(a)&&f._data(a),t=s&&s.events;if(!s||!t)return;c&&c.type&&(d=c.handler,c=c.type);if(!c||typeof c=="string"&&c.charAt(0)==="."){c=c||"";for(h in t)f.event.remove(a,h+c);return}c=c.split(" ");while(h=c[k++]){r=h,q=null,l=h.indexOf(".")<0,m=[],l||(m=h.split("."),h=m.shift(),n=new RegExp("(^|\\.)"+f.map(m.slice(0).sort(),C).join("\\.(?:.*\\.)?")+"(\\.|$)")),p=t[h];if(!p)continue;if(!d){for(j=0;j<p.length;j++){q=p[j];if(l||n.test(q.namespace))f.event.remove(a,r,q.handler,j),p.splice(j--,1)}continue}o=f.event.special[h]||{};for(j=e||0;j<p.length;j++){q=p[j];if(d.guid===q.guid){if(l||n.test(q.namespace))e==null&&p.splice(j--,1),o.remove&&o.remove.call(a,q);if(e!=null)break}}if(p.length===0||e!=null&&p.length===1)(!o.teardown||o.teardown.call(a,m)===!1)&&f.removeEvent(a,h,s.handle),g=null,delete t[h]}if(f.isEmptyObject(t)){var u=s.handle;u&&(u.elem=null),delete s.events,delete s.handle,f.isEmptyObject(s)&&f.removeData(a,b,!0)}}},customEvent:{getData:!0,setData:!0,changeData:!0},trigger:function(c,d,e,g){var h=c.type||c,i=[],j;h.indexOf("!")>=0&&(h=h.slice(0,-1),j=!0),h.indexOf(".")>=0&&(i=h.split("."),h=i. shift(),i.sort());if(!!e&&!f.event.customEvent[h]||!!f.event.global[h]){c=typeof c=="object"?c[f.expando]?c:new f.Event(h,c):new f.Event(h),c.type=h,c.exclusive=j,c.namespace=i.join("."),c.namespace_re=new RegExp("(^|\\.)"+i.join("\\.(?:.*\\.)?")+"(\\.|$)");if(g||!e)c.preventDefault(),c.stopPropagation();if(!e){f.each(f.cache,function(){var a=f.expando,b=this[a];b&&b.events&&b.events[h]&&f.event.trigger(c,d,b.handle.elem)});return}if(e.nodeType===3||e.nodeType===8)return;c.result=b,c.target=e,d=d!=null?f.makeArray(d):[],d.unshift(c);var k=e,l=h.indexOf(":")<0?"on"+h:"";do{var m=f._data(k,"handle");c.currentTarget=k,m&&m.apply(k,d),l&&f.acceptData(k)&&k[l]&&k[l].apply(k,d)===!1&&(c.result=!1,c.preventDefault()),k=k.parentNode||k.ownerDocument||k===c.target.ownerDocument&&a}while(k&&!c.isPropagationStopped());if(!c.isDefaultPrevented()){var n,o=f.event.special[h]||{};if((!o._default||o._default.call(e.ownerDocument,c)===!1)&&(h!=="click"||!f.nodeName(e,"a"))&&f.acceptData(e)){try{l&&e[h]&&(n=e[l],n&&(e[l]=null),f.event.triggered=h,e[h]())}catch(p){}n&&(e[l]=n),f.event.triggered=b}}return c.result}},handle:function(c){c=f.event.fix(c||a.event);var d=((f._data(this,"events")||{})[c.type]||[]).slice(0),e=!c.exclusive&&!c.namespace,g=Array.prototype.slice.call(arguments,0);g[0]=c,c.currentTarget=this;for(var h=0,i=d.length;h<i;h++){var j=d[h];if(e||c.namespace_re.test(j.namespace)){c.handler=j.handler,c.data=j.data,c.handleObj=j;var k=j.handler.apply(this,g);k!==b&&(c.result=k,k===!1&&(c.preventDefault(),c.stopPropagation()));if(c.isImmediatePropagationStopped())break}}return c.result},props:"altKey attrChange attrName bubbles button cancelable charCode clientX clientY ctrlKey currentTarget data detail eventPhase fromElement handler keyCode layerX layerY metaKey newValue offsetX offsetY pageX pageY prevValue relatedNode relatedTarget screenX screenY shiftKey srcElement target toElement view wheelDelta which".split(" "),fix:function(a){if(a[f.expando])return a;var d=a;a=f.Event(d);for(var e=this.props.length,g;e;)g=this.props[--e],a[g]=d[g];a.target||(a.target=a.srcElement||c),a.target.nodeType===3&&(a.target=a.target.parentNode),!a.relatedTarget&&a.fromElement&&(a.relatedTarget=a.fromElement===a.target?a.toElement:a.fromElement);if(a.pageX==null&&a.clientX!=null){var h=a.target.ownerDocument||c,i=h.documentElement,j=h.body;a.pageX=a.clientX+(i&&i.scrollLeft||j&&j.scrollLeft||0)-(i&&i.clientLeft||j&&j.clientLeft||0),a.pageY=a.clientY+(i&&i.scrollTop||j&&j.scrollTop||0)-(i&&i.clientTop||j&&j.clientTop||0)}a.which==null&&(a.charCode!=null||a.keyCode!=null)&&(a.which=a.charCode!=null?a.charCode:a.keyCode),!a.metaKey&&a.ctrlKey&&(a.metaKey=a.ctrlKey),!a.which&&a.button!==b&&(a.which=a.button&1?1:a.button&2?3:a.button&4?2:0);return a},guid:1e8,proxy:f.proxy,special:{ready:{setup:f.bindReady,teardown:f.noop},live:{add:function(a){f.event.add(this,N(a.origType,a.selector),f.extend({},a,{handler:M,guid:a.handler.guid}))},remove:function(a){f.event.remove(this,N(a.origType,a.selector),a)}},beforeunload:{setup:function(a,b,c){f.isWindow(this)&&(this.onbeforeunload=c)},teardown:function(a,b){this.onbeforeunload===b&&(this.onbeforeunload=null)}}}},f.removeEvent=c.removeEventListener?function(a,b,c){a.removeEventListener&&a.removeEventListener(b,c,!1)}:function(a,b,c){a.detachEvent&&a.detachEvent("on"+b,c)},f.Event=function(a,b){if(!this.preventDefault)return new f.Event(a,b);a&&a.type?(this.originalEvent=a,this.type=a.type,this.isDefaultPrevented=a.defaultPrevented||a.returnValue===!1||a.getPreventDefault&&a.getPreventDefault()?E:D):this.type=a,b&&f.extend(this,b),this.timeStamp=f.now(),this[f.expando]=!0},f.Event.prototype={preventDefault:function(){this.isDefaultPrevented=E;var a=this.originalEvent;!a||(a.preventDefault?a.preventDefault():a.returnValue=!1)},stopPropagation:function(){this.isPropagationStopped=E;var a=this.originalEvent;!a||(a.stopPropagation&&a.stopPropagation(),a.cancelBubble=!0)},stopImmediatePropagation:function(){this.isImmediatePropagationStopped=E,this.stopPropagation()},isDefaultPrevented:D,isPropagationStopped:D,isImmediatePropagationStopped:D};var F=function(a){var b=a.relatedTarget,c=!1,d=a.type;a.type=a.data,b!==this&&(b&&(c=f.contains(this,b)),c||(f.event.handle.apply(this,arguments),a.type=d))},G=function(a){a.type=a.data,f.event.handle.apply(this,arguments)};f.each({mouseenter:"mouseover",mouseleave:"mouseout"},function(a,b){f.event.special[a]={setup:function(c){f.event.add(this,b,c&&c.selector?G:F,a)},teardown:function(a){f.event.remove(this,b,a&&a.selector?G:F)}}}),f.support.submitBubbles||(f.event.special.submit={setup:function(a,b){if(!f.nodeName(this,"form"))f.event.add(this,"click.specialSubmit",function(a){var b=a.target,c=b.type;(c==="submit"||c==="image")&&f(b).closest("form").length&&K("submit",this,arguments)}),f.event.add(this,"keypress.specialSubmit",function(a){var b=a.target,c=b.type;(c==="text"||c==="password")&&f(b).closest("form").length&&a.keyCode===13&&K("submit",this,arguments)});else return!1},teardown:function(a){f.event.remove(this,".specialSubmit")}});if(!f.support.changeBubbles){var H,I=function(a){var b=a.type,c=a.value;b==="radio"||b==="checkbox"?c=a.checked:b==="select-multiple"?c=a.selectedIndex>-1?f.map(a.options,function(a){return a.selected}).join("-"):"":f.nodeName(a,"select")&&(c=a.selectedIndex);return c},J=function(c){var d=c.target,e,g;if(!!y.test(d.nodeName)&&!d.readOnly){e=f._data(d,"_change_data"),g=I(d),(c.type!=="focusout"||d.type!=="radio")&&f._data(d,"_change_data",g);if(e===b||g===e)return;if(e!=null||g)c.type="change",c.liveFired=b,f.event.trigger(c,arguments[1],d)}};f.event.special.change={filters:{focusout:J,beforedeactivate:J,click:function(a){var b=a.target,c=f.nodeName(b,"input")?b.type:"";(c==="radio"||c==="checkbox"||f.nodeName(b,"select"))&&J.call(this,a)},keydown:function(a){var b=a.target,c=f.nodeName(b,"input")?b.type:"";(a.keyCode===13&&!f.nodeName(b,"textarea")||a.keyCode===32&&(c==="checkbox"||c==="radio")||c==="select-multiple")&&J.call(this,a)},beforeactivate:function(a){var b=a.target;f._data(b,"_change_data",I(b))}},setup:function(a,b){if(this.type==="file")return!1;for(var c in H)f.event.add(this,c+".specialChange",H[c]);return y.test(this.nodeName)},teardown:function(a){f.event.remove(this,".specialChange");return y.test(this.nodeName)}},H=f.event.special.change.filters,H.focus=H.beforeactivate}f.support.focusinBubbles||f.each({focus:"focusin",blur:"focusout"},function(a,b){function e(a){var c=f.event.fix(a);c.type=b,c.originalEvent={},f.event.trigger(c,null,c.target),c.isDefaultPrevented()&&a.preventDefault()}var d=0;f.event.special[b]={setup:function(){d++===0&&c.addEventListener(a,e,!0)},teardown:function(){--d===0&&c.removeEventListener(a,e,!0)}}}),f.each(["bind","one"],function(a,c){f.fn[c]=function(a,d,e){var g;if(typeof a=="object"){for(var h in a)this[c](h,d,a[h],e);return this}if(arguments.length===2||d===!1)e=d,d=b;c==="one"?(g=function(a){f(this).unbind(a,g);return e.apply(this,arguments)},g.guid=e.guid||f.guid++):g=e;if(a==="unload"&&c!=="one")this.one(a,d,e);else for(var i=0,j=this.length;i<j;i++)f.event.add(this[i],a,g,d);return this}}),f.fn.extend({unbind:function(a,b){if(typeof a=="object"&&!a.preventDefault)for(var c in a)this.unbind(c,a[c]);else for(var d=0,e=this.length;d<e;d++)f.event.remove(this[d],a,b);return this},delegate:function(a,b,c,d){return this.live(b,c,d,a)},undelegate:function(a,b,c){return arguments.length===0?this.unbind("live"):this.die(b,null,c,a)},trigger:function(a,b){return this.each(function(){f.event.trigger(a,b,this)})},triggerHandler:function(a,b){if(this[0])return f.event.trigger(a,b,this[0],!0)},toggle:function(a){var b=arguments,c=a.guid||f.guid++,d=0,e=function(c){var e=(f.data(this,"lastToggle"+a.guid)||0)%d;f.data(this,"lastToggle"+a.guid,e+1),c.preventDefault();return b[e].apply(this,arguments)||!1};e.guid=c;while(d<b.length)b[d++].guid=c;return this.click(e)},hover:function(a,b){return this.mouseenter(a).mouseleave(b||a)}});var L={focus:"focusin",blur:"focusout",mouseenter:"mouseover",mouseleave:"mouseout"};f.each(["live","die"],function(a,c){f.fn[c]=function(a,d,e,g){var h,i=0,j,k,l,m=g||this.selector,n=g?this:f(this.context);if(typeof a=="object"&&!a.preventDefault){for(var o in a)n[c](o,d,a[o],m);return this}if(c==="die"&&!a&&g&&g.charAt(0)==="."){n.unbind(g);return this}if(d===!1||f.isFunction(d))e=d||D,d=b;a=(a||"").split(" ");while((h=a[i++])!=null){j=x.exec(h),k="",j&&(k=j[0],h=h.replace(x,""));if(h==="hover"){a.push("mouseenter"+k,"mouseleave"+k);continue}l=h,L[h]?(a.push(L[h]+k),h=h+k):h=(L[h]||h)+k;if(c==="live")for(var p=0,q=n.length;p<q;p++)f.event.add(n[p],"live."+N(h,m),{data:d,selector:m,handler:e,origType:h,origHandler:e,preType:l});else n.unbind("live."+N(h,m),e)}return this}}),f.each("blur focus focusin focusout load resize scroll unload click dblclick mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave change select submit keydown keypress keyup error".split(" "),function(a,b){f.fn[b]=function(a,c){c==null&&(c=a,a=null);return arguments.length>0?this.bind(b,a,c):this.trigger(b)},f.attrFn&&(f.attrFn[b]=!0)}),function(){function u(a,b,c,d,e,f){for(var g=0,h=d.length;g<h;g++){var i=d[g];if(i){var j=!1;i=i[a];while(i){if(i.sizcache===c){j=d[i.sizset];break}if(i.nodeType===1){f||(i.sizcache=c,i.sizset=g);if(typeof b!="string"){if(i===b){j=!0;break}}else if(k.filter(b,[i]).length>0){j=i;break}}i=i[a]}d[g]=j}}}function t(a,b,c,d,e,f){for(var g=0,h=d.length;g<h;g++){var i=d[g];if(i){var j=!1;i=i[a];while(i){if(i.sizcache===c){j=d[i.sizset];break}i.nodeType===1&&!f&&(i.sizcache=c,i.sizset=g);if(i.nodeName.toLowerCase()===b){j=i;break}i=i[a]}d[g]=j}}}var a=/((?:\((?:\([^()]+\)|[^()]+)+\)|\[(?:\[[^\[\]]*\]|['"][^'"]*['"]|[^\[\]'"]+)+\]|\\.|[^ >+~,(\[\\]+)+|[>+~])(\s*,\s*)?((?:.|\r|\n)*)/g,d=0,e=Object.prototype.toString,g=!1,h=!0,i=/\\/g,j=/\W/;[0,0].sort(function(){h=!1;return 0});var k=function(b,d,f,g){f=f||[],d=d||c;var h=d;if(d.nodeType!==1&&d.nodeType!==9)return[];if(!b||typeof b!="string")return f;var i,j,n,o,q,r,s,t,u=!0,w=k.isXML(d),x=[],y=b;do{a.exec(""),i=a.exec(y);if(i){y=i[3],x.push(i[1]);if(i[2]){o=i[3];break}}}while(i);if(x.length>1&&m.exec(b))if(x.length===2&&l.relative[x[0]])j=v(x[0]+x[1],d);else{j=l.relative[x[0]]?[d]:k(x.shift(),d);while(x.length)b=x.shift(),l.relative[b]&&(b+=x.shift()),j=v(b,j)}else{!g&&x.length>1&&d.nodeType===9&&!w&&l.match.ID.test(x[0])&&!l.match.ID.test(x[x.length-1])&&(q=k.find(x.shift(),d,w),d=q.expr?k.filter(q.expr,q.set)[0]:q.set[0]);if(d){q=g?{expr:x.pop(),set:p(g)}:k.find(x.pop(),x.length===1&&(x[0]==="~"||x[0]==="+")&&d.parentNode?d.parentNode:d,w),j=q.expr?k.filter(q.expr,q.set):q.set,x.length>0?n=p(j):u=!1;while(x.length)r=x.pop(),s=r,l.relative[r]?s=x.pop():r="",s==null&&(s=d),l.relative[r](n,s,w)}else n=x=[]}n||(n=j),n||k.error(r||b);if(e.call(n)==="[object Array]")if(!u)f.push.apply(f,n);else if(d&&d.nodeType===1)for(t=0;n[t]!=null;t++)n[t]&&(n[t]===!0||n[t].nodeType===1&&k.contains(d,n[t]))&&f.push(j[t]);else for(t=0;n[t]!=null;t++)n[t]&&n[t].nodeType===1&&f.push(j[t]);else p(n,f);o&&(k(o,h,f,g),k.uniqueSort(f));return f};k.uniqueSort=function(a){if(r){g=h,a.sort(r);if(g)for(var b=1;b<a.length;b++)a[b]===a[b-1]&&a.splice(b--,1)}return a},k.matches=function(a,b){return k(a,null,null,b)},k.matchesSelector=function(a,b){return k(b,null,null,[a]).length>0},k.find=function(a,b,c){var d;if(!a)return[];for(var e=0,f=l.order.length;e<f;e++){var g,h=l.order[e];if(g=l.leftMatch[h].exec(a)){var j=g[1];g.splice(1,1);if(j.substr(j.length-1)!=="\\"){g[1]=(g[1]||"").replace(i,""),d=l.find[h](g,b,c);if(d!=null){a=a.replace(l.match[h],"");break}}}}d||(d=typeof b.getElementsByTagName!="undefined"?b.getElementsByTagName("*"):[]);return{set:d,expr:a}},k.filter=function(a,c,d,e){var f,g,h=a,i=[],j=c,m=c&&c[0]&&k.isXML(c[0]);while(a&&c.length){for(var n in l.filter)if((f=l.leftMatch[n].exec(a))!=null&&f[2]){var o,p,q=l.filter[n],r=f[1];g=!1,f.splice(1,1);if(r.substr(r.length-1)==="\\")continue;j===i&&(i=[]);if(l.preFilter[n]){f=l.preFilter[n](f,j,d,i,e,m);if(!f)g=o=!0;else if(f===!0)continue}if(f)for(var s=0;(p=j[s])!=null;s++)if(p){o=q(p,f,s,j);var t=e^!!o;d&&o!=null?t?g=!0:j[s]=!1:t&&(i.push(p),g=!0)}if(o!==b){d||(j=i),a=a.replace(l.match[n],"");if(!g)return[];break}}if(a===h)if(g==null)k.error(a);else break;h=a}return j},k.error=function(a){throw"Syntax error, unrecognized expression: "+a};var l=k.selectors={order:["ID","NAME","TAG"],match:{ID:/#((?:[\w\u00c0-\uFFFF\-]|\\.)+)/,CLASS:/\.((?:[\w\u00c0-\uFFFF\-]|\\.)+)/,NAME:/\[name=['"]*((?:[\w\u00c0-\uFFFF\-]|\\.)+)['"]*\]/,ATTR:/\[\s*((?:[\w\u00c0-\uFFFF\-]|\\.)+)\s*(?:(\S?=)\s*(?:(['"])(.*?)\3|(#?(?:[\w\u00c0-\uFFFF\-]|\\.)*)|)|)\s*\]/,TAG:/^((?:[\w\u00c0-\uFFFF\*\-]|\\.)+)/,CHILD:/:(only|nth|last|first)-child(?:\(\s*(even|odd|(?:[+\-]?\d+|(?:[+\-]?\d*)?n\s*(?:[+\-]\s*\d+)?))\s*\))?/,POS:/:(nth|eq|gt|lt|first|last|even|odd)(?:\((\d*)\))?(?=[^\-]|$)/,PSEUDO:/:((?:[\w\u00c0-\uFFFF\-]|\\.)+)(?:\((['"]?)((?:\([^\)]+\)|[^\(\)]*)+)\2\))?/},leftMatch:{},attrMap:{"class":"className","for":"htmlFor"},attrHandle:{href:function(a){return a.getAttribute("href")},type:function(a){return a.getAttribute("type")}},relative:{"+":function(a,b){var c=typeof b=="string",d=c&&!j.test(b),e=c&&!d;d&&(b=b.toLowerCase());for(var f=0,g=a.length,h;f<g;f++)if(h=a[f]){while((h=h.previousSibling)&&h.nodeType!==1);a[f]=e||h&&h.nodeName.toLowerCase()===b?h||!1:h===b}e&&k.filter(b,a,!0)},">":function(a,b){var c,d=typeof b=="string",e=0,f=a.length;if(d&&!j.test(b)){b=b.toLowerCase();for(;e<f;e++){c=a[e];if(c){var g=c.parentNode;a[e]=g.nodeName.toLowerCase()===b?g:!1}}}else{for(;e<f;e++)c=a[e],c&&(a[e]=d?c.parentNode:c.parentNode===b);d&&k.filter(b,a,!0)}},"":function(a,b,c){var e,f=d++,g=u;typeof b=="string"&&!j.test(b)&&(b=b.toLowerCase(),e=b,g=t),g("parentNode",b,f,a,e,c)},"~":function(a,b,c){var e,f=d++,g=u;typeof b=="string"&&!j.test(b)&&(b=b.toLowerCase(),e=b,g=t),g("previousSibling",b,f,a,e,c)}},find:{ID:function(a,b,c){if(typeof b.getElementById!="undefined"&&!c){var d=b.getElementById(a[1]);return d&&d.parentNode?[d]:[]}},NAME:function(a,b){if(typeof b.getElementsByName!="undefined"){var c=[],d=b.getElementsByName(a[1]);for(var e=0,f=d.length;e<f;e++)d[e].getAttribute("name")===a[1]&&c.push(d[e]);return c.length===0?null:c}},TAG:function(a,b){if(typeof b.getElementsByTagName!="undefined")return b.getElementsByTagName(a[1])}},preFilter:{CLASS:function(a,b,c,d,e,f){a=" "+a[1].replace(i,"")+" ";if(f)return a;for(var g=0,h;(h=b[g])!=null;g++)h&&(e^(h.className&&(" "+h.className+" ").replace(/[\t\n\r]/g," ").indexOf(a)>=0)?c||d.push(h):c&&(b[g]=!1));return!1},ID:function(a){return a[1].replace(i,"")},TAG:function(a,b){return a[1].replace(i,"").toLowerCase()},CHILD:function(a){if(a[1]==="nth"){a[2]||k.error(a[0]),a[2]=a[2].replace(/^\+|\s*/g,"");var b=/(-?)(\d*)(?:n([+\-]?\d*))?/.exec(a[2]==="even"&&"2n"||a[2]==="odd"&&"2n+1"||!/\D/.test(a[2])&&"0n+"+a[2]||a[2]);a[2]=b[1]+(b[2]||1)-0,a[3]=b[3]-0}else a[2]&&k.error(a[0]);a[0]=d++;return a},ATTR:function(a,b,c,d,e,f){var g=a[1]=a[1].replace(i,"");!f&&l.attrMap[g]&&(a[1]=l.attrMap[g]),a[4]=(a[4]||a[5]||"").replace(i,""),a[2]==="~="&&(a[4]=" "+a[4]+" ");return a},PSEUDO:function(b,c,d,e,f){if(b[1]==="not")if((a.exec(b[3])||"").length>1||/^\w/.test(b[3]))b[3]=k(b[3],null,null,c);else{var g=k.filter(b[3],c,d,!0^f);d||e.push.apply(e,g);return!1}else if(l.match.POS.test(b[0])||l.match.CHILD.test(b[0]))return!0;return b},POS:function(a){a.unshift(!0);return a}},filters:{enabled:function(a){return a.disabled===!1&&a.type!=="hidden"},disabled:function(a){return a.disabled===!0},checked:function(a){return a.checked===!0},selected:function(a){a.parentNode&&a.parentNode.selectedIndex;return a.selected===!0},parent:function(a){return!!a.firstChild},empty:function(a){return!a.firstChild},has:function(a,b,c){return!!k(c[3],a).length},header:function(a){return/h\d/i.test(a.nodeName)},text:function(a){var b=a.getAttribute("type"),c=a.type;return a.nodeName.toLowerCase()==="input"&&"text"===c&&(b===c||b===null)},radio:function(a){return a.nodeName.toLowerCase()==="input"&&"radio"===a.type},checkbox:function(a){return a.nodeName.toLowerCase()==="input"&&"checkbox"===a.type},file:function(a){return a.nodeName.toLowerCase()==="input"&&"file"===a.type},password:function(a){return a.nodeName.toLowerCase()==="input"&&"password"===a.type},submit:function(a){var b=a.nodeName.toLowerCase();return(b==="input"||b==="button")&&"submit"===a.type},image:function(a){return a.nodeName.toLowerCase()==="input"&&"image"===a.type},reset:function(a){var b=a.nodeName.toLowerCase();return(b==="input"||b==="button")&&"reset"===a.type},button:function(a){var b=a.nodeName.toLowerCase();return b==="input"&&"button"===a.type||b==="button"},input:function(a){return/input|select|textarea|button/i.test(a.nodeName)},focus:function(a){return a===a.ownerDocument.activeElement}},setFilters:{first:function(a,b){return b===0},last:function(a,b,c,d){return b===d.length-1},even:function(a,b){return b%2===0},odd:function(a,b){return b%2===1},lt:function(a,b,c){return b<c[3]-0},gt:function(a,b,c){return b>c[3]-0},nth:function(a,b,c){return c[3]-0===b},eq:function(a,b,c){return c[3]-0===b}},filter:{PSEUDO:function(a,b,c,d){var e=b[1],f=l.filters[e];if(f)return f(a,c,b,d);if(e==="contains")return(a.textContent||a.innerText||k.getText([a])||"").indexOf(b[3])>=0;if(e==="not"){var g=b[3];for(var h=0,i=g.length;h<i;h++)if(g[h]===a)return!1;return!0}k.error(e)},CHILD:function(a,b){var c=b[1],d=a;switch(c){case"only":case"first":while(d=d.previousSibling)if(d.nodeType===1)return!1;if(c==="first")return!0;d=a;case"last":while(d=d.nextSibling)if(d.nodeType===1)return!1;return!0;case"nth":var e=b[2],f=b[3];if(e===1&&f===0)return!0;var g=b[0],h=a.parentNode;if(h&&(h.sizcache!==g||!a.nodeIndex)){var i=0;for(d=h.firstChild;d;d=d.nextSibling)d.nodeType===1&&(d.nodeIndex=++i);h.sizcache=g}var j=a.nodeIndex-f;return e===0?j===0:j%e===0&&j/e>=0}},ID:function(a,b){return a.nodeType===1&&a.getAttribute("id")===b},TAG:function(a,b){return b==="*"&&a.nodeType===1||a.nodeName.toLowerCase()===b},CLASS:function(a,b){return(" "+(a.className||a.getAttribute("class"))+" ").indexOf(b)>-1},ATTR:function(a,b){var c=b[1],d=l.attrHandle[c]?l.attrHandle[c](a):a[c]!=null?a[c]:a.getAttribute(c),e=d+"",f=b[2],g=b[4];return d==null?f==="!=":f==="="?e===g:f==="*="?e.indexOf(g)>=0:f==="~="?(" "+e+" ").indexOf(g)>=0:g?f==="!="?e!==g:f==="^="?e.indexOf(g)===0:f==="$="?e.substr(e.length-g.length)===g:f==="|="?e===g||e.substr(0,g.length+1)===g+"-":!1:e&&d!==!1},POS:function(a,b,c,d){var e=b[2],f=l.setFilters[e];if(f)return f(a,c,b,d)}}},m=l.match.POS,n=function(a,b){return"\\"+(b-0+1)};for(var o in l.match)l.match[o]=new RegExp(l.match[o].source+/(?![^\[]*\])(?![^\(]*\))/.source),l.leftMatch[o]=new RegExp(/(^(?:.|\r|\n)*?)/.source+l.match[o].source.replace(/\\(\d+)/g,n));var p=function(a,b){a=Array.prototype.slice.call(a,0);if(b){b.push.apply(b,a);return b}return a};try{Array.prototype.slice.call(c.documentElement.childNodes,0)[0].nodeType}catch(q){p=function(a,b){var c=0,d=b||[];if(e.call(a)==="[object Array]")Array.prototype.push.apply(d,a);else if(typeof a.length=="number")for(var f=a.length;c<f;c++)d.push(a[c]);else for(;a[c];c++)d.push(a[c]);return d}}var r,s;c.documentElement.compareDocumentPosition?r=function(a,b){if(a===b){g=!0;return 0}if(!a.compareDocumentPosition||!b.compareDocumentPosition)return a.compareDocumentPosition?-1:1;return a.compareDocumentPosition(b)&4?-1:1}:(r=function(a,b){if(a===b){g=!0;return 0}if(a.sourceIndex&&b.sourceIndex)return a.sourceIndex-b.sourceIndex;var c,d,e=[],f=[],h=a.parentNode,i=b.parentNode,j=h;if(h===i)return s(a,b);if(!h)return-1;if(!i)return 1;while(j)e.unshift(j),j=j.parentNode;j=i;while(j)f.unshift(j),j=j.parentNode;c=e.length,d=f.length;for(var k=0;k<c&&k<d;k++)if(e[k]!==f[k])return s(e[k],f[k]);return k===c?s(a,f[k],-1):s(e[k],b,1)},s=function(a,b,c){if(a===b)return c;var d=a.nextSibling;while(d){if(d===b)return-1;d=d.nextSibling}return 1}),k.getText=function(a){var b="",c;for(var d=0;a[d];d++)c=a[d],c.nodeType===3||c.nodeType===4?b+=c.nodeValue:c.nodeType!==8&&(b+=k.getText(c.childNodes));return b},function(){var a=c.createElement("div"),d="script"+(new Date).getTime(),e=c.documentElement;a.innerHTML="<a name='"+d+"'/>",e.insertBefore(a,e.firstChild),c.getElementById(d)&&(l.find.ID=function(a,c,d){if(typeof c.getElementById!="undefined"&&!d){var e=c.getElementById(a[1]);return e?e.id===a[1]||typeof e.getAttributeNode!="undefined"&&e.getAttributeNode("id").nodeValue===a[1]?[e]:b:[]}},l.filter.ID=function(a,b){var c=typeof a.getAttributeNode!="undefined"&&a.getAttributeNode("id");return a.nodeType===1&&c&&c.nodeValue===b}),e.removeChild(a),e=a=null}(),function(){var a=c.createElement("div");a.appendChild(c.createComment("")),a.getElementsByTagName("*").length>0&&(l.find.TAG=function(a,b){var c=b.getElementsByTagName(a[1]);if(a[1]==="*"){var d=[];for(var e=0;c[e];e++)c[e].nodeType===1&&d.push(c[e]);c=d}return c}),a.innerHTML="<a href='#'></a>",a.firstChild&&typeof a.firstChild.getAttribute!="undefined"&&a.firstChild.getAttribute("href")!=="#"&&(l.attrHandle.href=function(a){return a.getAttribute("href",2)}),a=null}(),c.querySelectorAll&&function(){var a=k,b=c.createElement("div"),d="__sizzle__";b.innerHTML="<p class='TEST'></p>";if(!b.querySelectorAll||b.querySelectorAll(".TEST").length!==0){k=function(b,e,f,g){e=e||c;if(!g&&!k.isXML(e)){var h=/^(\w+$)|^\.([\w\-]+$)|^#([\w\-]+$)/.exec(b);if(h&&(e.nodeType===1||e.nodeType===9)){if(h[1])return p(e.getElementsByTagName(b),f);if(h[2]&&l.find.CLASS&&e.getElementsByClassName)return p(e.getElementsByClassName(h[2]),f)}if(e.nodeType===9){if(b==="body"&&e.body)return p([e.body],f);if(h&&h[3]){var i=e.getElementById(h[3]);if(!i||!i.parentNode)return p([],f);if(i.id===h[3])return p([i],f)}try{return p(e.querySelectorAll(b),f)}catch(j){}}else if(e.nodeType===1&&e.nodeName.toLowerCase()!=="object"){var m=e,n=e.getAttribute("id"),o=n||d,q=e.parentNode,r=/^\s*[+~]/.test(b);n?o=o.replace(/'/g,"\\$&"):e.setAttribute("id",o),r&&q&&(e=e.parentNode);try{if(!r||q)return p(e.querySelectorAll("[id='"+o+"'] "+b),f)}catch(s){}finally{n||m.removeAttribute("id")}}}return a(b,e,f,g)};for(var e in a)k[e]=a[e];b=null}}(),function(){var a=c.documentElement,b=a.matchesSelector||a.mozMatchesSelector||a.webkitMatchesSelector||a.msMatchesSelector;if(b){var d=!b.call(c.createElement("div"),"div"),e=!1;try{b.call(c.documentElement,"[test!='']:sizzle")}catch(f){e=!0}k.matchesSelector=function(a,c){c=c.replace(/\=\s*([^'"\]]*)\s*\]/g,"='$1']");if(!k.isXML(a))try{if(e||!l.match.PSEUDO.test(c)&&!/!=/.test(c)){var f=b.call(a,c);if(f||!d||a.document&&a.document.nodeType!==11)return f}}catch(g){}return k(c,null,null,[a]).length>0}}}(),function(){var a=c.createElement("div");a.innerHTML="<div class='test e'></div><div class='test'></div>";if(!!a.getElementsByClassName&&a.getElementsByClassName("e").length!==0){a.lastChild.className="e";if(a.getElementsByClassName("e").length===1)return;l.order.splice(1,0,"CLASS"),l.find.CLASS=function(a,b,c){if(typeof b.getElementsByClassName!="undefined"&&!c)return b.getElementsByClassName(a[1])},a=null}}(),c.documentElement.contains?k.contains=function(a,b){return a!==b&&(a.contains?a.contains(b):!0)}:c.documentElement.compareDocumentPosition?k.contains=function(a,b){return!!(a.compareDocumentPosition(b)&16)}:k.contains=function(){return!1},k.isXML=function(a){var b=(a?a.ownerDocument||a:0).documentElement;return b?b.nodeName!=="HTML":!1};var v=function(a,b){var c,d=[],e="",f=b.nodeType?[b]:b;while(c=l.match.PSEUDO.exec(a))e+=c[0],a=a.replace(l.match.PSEUDO,"");a=l.relative[a]?a+"*":a;for(var g=0,h=f.length;g<h;g++)k(a,f[g],d);return k.filter(e,d)};f.find=k,f.expr=k.selectors,f.expr[":"]=f.expr.filters,f.unique=k.uniqueSort,f.text=k.getText,f.isXMLDoc=k.isXML,f.contains=k.contains}();var O=/Until$/,P=/^(?:parents|prevUntil|prevAll)/,Q=/,/,R=/^.[^:#\[\.,]*$/,S=Array.prototype.slice,T=f.expr.match.POS,U={children:!0,contents:!0,next:!0,prev:!0};f.fn.extend({find:function(a){var b=this,c,d;if(typeof a!="string")return f(a).filter(function(){for(c=0,d=b.length;c<d;c++)if(f.contains(b[c],this))return!0});var e=this.pushStack("","find",a),g,h,i;for(c=0,d=this.length;c<d;c++){g=e.length,f.find(a,this[c],e);if(c>0)for(h=g;h<e.length;h++)for(i=0;i<g;i++)if(e[i]===e[h]){e.splice(h--,1);break}}return e},has:function(a){var b=f(a);return this.filter(function(){for(var a=0,c=b.length;a<c;a++)if(f.contains(this,b[a]))return!0})},not:function(a){return this.pushStack(W(this,a,!1),"not",a)},filter:function(a){return this.pushStack(W(this,a,!0),"filter",a)},is:function(a){return!!a&&(typeof a=="string"?f.filter(a,this).length>0:this.filter(a).length>0)},closest:function(a,b){var c=[],d,e,g=this[0];if(f.isArray(a)){var h,i,j={},k=1;if(g&&a.length){for(d=0,e=a.length;d<e;d++)i=a[d],j[i]||(j[i]=T.test(i)?f(i,b||this.context):i);while(g&&g.ownerDocument&&g!==b){for(i in j)h=j[i],(h.jquery?h.index(g)>-1:f(g).is(h))&&c.push({selector:i,elem:g,level:k});g=g.parentNode,k++}}return c}var l=T.test(a)||typeof a!="string"?f(a,b||this.context):0;for(d=0,e=this.length;d<e;d++){g=this[d];while(g){if(l?l.index(g)>-1:f.find.matchesSelector(g,a)){c.push(g);break}g=g.parentNode;if(!g||!g.ownerDocument||g===b||g.nodeType===11)break}}c=c.length>1?f.unique(c):c;return this.pushStack(c,"closest",a)},index:function(a){if(!a||typeof a=="string")return f.inArray(this[0],a?f(a):this.parent().children());return f.inArray(a.jquery?a[0]:a,this)},add:function(a,b){var c=typeof a=="string"?f(a,b):f.makeArray(a&&a.nodeType?[a]:a),d=f.merge(this.get(),c);return this.pushStack(V(c[0])||V(d[0])?d:f.unique(d))},andSelf:function(){return this.add(this.prevObject)}}),f.each({parent:function(a){var b=a.parentNode;return b&&b.nodeType!==11?b:null},parents:function(a){return f.dir(a,"parentNode")},parentsUntil:function(a,b,c){return f.dir(a,"parentNode",c)},next:function(a){return f.nth(a,2,"nextSibling")},prev:function(a){return f.nth(a,2,"previousSibling")},nextAll:function(a){return f.dir(a,"nextSibling")},prevAll:function(a){return f.dir(a,"previousSibling")},nextUntil:function(a,b,c){return f.dir(a,"nextSibling",c)},prevUntil:function(a,b,c){return f.dir(a,"previousSibling",c)},siblings:function(a){return f.sibling(a.parentNode.firstChild,a)},children:function(a){return f.sibling(a.firstChild)},contents:function(a){return f.nodeName(a,"iframe")?a.contentDocument||a.contentWindow.document:f.makeArray(a.childNodes)}},function(a,b){f.fn[a]=function(c,d){var e=f.map(this,b,c),g=S.call(arguments);O.test(a)||(d=c),d&&typeof d=="string"&&(e=f.filter(d,e)),e=this.length>1&&!U[a]?f.unique(e):e,(this.length>1||Q.test(d))&&P.test(a)&&(e=e.reverse());return this.pushStack(e,a,g.join(","))}}),f.extend({filter:function(a,b,c){c&&(a=":not("+a+")");return b.length===1?f.find.matchesSelector(b[0],a)?[b[0]]:[]:f.find.matches(a,b)},dir:function(a,c,d){var e=[],g=a[c];while(g&&g.nodeType!==9&&(d===b||g.nodeType!==1||!f(g).is(d)))g.nodeType===1&&e.push(g),g=g[c];return e},nth:function(a,b,c,d){b=b||1;var e=0;for(;a;a=a[c])if(a.nodeType===1&&++e===b)break;return a},sibling:function(a,b){var c=[];for(;a;a=a.nextSibling)a.nodeType===1&&a!==b&&c.push(a);return c}});var X=/ jQuery\d+="(?:\d+|null)"/g,Y=/^\s+/,Z=/<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/ig,$=/<([\w:]+)/,_=/<tbody/i,ba=/<|&#?\w+;/,bb=/<(?:script|object|embed|option|style)/i,bc=/checked\s*(?:[^=]|=\s*.checked.)/i,bd=/\/(java|ecma)script/i,be=/^\s*<!(?:\[CDATA\[|\-\-)/,bf={option:[1,"<select multiple='multiple'>","</select>"],legend:[1,"<fieldset>","</fieldset>"],thead:[1,"<table>","</table>"],tr:[2,"<table><tbody>","</tbody></table>"],td:[3,"<table><tbody><tr>","</tr></tbody></table>"],col:[2,"<table><tbody></tbody><colgroup>","</colgroup></table>"],area:[1,"<map>","</map>"],_default:[0,"",""]};bf.optgroup=bf.option,bf.tbody=bf.tfoot=bf.colgroup=bf.caption=bf.thead,bf.th=bf.td,f.support.htmlSerialize||(bf._default=[1,"div<div>","</div>"]),f.fn.extend({text:function(a){if(f.isFunction(a))return this.each(function(b){var c=f(this);c.text(a.call(this,b,c.text()))});if(typeof a!="object"&&a!==b)return this.empty().append((this[0]&&this[0].ownerDocument||c).createTextNode(a));return f.text(this)},wrapAll:function(a){if(f.isFunction(a))return this.each(function(b){f(this).wrapAll(a.call(this,b))});if(this[0]){var b=f(a,this[0].ownerDocument).eq(0).clone(!0);this[0].parentNode&&b.insertBefore(this[0]),b.map(function(){var a=this;while(a.firstChild&&a.firstChild.nodeType===1)a=a.firstChild;return a}).append(this)}return this},wrapInner:function(a){if(f.isFunction(a))return this.each(function(b){f(this).wrapInner(a.call(this,b))});return this.each(function(){var b=f(this),c=b.contents();c.length?c.wrapAll(a):b.append(a)})},wrap:function(a){return this.each(function(){f(this).wrapAll(a)})},unwrap:function(){return this.parent().each(function(){f.nodeName(this,"body")||f(this).replaceWith(this.childNodes)}).end()},append:function(){return this.domManip(arguments,!0,function(a){this.nodeType===1&&this.appendChild(a)})},prepend:function(){return this.domManip(arguments,!0,function(a){this.nodeType===1&&this.insertBefore(a,this.firstChild)})},before:function(){if(this[0]&&this[0].parentNode)return this.domManip(arguments,!1,function(a){this.parentNode.insertBefore(a,this)});if(arguments.length){var a=f(arguments[0]);a.push.apply(a,this.toArray());return this.pushStack(a,"before",arguments)}},after:function(){if(this[0]&&this[0].parentNode)return this.domManip(arguments,!1,function(a){this.parentNode.insertBefore(a,this.nextSibling)});if(arguments.length){var a=this.pushStack(this,"after",arguments);a.push.apply(a,f(arguments[0]).toArray());return a}},remove:function(a,b){for(var c=0,d;(d=this[c])!=null;c++)if(!a||f.filter(a,[d]).length)!b&&d.nodeType===1&&(f.cleanData(d.getElementsByTagName("*")),f.cleanData([d])),d.parentNode&&d.parentNode.removeChild(d);return this},empty:function(){for(var a=0,b;(b=this[a])!=null;a++){b.nodeType===1&&f.cleanData(b.getElementsByTagName("*"));while(b.firstChild)b.removeChild(b.firstChild)}return this},clone:function(a,b){a=a==null?!1:a,b=b==null?a:b;return this.map(function(){return f.clone(this,a,b)})},html:function(a){if(a===b)return this[0]&&this[0].nodeType===1?this[0].innerHTML.replace(X,""):null;if(typeof a=="string"&&!bb.test(a)&&(f.support.leadingWhitespace||!Y.test(a))&&!bf[($.exec(a)||["",""])[1].toLowerCase()]){a=a.replace(Z,"<$1></$2>");try{for(var c=0,d=this.length;c<d;c++)this[c].nodeType===1&&(f.cleanData(this[c].getElementsByTagName("*")),this[c].innerHTML=a)}catch(e){this.empty().append(a)}}else f.isFunction(a)?this.each(function(b){var c=f(this);c.html(a.call(this,b,c.html()))}):this.empty().append(a);return this},replaceWith:function(a){if(this[0]&&this[0].parentNode){if(f.isFunction(a))return this.each(function(b){var c=f(this),d=c.html();c.replaceWith(a.call(this,b,d))});typeof a!="string"&&(a=f(a).detach());return this.each(function(){var b=this.nextSibling,c=this.parentNode;f(this).remove(),b?f(b).before(a):f(c).append(a)})}return this.length?this.pushStack(f(f.isFunction(a)?a():a),"replaceWith",a):this},detach:function(a){return this.remove(a,!0)},domManip:function(a,c,d){var e,g,h,i,j=a[0],k=[];if(!f.support.checkClone&&arguments.length===3&&typeof j=="string"&&bc.test(j))return this.each(function(){f(this).domManip(a,c,d,!0)});if(f.isFunction(j))return this.each(function(e){var g=f(this);a[0]=j.call(this,e,c?g.html():b),g.domManip(a,c,d)});if(this[0]){i=j&&j.parentNode,f.support.parentNode&&i&&i.nodeType===11&&i.childNodes.length===this.length?e={fragment:i}:e=f.buildFragment(a,this,k),h=e.fragment,h.childNodes.length===1?g=h=h.firstChild:g=h.firstChild;if(g){c=c&&f.nodeName(g,"tr");for(var l=0,m=this.length,n=m-1;l<m;l++)d.call(c?bg(this[l],g):this[l],e.cacheable||m>1&&l<n?f.clone(h,!0,!0):h)}k.length&&f.each(k,bm)}return this}}),f.buildFragment=function(a,b,d){var e,g,h,i;b&&b[0]&&(i=b[0].ownerDocument||b[0]),i.createDocumentFragment||(i=c),a.length===1&&typeof a[0]=="string"&&a[0].length<512&&i===c&&a[0].charAt(0)==="<"&&!bb.test(a[0])&&(f.support.checkClone||!bc.test(a[0]))&&(g=!0,h=f.fragments[a[0]],h&&h!==1&&(e=h)),e||(e=i.createDocumentFragment(),f.clean(a,i,e,d)),g&&(f.fragments[a[0]]=h?e:1);return{fragment:e,cacheable:g}},f.fragments={},f.each({appendTo:"append",prependTo:"prepend",insertBefore:"before",insertAfter:"after",replaceAll:"replaceWith"},function(a,b){f.fn[a]=function(c){var d=[],e=f(c),g=this.length===1&&this[0].parentNode;if(g&&g.nodeType===11&&g.childNodes.length===1&&e.length===1){e[b](this[0]);return this}for(var h=0,i=e.length;h<i;h++){var j=(h>0?this.clone(!0):this).get();f(e[h])[b](j),d=d.concat(j )}return this.pushStack(d,a,e.selector)}}),f.extend({clone:function(a,b,c){var d=a.cloneNode(!0),e,g,h;if((!f.support.noCloneEvent||!f.support.noCloneChecked)&&(a.nodeType===1||a.nodeType===11)&&!f.isXMLDoc(a)){bi(a,d),e=bj(a),g=bj(d);for(h=0;e[h];++h)bi(e[h],g[h])}if(b){bh(a,d);if(c){e=bj(a),g=bj(d);for(h=0;e[h];++h)bh(e[h],g[h])}}e=g=null;return d},clean:function(a,b,d,e){var g;b=b||c,typeof b.createElement=="undefined"&&(b=b.ownerDocument||b[0]&&b[0].ownerDocument||c);var h=[],i;for(var j=0,k;(k=a[j])!=null;j++){typeof k=="number"&&(k+="");if(!k)continue;if(typeof k=="string")if(!ba.test(k))k=b.createTextNode(k);else{k=k.replace(Z,"<$1></$2>");var l=($.exec(k)||["",""])[1].toLowerCase(),m=bf[l]||bf._default,n=m[0],o=b.createElement("div");o.innerHTML=m[1]+k+m[2];while(n--)o=o.lastChild;if(!f.support.tbody){var p=_.test(k),q=l==="table"&&!p?o.firstChild&&o.firstChild.childNodes:m[1]==="<table>"&&!p?o.childNodes:[];for(i=q.length-1;i>=0;--i)f.nodeName(q[i],"tbody")&&!q[i].childNodes.length&&q[i].parentNode.removeChild(q[i])}!f.support.leadingWhitespace&&Y.test(k)&&o.insertBefore(b.createTextNode(Y.exec(k)[0]),o.firstChild),k=o.childNodes}var r;if(!f.support.appendChecked)if(k[0]&&typeof (r=k.length)=="number")for(i=0;i<r;i++)bl(k[i]);else bl(k);k.nodeType?h.push(k):h=f.merge(h,k)}if(d){g=function(a){return!a.type||bd.test(a.type)};for(j=0;h[j];j++)if(e&&f.nodeName(h[j],"script")&&(!h[j].type||h[j].type.toLowerCase()==="text/javascript"))e.push(h[j].parentNode?h[j].parentNode.removeChild(h[j]):h[j]);else{if(h[j].nodeType===1){var s=f.grep(h[j].getElementsByTagName("script"),g);h.splice.apply(h,[j+1,0].concat(s))}d.appendChild(h[j])}}return h},cleanData:function(a){var b,c,d=f.cache,e=f.expando,g=f.event.special,h=f.support.deleteExpando;for(var i=0,j;(j=a[i])!=null;i++){if(j.nodeName&&f.noData[j.nodeName.toLowerCase()])continue;c=j[f.expando];if(c){b=d[c]&&d[c][e];if(b&&b.events){for(var k in b.events)g[k]?f.event.remove(j,k):f.removeEvent(j,k,b.handle);b.handle&&(b.handle.elem=null)}h?delete j[f.expando]:j.removeAttribute&&j.removeAttribute(f.expando),delete d[c]}}}});var bn=/alpha\([^)]*\)/i,bo=/opacity=([^)]*)/,bp=/([A-Z]|^ms)/g,bq=/^-?\d+(?:px)?$/i,br=/^-?\d/,bs=/^[+\-]=/,bt=/[^+\-\.\de]+/g,bu={position:"absolute",visibility:"hidden",display:"block"},bv=["Left","Right"],bw=["Top","Bottom"],bx,by,bz;f.fn.css=function(a,c){if(arguments.length===2&&c===b)return this;return f.access(this,a,c,!0,function(a,c,d){return d!==b?f.style(a,c,d):f.css(a,c)})},f.extend({cssHooks:{opacity:{get:function(a,b){if(b){var c=bx(a,"opacity","opacity");return c===""?"1":c}return a.style.opacity}}},cssNumber:{fillOpacity:!0,fontWeight:!0,lineHeight:!0,opacity:!0,orphans:!0,widows:!0,zIndex:!0,zoom:!0},cssProps:{"float":f.support.cssFloat?"cssFloat":"styleFloat"},style:function(a,c,d,e){if(!!a&&a.nodeType!==3&&a.nodeType!==8&&!!a.style){var g,h,i=f.camelCase(c),j=a.style,k=f.cssHooks[i];c=f.cssProps[i]||i;if(d===b){if(k&&"get"in k&&(g=k.get(a,!1,e))!==b)return g;return j[c]}h=typeof d;if(h==="number"&&isNaN(d)||d==null)return;h==="string"&&bs.test(d)&&(d=+d.replace(bt,"")+parseFloat(f.css(a,c)),h="number"),h==="number"&&!f.cssNumber[i]&&(d+="px");if(!k||!("set"in k)||(d=k.set(a,d))!==b)try{j[c]=d}catch(l){}}},css:function(a,c,d){var e,g;c=f.camelCase(c),g=f.cssHooks[c],c=f.cssProps[c]||c,c==="cssFloat"&&(c="float");if(g&&"get"in g&&(e=g.get(a,!0,d))!==b)return e;if(bx)return bx(a,c)},swap:function(a,b,c){var d={};for(var e in b)d[e]=a.style[e],a.style[e]=b[e];c.call(a);for(e in b)a.style[e]=d[e]}}),f.curCSS=f.css,f.each(["height","width"],function(a,b){f.cssHooks[b]={get:function(a,c,d){var e;if(c){if(a.offsetWidth!==0)return bA(a,b,d);f.swap(a,bu,function(){e=bA(a,b,d)});return e}},set:function(a,b){if(!bq.test(b))return b;b=parseFloat(b);if(b>=0)return b+"px"}}}),f.support.opacity||(f.cssHooks.opacity={get:function(a,b){return bo.test((b&&a.currentStyle?a.currentStyle.filter:a.style.filter)||"")?parseFloat(RegExp.$1)/100+"":b?"1":""},set:function(a,b){var c=a.style,d=a.currentStyle;c.zoom=1;var e=f.isNaN(b)?"":"alpha(opacity="+b*100+")",g=d&&d.filter||c.filter||"";c.filter=bn.test(g)?g.replace(bn,e):g+" "+e}}),f(function(){f.support.reliableMarginRight||(f.cssHooks.marginRight={get:function(a,b){var c;f.swap(a,{display:"inline-block"},function(){b?c=bx(a,"margin-right","marginRight"):c=a.style.marginRight});return c}})}),c.defaultView&&c.defaultView.getComputedStyle&&(by=function(a,c){var d,e,g;c=c.replace(bp,"-$1").toLowerCase();if(!(e=a.ownerDocument.defaultView))return b;if(g=e.getComputedStyle(a,null))d=g.getPropertyValue(c),d===""&&!f.contains(a.ownerDocument.documentElement,a)&&(d=f.style(a,c));return d}),c.documentElement.currentStyle&&(bz=function(a,b){var c,d=a.currentStyle&&a.currentStyle[b],e=a.runtimeStyle&&a.runtimeStyle[b],f=a.style;!bq.test(d)&&br.test(d)&&(c=f.left,e&&(a.runtimeStyle.left=a.currentStyle.left),f.left=b==="fontSize"?"1em":d||0,d=f.pixelLeft+"px",f.left=c,e&&(a.runtimeStyle.left=e));return d===""?"auto":d}),bx=by||bz,f.expr&&f.expr.filters&&(f.expr.filters.hidden=function(a){var b=a.offsetWidth,c=a.offsetHeight;return b===0&&c===0||!f.support.reliableHiddenOffsets&&(a.style.display||f.css(a,"display"))==="none"},f.expr.filters.visible=function(a){return!f.expr.filters.hidden(a)});var bB=/%20/g,bC=/\[\]$/,bD=/\r?\n/g,bE=/#.*$/,bF=/^(.*?):[ \t]*([^\r\n]*)\r?$/mg,bG=/^(?:color|date|datetime|email|hidden|month|number|password|range|search|tel|text|time|url|week)$/i,bH=/^(?:about|app|app\-storage|.+\-extension|file|widget):$/,bI=/^(?:GET|HEAD)$/,bJ=/^\/\//,bK=/\?/,bL=/<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi,bM=/^(?:select|textarea)/i,bN=/\s+/,bO=/([?&])_=[^&]*/,bP=/^([\w\+\.\-]+:)(?:\/\/([^\/?#:]*)(?::(\d+))?)?/,bQ=f.fn.load,bR={},bS={},bT,bU;try{bT=e.href}catch(bV){bT=c.createElement("a"),bT.href="",bT=bT.href}bU=bP.exec(bT.toLowerCase())||[],f.fn.extend({load:function(a,c,d){if(typeof a!="string"&&bQ)return bQ.apply(this,arguments);if(!this.length)return this;var e=a.indexOf(" ");if(e>=0){var g=a.slice(e,a.length);a=a.slice(0,e)}var h="GET";c&&(f.isFunction(c)?(d=c,c=b):typeof c=="object"&&(c=f.param(c,f.ajaxSettings.traditional),h="POST"));var i=this;f.ajax({url:a,type:h,dataType:"html",data:c,complete:function(a,b,c){c=a.responseText,a.isResolved()&&(a.done(function(a){c=a}),i.html(g?f("<div>").append(c.replace(bL,"")).find(g):c)),d&&i.each(d,[c,b,a])}});return this},serialize:function(){return f.param(this.serializeArray())},serializeArray:function(){return this.map(function(){return this.elements?f.makeArray(this.elements):this}).filter(function(){return this.name&&!this.disabled&&(this.checked||bM.test(this.nodeName)||bG.test(this.type))}).map(function(a,b){var c=f(this).val();return c==null?null:f.isArray(c)?f.map(c,function(a,c){return{name:b.name,value:a.replace(bD,"\r\n")}}):{name:b.name,value:c.replace(bD,"\r\n")}}).get()}}),f.each("ajaxStart ajaxStop ajaxComplete ajaxError ajaxSuccess ajaxSend".split(" "),function(a,b){f.fn[b]=function(a){return this.bind(b,a)}}),f.each(["get","post"],function(a,c){f[c]=function(a,d,e,g){f.isFunction(d)&&(g=g||e,e=d,d=b);return f.ajax({type:c,url:a,data:d,success:e,dataType:g})}}),f.extend({getScript:function(a,c){return f.get(a,b,c,"script")},getJSON:function(a,b,c){return f.get(a,b,c,"json")},ajaxSetup:function(a,b){b?f.extend(!0,a,f.ajaxSettings,b):(b=a,a=f.extend(!0,f.ajaxSettings,b));for(var c in{context:1,url:1})c in b?a[c]=b[c]:c in f.ajaxSettings&&(a[c]=f.ajaxSettings[c]);return a},ajaxSettings:{url:bT,isLocal:bH.test(bU[1]),global:!0,type:"GET",contentType:"application/x-www-form-urlencoded",processData:!0,async:!0,accepts:{xml:"application/xml, text/xml",html:"text/html",text:"text/plain",json:"application/json, text/javascript","*":"*/*"},contents:{xml:/xml/,html:/html/,json:/json/},responseFields:{xml:"responseXML",text:"responseText"},converters:{"* text":a.String,"text html":!0,"text json":f.parseJSON,"text xml":f.parseXML}},ajaxPrefilter:bW(bR),ajaxTransport:bW(bS),ajax:function(a,c){function w(a,c,l,m){if(s!==2){s=2,q&&clearTimeout(q),p=b,n=m||"",v.readyState=a?4:0;var o,r,u,w=l?bZ(d,v,l):b,x,y;if(a>=200&&a<300||a===304){if(d.ifModified){if(x=v.getResponseHeader("Last-Modified"))f.lastModified[k]=x;if(y=v.getResponseHeader("Etag"))f.etag[k]=y}if(a===304)c="notmodified",o=!0;else try{r=b$(d,w),c="success",o=!0}catch(z){c="parsererror",u=z}}else{u=c;if(!c||a)c="error",a<0&&(a=0)}v.status=a,v.statusText=c,o?h.resolveWith(e,[r,c,v]):h.rejectWith(e,[v,c,u]),v.statusCode(j),j=b,t&&g.trigger("ajax"+(o?"Success":"Error"),[v,d,o?r:u]),i.resolveWith(e,[v,c]),t&&(g.trigger("ajaxComplete",[v,d]),--f.active||f.event.trigger("ajaxStop"))}}typeof a=="object"&&(c=a,a=b),c=c||{};var d=f.ajaxSetup({},c),e=d.context||d,g=e!==d&&(e.nodeType||e instanceof f)?f(e):f.event,h=f.Deferred(),i=f._Deferred(),j=d.statusCode||{},k,l={},m={},n,o,p,q,r,s=0,t,u,v={readyState:0,setRequestHeader:function(a,b){if(!s){var c=a.toLowerCase();a=m[c]=m[c]||a,l[a]=b}return this},getAllResponseHeaders:function(){return s===2?n:null},getResponseHeader:function(a){var c;if(s===2){if(!o){o={};while(c=bF.exec(n))o[c[1].toLowerCase()]=c[2]}c=o[a.toLowerCase()]}return c===b?null:c},overrideMimeType:function(a){s||(d.mimeType=a);return this},abort:function(a){a=a||"abort",p&&p.abort(a),w(0,a);return this}};h.promise(v),v.success=v.done,v.error=v.fail,v.complete=i.done,v.statusCode=function(a){if(a){var b;if(s<2)for(b in a)j[b]=[j[b],a[b]];else b=a[v.status],v.then(b,b)}return this},d.url=((a||d.url)+"").replace(bE,"").replace(bJ,bU[1]+"//"),d.dataTypes=f.trim(d.dataType||"*").toLowerCase().split(bN),d.crossDomain==null&&(r=bP.exec(d.url.toLowerCase()),d.crossDomain=!(!r||r[1]==bU[1]&&r[2]==bU[2]&&(r[3]||(r[1]==="http:"?80:443))==(bU[3]||(bU[1]==="http:"?80:443)))),d.data&&d.processData&&typeof d.data!="string"&&(d.data=f.param(d.data,d.traditional)),bX(bR,d,c,v);if(s===2)return!1;t=d.global,d.type=d.type.toUpperCase(),d.hasContent=!bI.test(d.type),t&&f.active++===0&&f.event.trigger("ajaxStart");if(!d.hasContent){d.data&&(d.url+=(bK.test(d.url)?"&":"?")+d.data),k=d.url;if(d.cache===!1){var x=f.now(),y=d.url.replace(bO,"$1_="+x);d.url=y+(y===d.url?(bK.test(d.url)?"&":"?")+"_="+x:"")}}(d.data&&d.hasContent&&d.contentType!==!1||c.contentType)&&v.setRequestHeader("Content-Type",d.contentType),d.ifModified&&(k=k||d.url,f.lastModified[k]&&v.setRequestHeader("If-Modified-Since",f.lastModified[k]),f.etag[k]&&v.setRequestHeader("If-None-Match",f.etag[k])),v.setRequestHeader("Accept",d.dataTypes[0]&&d.accepts[d.dataTypes[0]]?d.accepts[d.dataTypes[0]]+(d.dataTypes[0]!=="*"?", */*; q=0.01":""):d.accepts["*"]);for(u in d.headers)v.setRequestHeader(u,d.headers[u]);if(d.beforeSend&&(d.beforeSend.call(e,v,d)===!1||s===2)){v.abort();return!1}for(u in{success:1,error:1,complete:1})v[u](d[u]);p=bX(bS,d,c,v);if(!p)w(-1,"No Transport");else{v.readyState=1,t&&g.trigger("ajaxSend",[v,d]),d.async&&d.timeout>0&&(q=setTimeout(function(){v.abort("timeout")},d.timeout));try{s=1,p.send(l,w)}catch(z){status<2?w(-1,z):f.error(z)}}return v},param:function(a,c){var d=[],e=function(a,b){b=f.isFunction(b)?b():b,d[d.length]=encodeURIComponent(a)+"="+encodeURIComponent(b)};c===b&&(c=f.ajaxSettings.traditional);if(f.isArray(a)||a.jquery&&!f.isPlainObject(a))f.each(a,function(){e(this.name,this.value)});else for(var g in a)bY(g,a[g],c,e);return d.join("&").replace(bB,"+")}}),f.extend({active:0,lastModified:{},etag:{}});var b_=f.now(),ca=/(\=)\?(&|$)|\?\?/i;f.ajaxSetup({jsonp:"callback",jsonpCallback:function(){return f.expando+"_"+b_++}}),f.ajaxPrefilter("json jsonp",function(b,c,d){var e=b.contentType==="application/x-www-form-urlencoded"&&typeof b.data=="string";if(b.dataTypes[0]==="jsonp"||b.jsonp!==!1&&(ca.test(b.url)||e&&ca.test(b.data))){var g,h=b.jsonpCallback=f.isFunction(b.jsonpCallback)?b.jsonpCallback():b.jsonpCallback,i=a[h],j=b.url,k=b.data,l="$1"+h+"$2";b.jsonp!==!1&&(j=j.replace(ca,l),b.url===j&&(e&&(k=k.replace(ca,l)),b.data===k&&(j+=(/\?/.test(j)?"&":"?")+b.jsonp+"="+h))),b.url=j,b.data=k,a[h]=function(a){g=[a]},d.always(function(){a[h]=i,g&&f.isFunction(i)&&a[h](g[0])}),b.converters["script json"]=function(){g||f.error(h+" was not called");return g[0]},b.dataTypes[0]="json";return"script"}}),f.ajaxSetup({accepts:{script:"text/javascript, application/javascript, application/ecmascript, application/x-ecmascript"},contents:{script:/javascript|ecmascript/},converters:{"text script":function(a){f.globalEval(a);return a}}}),f.ajaxPrefilter("script",function(a){a.cache===b&&(a.cache=!1),a.crossDomain&&(a.type="GET",a.global=!1)}),f.ajaxTransport("script",function(a){if(a.crossDomain){var d,e=c.head||c.getElementsByTagName("head")[0]||c.documentElement;return{send:function(f,g){d=c.createElement("script"),d.async="async",a.scriptCharset&&(d.charset=a.scriptCharset),d.src=a.url,d.onload=d.onreadystatechange=function(a,c){if(c||!d.readyState||/loaded|complete/.test(d.readyState))d.onload=d.onreadystatechange=null,e&&d.parentNode&&e.removeChild(d),d=b,c||g(200,"success")},e.insertBefore(d,e.firstChild)},abort:function(){d&&d.onload(0,1)}}}});var cb=a.ActiveXObject?function(){for(var a in cd)cd[a](0,1)}:!1,cc=0,cd;f.ajaxSettings.xhr=a.ActiveXObject?function(){return!this.isLocal&&ce()||cf()}:ce,function(a){f.extend(f.support,{ajax:!!a,cors:!!a&&"withCredentials"in a})}(f.ajaxSettings.xhr()),f.support.ajax&&f.ajaxTransport(function(c){if(!c.crossDomain||f.support.cors){var d;return{send:function(e,g){var h=c.xhr(),i,j;c.username?h.open(c.type,c.url,c.async,c.username,c.password):h.open(c.type,c.url,c.async);if(c.xhrFields)for(j in c.xhrFields)h[j]=c.xhrFields[j];c.mimeType&&h.overrideMimeType&&h.overrideMimeType(c.mimeType),!c.crossDomain&&!e["X-Requested-With"]&&(e["X-Requested-With"]="XMLHttpRequest");try{for(j in e)h.setRequestHeader(j,e[j])}catch(k){}h.send(c.hasContent&&c.data||null),d=function(a,e){var j,k,l,m,n;try{if(d&&(e||h.readyState===4)){d=b,i&&(h.onreadystatechange=f.noop,cb&&delete cd[i]);if(e)h.readyState!==4&&h.abort();else{j=h.status,l=h.getAllResponseHeaders(),m={},n=h.responseXML,n&&n.documentElement&&(m.xml=n),m.text=h.responseText;try{k=h.statusText}catch(o){k=""}!j&&c.isLocal&&!c.crossDomain?j=m.text?200:404:j===1223&&(j=204)}}}catch(p){e||g(-1,p)}m&&g(j,k,m,l)},!c.async||h.readyState===4?d():(i=++cc,cb&&(cd||(cd={},f(a).unload(cb)),cd[i]=d),h.onreadystatechange=d)},abort:function(){d&&d(0,1)}}}});var cg={},ch,ci,cj=/^(?:toggle|show|hide)$/,ck=/^([+\-]=)?([\d+.\-]+)([a-z%]*)$/i,cl,cm=[["height","marginTop","marginBottom","paddingTop","paddingBottom"],["width","marginLeft","marginRight","paddingLeft","paddingRight"],["opacity"]],cn,co=a.webkitRequestAnimationFrame||a.mozRequestAnimationFrame||a.oRequestAnimationFrame;f.fn.extend({show:function(a,b,c){var d,e;if(a||a===0)return this.animate(cr("show",3),a,b,c);for(var g=0,h=this.length;g<h;g++)d=this[g],d.style&&(e=d.style.display,!f._data(d,"olddisplay")&&e==="none"&&(e=d.style.display=""),e===""&&f.css(d,"display")==="none"&&f._data(d,"olddisplay",cs(d.nodeName)));for(g=0;g<h;g++){d=this[g];if(d.style){e=d.style.display;if(e===""||e==="none")d.style.display=f._data(d,"olddisplay")||""}}return this},hide:function(a,b,c){if(a||a===0)return this.animate(cr("hide",3),a,b,c);for(var d=0,e=this.length;d<e;d++)if(this[d].style){var g=f.css(this[d],"display");g!=="none"&&!f._data(this[d],"olddisplay")&&f._data(this[d],"olddisplay",g)}for(d=0;d<e;d++)this[d].style&&(this[d].style.display="none");return this},_toggle:f.fn.toggle,toggle:function(a,b,c){var d=typeof a=="boolean";f.isFunction(a)&&f.isFunction(b)?this._toggle.apply(this,arguments):a==null||d?this.each(function(){var b=d?a:f(this).is(":hidden");f(this)[b?"show":"hide"]()}):this.animate(cr("toggle",3),a,b,c);return this},fadeTo:function(a,b,c,d){return this.filter(":hidden").css("opacity",0).show().end().animate({opacity:b},a,c,d)},animate:function(a,b,c,d){var e=f.speed(b,c,d);if(f.isEmptyObject(a))return this.each(e.complete,[!1]);a=f.extend({},a);return this[e.queue===!1?"each":"queue"](function(){e.queue===!1&&f._mark(this);var b=f.extend({},e),c=this.nodeType===1,d=c&&f(this).is(":hidden"),g,h,i,j,k,l,m,n,o;b.animatedProperties={};for(i in a){g=f.camelCase(i),i!==g&&(a[g]=a[i],delete a[i]),h=a[g],f.isArray(h)?(b.animatedProperties[g]=h[1],h=a[g]=h[0]):b.animatedProperties[g]=b.specialEasing&&b.specialEasing[g]||b.easing||"swing";if(h==="hide"&&d||h==="show"&&!d)return b.complete.call(this);c&&(g==="height"||g==="width")&&(b.overflow=[this.style.overflow,this.style.overflowX,this.style.overflowY],f.css(this,"display")==="inline"&&f.css(this,"float")==="none"&&(f.support.inlineBlockNeedsLayout?(j=cs(this.nodeName),j==="inline"?this.style.display="inline-block":(this.style.display="inline",this.style.zoom=1)):this.style.display="inline-block"))}b.overflow!=null&&(this.style.overflow="hidden");for(i in a)k=new f.fx(this,b,i),h=a[i],cj.test(h)?k[h==="toggle"?d?"show":"hide":h]():(l=ck.exec(h),m=k.cur(),l?(n=parseFloat(l[2]),o=l[3]||(f.cssNumber[i]?"":"px"),o!=="px"&&(f.style(this,i,(n||1)+o),m=(n||1)/k.cur()*m,f.style(this,i,m+o)),l[1]&&(n=(l[1]==="-="?-1:1)*n+m),k.custom(m,n,o)):k.custom(m,h,""));return!0})},stop:function(a,b){a&&this.queue([]),this.each(function(){var a=f.timers,c=a.length;b||f._unmark(!0,this);while(c--)a[c].elem===this&&(b&&a[c](!0),a.splice(c,1))}),b||this.dequeue();return this}}),f.each({slideDown:cr("show",1),slideUp:cr("hide",1),slideToggle:cr("toggle",1),fadeIn:{opacity:"show"},fadeOut:{opacity:"hide"},fadeToggle:{opacity:"toggle"}},function(a,b){f.fn[a]=function(a,c,d){return this.animate(b,a,c,d)}}),f.extend({speed:function(a,b,c){var d=a&&typeof a=="object"?f.extend({},a):{complete:c||!c&&b||f.isFunction(a)&&a,duration:a,easing:c&&b||b&&!f.isFunction(b)&&b};d.duration=f.fx.off?0:typeof d.duration=="number"?d.duration:d.duration in f.fx.speeds?f.fx.speeds[d.duration]:f.fx.speeds._default,d.old=d.complete,d.complete=function(a){f.isFunction(d.old)&&d.old.call(this),d.queue!==!1?f.dequeue(this):a!==!1&&f._unmark(this)};return d},easing:{linear:function(a,b,c,d){return c+d*a},swing:function(a,b,c,d){return(-Math.cos(a*Math.PI)/2+.5)*d+c}},timers:[],fx:function(a,b,c){this.options=b,this.elem=a,this.prop=c,b.orig=b.orig||{}}}),f.fx.prototype={update:function(){this.options.step&&this.options.step.call(this.elem,this.now,this),(f.fx.step[this.prop]||f.fx.step._default)(this)},cur:function(){if(this.elem[this.prop]!=null&&(!this.elem.style||this.elem.style[this.prop]==null))return this.elem[this.prop];var a,b=f.css(this.elem,this.prop);return isNaN(a=parseFloat(b))?!b||b==="auto"?0:b:a},custom:function(a,b,c){function h(a){return d.step(a)}var d=this,e=f.fx,g;this.startTime=cn||cp(),this.start=a,this.end=b,this.unit=c||this.unit||(f.cssNumber[this.prop]?"":"px"),this.now=this.start,this.pos=this.state=0,h.elem=this.elem,h()&&f.timers.push(h)&&!cl&&(co?(cl=!0,g=function(){cl&&(co(g),e.tick())},co(g)):cl=setInterval(e.tick,e.interval))},show:function(){this.options.orig[this.prop]=f.style(this.elem,this.prop),this.options.show=!0,this.custom(this.prop==="width"||this.prop==="height"?1:0,this.cur()),f(this.elem).show()},hide:function(){this.options.orig[this.prop]=f.style(this.elem,this.prop),this.options.hide=!0,this.custom(this.cur(),0)},step:function(a){var b=cn||cp(),c=!0,d=this.elem,e=this.options,g,h;if(a||b>=e.duration+this.startTime){this.now=this.end,this.pos=this.state=1,this.update(),e.animatedProperties[this.prop]=!0;for(g in e.animatedProperties)e.animatedProperties[g]!==!0&&(c=!1);if(c){e.overflow!=null&&!f.support.shrinkWrapBlocks&&f.each(["","X","Y"],function(a,b){d.style["overflow"+b]=e.overflow[a]}),e.hide&&f(d).hide();if(e.hide||e.show)for(var i in e.animatedProperties)f.style(d,i,e.orig[i]);e.complete.call(d)}return!1}e.duration==Infinity?this.now=b:(h=b-this.startTime,this.state=h/e.duration,this.pos=f.easing[e.animatedProperties[this.prop]](this.state,h,0,1,e.duration),this.now=this.start+(this.end-this.start)*this.pos),this.update();return!0}},f.extend(f.fx,{tick:function(){for(var a=f.timers,b=0;b<a.length;++b)a[b]()||a.splice(b--,1);a.length||f.fx.stop()},interval:13,stop:function(){clearInterval(cl),cl=null},speeds:{slow:600,fast:200,_default:400},step:{opacity:function(a){f.style(a.elem,"opacity",a.now)},_default:function(a){a.elem.style&&a.elem.style[a.prop]!=null?a.elem.style[a.prop]=(a.prop==="width"||a.prop==="height"?Math.max(0,a.now):a.now)+a.unit:a.elem[a.prop]=a.now}}}),f.expr&&f.expr.filters&&(f.expr.filters.animated=function(a){return f.grep(f.timers,function(b){return a===b.elem}).length});var ct=/^t(?:able|d|h)$/i,cu=/^(?:body|html)$/i;"getBoundingClientRect"in c.documentElement?f.fn.offset=function(a){var b=this[0],c;if(a)return this.each(function(b){f.offset.setOffset(this,a,b)});if(!b||!b.ownerDocument)return null;if(b===b.ownerDocument.body)return f.offset.bodyOffset(b);try{c=b.getBoundingClientRect()}catch(d){}var e=b.ownerDocument,g=e.documentElement;if(!c||!f.contains(g,b))return c?{top:c.top,left:c.left}:{top:0,left:0};var h=e.body,i=cv(e),j=g.clientTop||h.clientTop||0,k=g.clientLeft||h.clientLeft||0,l=i.pageYOffset||f.support.boxModel&&g.scrollTop||h.scrollTop,m=i.pageXOffset||f.support.boxModel&&g.scrollLeft||h.scrollLeft,n=c.top+l-j,o=c.left+m-k;return{top:n,left:o}}:f.fn.offset=function(a){var b=this[0];if(a)return this.each(function(b){f.offset.setOffset(this,a,b)});if(!b||!b.ownerDocument)return null;if(b===b.ownerDocument.body)return f.offset.bodyOffset(b);f.offset.initialize();var c,d=b.offsetParent,e=b,g=b.ownerDocument,h=g.documentElement,i=g.body,j=g.defaultView,k=j?j.getComputedStyle(b,null):b.currentStyle,l=b.offsetTop,m=b.offsetLeft;while((b=b.parentNode)&&b!==i&&b!==h){if(f.offset.supportsFixedPosition&&k.position==="fixed")break;c=j?j.getComputedStyle(b,null):b.currentStyle,l-=b.scrollTop,m-=b.scrollLeft,b===d&&(l+=b.offsetTop,m+=b.offsetLeft,f.offset.doesNotAddBorder&&(!f.offset.doesAddBorderForTableAndCells||!ct.test(b.nodeName))&&(l+=parseFloat(c.borderTopWidth)||0,m+=parseFloat(c.borderLeftWidth)||0),e=d,d=b.offsetParent),f.offset.subtractsBorderForOverflowNotVisible&&c.overflow!=="visible"&&(l+=parseFloat(c.borderTopWidth)||0,m+=parseFloat(c.borderLeftWidth)||0),k=c}if(k.position==="relative"||k.position==="static")l+=i.offsetTop,m+=i.offsetLeft;f.offset.supportsFixedPosition&&k.position==="fixed"&&(l+=Math.max(h.scrollTop,i.scrollTop),m+=Math.max(h.scrollLeft,i.scrollLeft));return{top:l,left:m}},f.offset={initialize:function(){var a=c.body,b=c.createElement("div"),d,e,g,h,i=parseFloat(f.css(a,"marginTop"))||0,j="<div style='position:absolute;top:0;left:0;margin:0;border:5px solid #000;padding:0;width:1px;height:1px;'><div></div></div><table style='position:absolute;top:0;left:0;margin:0;border:5px solid #000;padding:0;width:1px;height:1px;' cellpadding='0' cellspacing='0'><tr><td></td></tr></table>";f.extend(b.style,{position:"absolute",top:0,left:0,margin:0,border:0,width:"1px",height:"1px",visibility:"hidden"}),b.innerHTML=j,a.insertBefore(b,a.firstChild),d=b.firstChild,e=d.firstChild,h=d.nextSibling.firstChild.firstChild,this.doesNotAddBorder=e.offsetTop!==5,this.doesAddBorderForTableAndCells=h.offsetTop===5,e.style.position="fixed",e.style.top="20px",this.supportsFixedPosition=e.offsetTop===20||e.offsetTop===15,e.style.position=e.style.top="",d.style.overflow="hidden",d.style.position="relative",this.subtractsBorderForOverflowNotVisible=e.offsetTop===-5,this.doesNotIncludeMarginInBodyOffset=a.offsetTop!==i,a.removeChild(b),f.offset.initialize=f.noop},bodyOffset:function(a){var b=a.offsetTop,c=a.offsetLeft;f.offset.initialize(),f.offset.doesNotIncludeMarginInBodyOffset&&(b+=parseFloat(f.css(a,"marginTop"))||0,c+=parseFloat(f.css(a,"marginLeft"))||0);return{top:b,left:c}},setOffset:function(a,b,c){var d=f.css(a,"position");d==="static"&&(a.style.position="relative");var e=f(a),g=e.offset(),h=f.css(a,"top"),i=f.css(a,"left"),j=(d==="absolute"||d==="fixed")&&f.inArray("auto",[h,i])>-1,k={},l={},m,n;j?(l=e.position(),m=l.top,n=l.left):(m=parseFloat(h)||0,n=parseFloat(i)||0),f.isFunction(b)&&(b=b.call(a,c,g)),b.top!=null&&(k.top=b.top-g.top+m),b.left!=null&&(k.left=b.left-g.left+n),"using"in b?b.using.call(a,k):e.css(k)}},f.fn.extend({position:function(){if(!this[0])return null;var a=this[0],b=this.offsetParent(),c=this.offset(),d=cu.test(b[0].nodeName)?{top:0,left:0}:b.offset();c.top-=parseFloat(f.css(a,"marginTop"))||0,c.left-=parseFloat(f.css(a,"marginLeft"))||0,d.top+=parseFloat(f.css(b[0],"borderTopWidth"))||0,d.left+=parseFloat(f.css(b[0],"borderLeftWidth"))||0;return{top:c.top-d.top,left:c.left-d.left}},offsetParent:function(){return this.map(function(){var a=this.offsetParent||c.body;while(a&&!cu.test(a.nodeName)&&f.css(a,"position")==="static")a=a.offsetParent;return a})}}),f.each(["Left","Top"],function(a,c){var d="scroll"+c;f.fn[d]=function(c){var e,g;if(c===b){e=this[0];if(!e)return null;g=cv(e);return g?"pageXOffset"in g?g[a?"pageYOffset":"pageXOffset"]:f.support.boxModel&&g.document.documentElement[d]||g.document.body[d]:e[d]}return this.each(function(){g=cv(this),g?g.scrollTo(a?f(g).scrollLeft():c,a?c:f(g).scrollTop()):this[d]=c})}}),f.each(["Height","Width"],function(a,c){var d=c.toLowerCase();f.fn["inner"+c]=function(){var a=this[0];return a&&a.style?parseFloat(f.css(a,d,"padding")):null},f.fn["outer"+c]=function(a){var b=this[0];return b&&b.style?parseFloat(f.css(b,d,a?"margin":"border")):null},f.fn[d]=function(a){var e=this[0];if(!e)return a==null?null:this;if(f.isFunction(a))return this.each(function(b){var c=f(this);c[d](a.call(this,b,c[d]()))});if(f.isWindow(e)){var g=e.document.documentElement["client"+c];return e.document.compatMode==="CSS1Compat"&&g||e.document.body["client"+c]||g}if(e.nodeType===9)return Math.max(e.documentElement["client"+c],e.body["scroll"+c],e.documentElement["scroll"+c],e.body["offset"+c],e.documentElement["offset"+c]);if(a===b){var h=f.css(e,d),i=parseFloat(h);return f.isNaN(i)?h:i}return this.css(d,typeof a=="string"?a:a+"px")}}),a.jQuery=a.$=f})(window);
app/initializer/after.js
KleeGroup/focus-demo-app
//////////////////////////////////////////////////////// /// SCRIPT EXECUTED AFTER DOM CONTENT LOADED //////////////////////////////////////////////////////// import React from 'react'; import storesInitializer from './scripts/stores-initializer'; import userInitializer from './scripts/user-initializer'; import headerInitializer from './scripts/header-initializer' import routerInitializer from './scripts/router-initializer' /** * Launches initializers that has to be loaded after DOM content is loaded. */ export const initialize = () => { console.info('[INITIALIZER - AFTER CONTENT LOADED]'); storesInitializer(); userInitializer(); headerInitializer(); routerInitializer(); };
renderer/components/UI/BackgroundTertiary.js
LN-Zap/zap-desktop
import React from 'react' import { Box } from 'rebass/styled-components' /** * @name BackgroundTertiary * @example * <BackgroundTertiary /> */ class BackgroundTertiary extends React.Component { render() { return <Box bg="tertiaryColor" color="primaryText" {...this.props} /> } } export default BackgroundTertiary
app/components/Login/Social.js
Jberivera/pandoras-wall
import React from 'react'; import style from './Login.scss'; import classNames from 'classnames/bind'; const css = classNames.bind(style); const Social = ({ onFacebookLogin }) => { return ( <div> <div className={ css('fb-btn') } onClick={onFacebookLogin}>Facebook</div> </div> ); }; export default Social;
docs/app/Examples/collections/Grid/Variations/GridExampleStretchedEqual.js
shengnian/shengnian-ui-react
import React from 'react' import { Grid, Image, Segment } from 'shengnian-ui-react' const GridExampleStretchedEqual = () => ( <Grid columns='equal'> <Grid.Row stretched> <Grid.Column> <Segment>1</Segment> <Segment>2</Segment> </Grid.Column> <Grid.Column width={6}> <Segment> <Image src='/assets/images/wireframe/paragraph.png' /> </Segment> </Grid.Column> <Grid.Column> <Segment>1</Segment> <Segment>2</Segment> </Grid.Column> </Grid.Row> <Grid.Row> <Grid.Column> <Segment>1</Segment> <Segment>2</Segment> </Grid.Column> <Grid.Column width={6}> <Segment> <Image src='/assets/images/wireframe/paragraph.png' /> </Segment> </Grid.Column> <Grid.Column> <Segment>1</Segment> <Segment>2</Segment> </Grid.Column> </Grid.Row> </Grid> ) export default GridExampleStretchedEqual
imports/ui/components/NestedCategoriesWidget/NestedCategories.js
muhammadsasmito/meteor-solr
/* eslint-disable react/prefer-es6-class */ import React from 'react'; import classNames from 'classnames'; const NestedCategories = React.createClass({ propTypes: { categories: React.PropTypes.object.isRequired, onCategorySelect: React.PropTypes.func.isRequired, selectedCategoryPath: React.PropTypes.string, }, getInitialState() { return { showChildren: false, }; }, componentWillMount() { if (this.isCategorySelected(this.props.selectedCategoryPath)) { this.showChildren(); } }, componentWillReceiveProps(newProps) { if (newProps.selectedCategoryPath && this.isCategorySelected(newProps.selectedCategoryPath)) { this.showChildren(); } else { this.hideChildren(); } }, onChildDisplayToggle(event) { event.preventDefault(); event.stopPropagation(); if (this.props.categories.children) { this.toggleChildren(); } else { this.props.onCategorySelect(this.props.categories.path); } }, showChildren() { this.setState({ showChildren: true }); }, hideChildren() { this.setState({ showChildren: false }); }, toggleChildren() { if (this.state.showChildren) { this.hideChildren(); } else { this.showChildren(); } }, isCategorySelected(incomingCategory) { let isCategorySelected = false; const currentPath = this.props.categories.path.substring( 1, this.props.categories.path.length ); if (incomingCategory && (incomingCategory.indexOf(currentPath) > -1)) { isCategorySelected = true; } return isCategorySelected; }, handleCategorySelect(event) { event.preventDefault(); event.stopPropagation(); this.props.onCategorySelect(this.props.categories.path); }, renderCategoryLink() { let categoryLink; if (this.props.selectedCategoryPath === this.props.categories.path) { categoryLink = ( <span className="selected">{this.props.categories.name}</span> ); } else { categoryLink = ( <a href="#category" onClick={this.handleCategorySelect}> {this.props.categories.name} </a> ); } return categoryLink; }, renderChildrenCategories() { let childrenCategoryContent; const childrenCategories = []; if (this.props.categories.children) { this.props.categories.children.forEach((child) => { childrenCategories.push( <NestedCategories key={child.name} categories={child} onCategorySelect={this.props.onCategorySelect} selectedCategoryPath={this.props.selectedCategoryPath} /> ); }); if (childrenCategories) { childrenCategoryContent = ( <ul>{childrenCategories}</ul> ); } } return childrenCategoryContent; }, render() { const classes = classNames({ 'has-children': this.props.categories.children, 'no-children': !this.props.categories.children, open: this.state.showChildren, closed: !this.state.showChildren, }); return ( <li className={classes} onClick={this.onChildDisplayToggle} > {this.renderCategoryLink()} <span className="count">({this.props.categories.count})</span> {this.renderChildrenCategories()} </li> ); }, }); export default NestedCategories;
js/components/month_choise.js
monetario/web
import React from 'react'; import Datetime from 'react-datetime'; import Formsy from 'formsy-react'; import Moment from 'moment'; const MonthChoise = React.createClass({ getDefaultProps() { return { }; }, render() { return ( <div className="datepicker datepicker-inline"> <div className="datepicker-days" style={{display: 'none'}}> <table className="table table-condensed"> <thead> <tr> <th className="prev" style={{visibility: 'visible'}}>«</th> <th colSpan="5" className="datepicker-switch">January 2005</th> <th className="next" style={{visibility: 'visible'}}>»</th> </tr> <tr> <th className="dow">Su</th> <th className="dow">Mo</th> <th className="dow">Tu</th> <th className="dow">We</th> <th className="dow">Th</th> <th className="dow">Fr</th> <th className="dow">Sa</th> </tr> </thead> <tbody> <tr> <td className="old day">26</td> <td className="old day">27</td> <td className="old day">28</td> <td className="old day">29</td> <td className="old day">30</td> <td className="old day">31</td> <td className="day">1</td> </tr> <tr> <td className="day">2</td> <td className="day">3</td> <td className="day">4</td> <td className="day">5</td> <td className="day">6</td> <td className="day">7</td> <td className="day">8</td> </tr> <tr> <td className="day">9</td> <td className="day">10</td> <td className="day">11</td> <td className="day">12</td> <td className="day">13</td> <td className="day">14</td> <td className="day">15</td> </tr> <tr> <td className="day">16</td> <td className="day">17</td> <td className="day">18</td> <td className="day">19</td> <td className="day">20</td> <td className="day">21</td> <td className="day">22</td> </tr> <tr> <td className="day">23</td> <td className="day">24</td> <td className="day">25</td> <td className="day">26</td> <td className="day">27</td> <td className="day">28</td> <td className="day">29</td> </tr> <tr> <td className="day">30</td> <td className="day">31</td> <td className="new day">1</td> <td className="new day">2</td> <td className="new day">3</td> <td className="new day">4</td> <td className="new day">5</td> </tr> </tbody> <tfoot> <tr> <th colSpan="7" className="today" style={{display: 'none'}}>Today</th> </tr> <tr> <th colSpan="7" className="clear" style={{display: 'none'}}>Clear</th> </tr> </tfoot> </table> </div> <div className="datepicker-months" style={{display: 'block'}}> <table className="table table-condensed"> <thead> <tr> <th className="prev" style={{visibility: 'visible'}}>«</th> <th colSpan="5" className="datepicker-switch">2005</th> <th className="next" style={{visibility: 'visible'}}>»</th> </tr> </thead> <tbody> <tr> <td colSpan="7"><span className="month">Jan</span><span className="month">Feb</span><span className="month">Mar</span><span className="month">Apr</span><span className="month">May</span><span className="month">Jun</span><span className="month">Jul</span><span className="month">Aug</span><span className="month">Sep</span><span className="month">Oct</span><span className="month">Nov</span><span className="month">Dec</span></td> </tr> </tbody> <tfoot> <tr> <th colSpan="7" className="today" style={{display: 'none'}}>Today</th> </tr> <tr> <th colSpan="7" className="clear" style={{display: 'none'}}>Clear</th> </tr> </tfoot> </table> </div> <div className="datepicker-years" style={{display: 'none'}}> <table className="table table-condensed"> <thead> <tr> <th className="prev" style={{visibility: 'visible'}}>«</th> <th colSpan="5" className="datepicker-switch">2000-2009</th> <th className="next" style={{visibility: 'visible'}}>»</th> </tr> </thead> <tbody> <tr> <td colSpan="7"><span className="year old">1999</span><span className="year">2000</span><span className="year">2001</span><span className="year">2002</span><span className="year">2003</span><span className="year">2004</span><span className="year">2005</span><span className="year">2006</span><span className="year">2007</span><span className="year">2008</span><span className="year">2009</span><span className="year new">2010</span></td> </tr> </tbody> <tfoot> <tr> <th colSpan="7" className="today" style={{display: 'none'}}>Today</th> </tr> <tr> <th colSpan="7" className="clear" style={{display: 'none'}}>Clear</th> </tr> </tfoot> </table> </div> </div> ); } }); export default MonthChoise;
react/comments/src/CommentBox.js
sabertazimi/st-proj
import React from 'react'; import CommentList from './CommentList'; import CommentForm from './CommentForm'; export default class CommentBox extends React.Component { constructor(props, context) { super(props, context); this.state = { data: [ { id: 1, author: 'sabertazimi', text: 'Hello React' } ] }; this.handleCommentSubmit = this.handleCommentSubmit.bind(this); } handleCommentSubmit(comment) { comment.id = Date.now(); const comments = this.state.data; const newComments = comments.concat([comment]); this.setState({ data: newComments }); } render() { return ( <div className="commentBox"> <h1>Comments</h1> <CommentList data={this.state.data}/> <CommentForm onCommentSubmit={this.handleCommentSubmit}/> </div> ); } }
packages/material-ui-icons/src/IndeterminateCheckBoxSharp.js
lgollut/material-ui
import * as React from 'react'; import createSvgIcon from './utils/createSvgIcon'; export default createSvgIcon( <path d="M21 3H3v18h18V3zm-4 10H7v-2h10v2z" /> , 'IndeterminateCheckBoxSharp');
ajax/libs/jointjs/0.9.1/joint.js
steadiest/cdnjs
/*! JointJS v0.9.1 - JavaScript diagramming library 2014-08-07 This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/. */ /*! * jQuery JavaScript Library v2.0.3 * http://jquery.com/ * * Includes Sizzle.js * http://sizzlejs.com/ * * Copyright 2005, 2013 jQuery Foundation, Inc. and other contributors * Released under the MIT license * http://jquery.org/license * * Date: 2013-07-03T13:30Z */ (function( window, undefined ) { // Can't do this because several apps including ASP.NET trace // the stack via arguments.caller.callee and Firefox dies if // you try to trace through "use strict" call chains. (#13335) // Support: Firefox 18+ //"use strict"; var // A central reference to the root jQuery(document) rootjQuery, // The deferred used on DOM ready readyList, // Support: IE9 // For `typeof xmlNode.method` instead of `xmlNode.method !== undefined` core_strundefined = typeof undefined, // Use the correct document accordingly with window argument (sandbox) location = window.location, document = window.document, docElem = document.documentElement, // Map over jQuery in case of overwrite _jQuery = window.jQuery, // Map over the $ in case of overwrite _$ = window.$, // [[Class]] -> type pairs class2type = {}, // List of deleted data cache ids, so we can reuse them core_deletedIds = [], core_version = "2.0.3", // Save a reference to some core methods core_concat = core_deletedIds.concat, core_push = core_deletedIds.push, core_slice = core_deletedIds.slice, core_indexOf = core_deletedIds.indexOf, core_toString = class2type.toString, core_hasOwn = class2type.hasOwnProperty, core_trim = core_version.trim, // Define a local copy of jQuery jQuery = function( selector, context ) { // The jQuery object is actually just the init constructor 'enhanced' return new jQuery.fn.init( selector, context, rootjQuery ); }, // Used for matching numbers core_pnum = /[+-]?(?:\d*\.|)\d+(?:[eE][+-]?\d+|)/.source, // Used for splitting on whitespace core_rnotwhite = /\S+/g, // A simple way to check for HTML strings // Prioritize #id over <tag> to avoid XSS via location.hash (#9521) // Strict HTML recognition (#11290: must start with <) rquickExpr = /^(?:\s*(<[\w\W]+>)[^>]*|#([\w-]*))$/, // Match a standalone tag rsingleTag = /^<(\w+)\s*\/?>(?:<\/\1>|)$/, // Matches dashed string for camelizing rmsPrefix = /^-ms-/, rdashAlpha = /-([\da-z])/gi, // Used by jQuery.camelCase as callback to replace() fcamelCase = function( all, letter ) { return letter.toUpperCase(); }, // The ready event handler and self cleanup method completed = function() { document.removeEventListener( "DOMContentLoaded", completed, false ); window.removeEventListener( "load", completed, false ); jQuery.ready(); }; jQuery.fn = jQuery.prototype = { // The current version of jQuery being used jquery: core_version, constructor: jQuery, init: function( selector, context, rootjQuery ) { var match, elem; // HANDLE: $(""), $(null), $(undefined), $(false) if ( !selector ) { return this; } // Handle HTML strings if ( typeof selector === "string" ) { if ( selector.charAt(0) === "<" && selector.charAt( selector.length - 1 ) === ">" && selector.length >= 3 ) { // Assume that strings that start and end with <> are HTML and skip the regex check match = [ null, selector, null ]; } else { match = rquickExpr.exec( selector ); } // Match html or make sure no context is specified for #id if ( match && (match[1] || !context) ) { // HANDLE: $(html) -> $(array) if ( match[1] ) { context = context instanceof jQuery ? context[0] : context; // scripts is true for back-compat jQuery.merge( this, jQuery.parseHTML( match[1], context && context.nodeType ? context.ownerDocument || context : document, true ) ); // HANDLE: $(html, props) if ( rsingleTag.test( match[1] ) && jQuery.isPlainObject( context ) ) { for ( match in context ) { // Properties of context are called as methods if possible if ( jQuery.isFunction( this[ match ] ) ) { this[ match ]( context[ match ] ); // ...and otherwise set as attributes } else { this.attr( match, context[ match ] ); } } } return this; // HANDLE: $(#id) } else { elem = document.getElementById( match[2] ); // Check parentNode to catch when Blackberry 4.6 returns // nodes that are no longer in the document #6963 if ( elem && elem.parentNode ) { // Inject the element directly into the jQuery object this.length = 1; this[0] = elem; } this.context = document; this.selector = selector; return this; } // HANDLE: $(expr, $(...)) } else if ( !context || context.jquery ) { return ( context || rootjQuery ).find( selector ); // HANDLE: $(expr, context) // (which is just equivalent to: $(context).find(expr) } else { return this.constructor( context ).find( selector ); } // HANDLE: $(DOMElement) } else if ( selector.nodeType ) { this.context = this[0] = selector; this.length = 1; return this; // HANDLE: $(function) // Shortcut for document ready } else if ( jQuery.isFunction( selector ) ) { return rootjQuery.ready( selector ); } if ( selector.selector !== undefined ) { this.selector = selector.selector; this.context = selector.context; } return jQuery.makeArray( selector, this ); }, // Start with an empty selector selector: "", // The default length of a jQuery object is 0 length: 0, toArray: function() { return core_slice.call( this ); }, // Get the Nth element in the matched element set OR // Get the whole matched element set as a clean array get: function( num ) { return num == null ? // Return a 'clean' array this.toArray() : // Return just the object ( num < 0 ? this[ this.length + num ] : this[ num ] ); }, // Take an array of elements and push it onto the stack // (returning the new matched element set) pushStack: function( elems ) { // Build a new jQuery matched element set var ret = jQuery.merge( this.constructor(), elems ); // Add the old object onto the stack (as a reference) ret.prevObject = this; ret.context = this.context; // Return the newly-formed element set return ret; }, // Execute a callback for every element in the matched set. // (You can seed the arguments with an array of args, but this is // only used internally.) each: function( callback, args ) { return jQuery.each( this, callback, args ); }, ready: function( fn ) { // Add the callback jQuery.ready.promise().done( fn ); return this; }, slice: function() { return this.pushStack( core_slice.apply( this, arguments ) ); }, first: function() { return this.eq( 0 ); }, last: function() { return this.eq( -1 ); }, eq: function( i ) { var len = this.length, j = +i + ( i < 0 ? len : 0 ); return this.pushStack( j >= 0 && j < len ? [ this[j] ] : [] ); }, map: function( callback ) { return this.pushStack( jQuery.map(this, function( elem, i ) { return callback.call( elem, i, elem ); })); }, end: function() { return this.prevObject || this.constructor(null); }, // For internal use only. // Behaves like an Array's method, not like a jQuery method. push: core_push, sort: [].sort, splice: [].splice }; // Give the init function the jQuery prototype for later instantiation jQuery.fn.init.prototype = jQuery.fn; jQuery.extend = jQuery.fn.extend = function() { var options, name, src, copy, copyIsArray, clone, target = arguments[0] || {}, i = 1, length = arguments.length, deep = false; // Handle a deep copy situation if ( typeof target === "boolean" ) { deep = target; target = arguments[1] || {}; // skip the boolean and the target i = 2; } // Handle case when target is a string or something (possible in deep copy) if ( typeof target !== "object" && !jQuery.isFunction(target) ) { target = {}; } // extend jQuery itself if only one argument is passed if ( length === i ) { target = this; --i; } for ( ; i < length; i++ ) { // Only deal with non-null/undefined values if ( (options = arguments[ i ]) != null ) { // Extend the base object for ( name in options ) { src = target[ name ]; copy = options[ name ]; // Prevent never-ending loop if ( target === copy ) { continue; } // Recurse if we're merging plain objects or arrays if ( deep && copy && ( jQuery.isPlainObject(copy) || (copyIsArray = jQuery.isArray(copy)) ) ) { if ( copyIsArray ) { copyIsArray = false; clone = src && jQuery.isArray(src) ? src : []; } else { clone = src && jQuery.isPlainObject(src) ? src : {}; } // Never move original objects, clone them target[ name ] = jQuery.extend( deep, clone, copy ); // Don't bring in undefined values } else if ( copy !== undefined ) { target[ name ] = copy; } } } } // Return the modified object return target; }; jQuery.extend({ // Unique for each copy of jQuery on the page expando: "jQuery" + ( core_version + Math.random() ).replace( /\D/g, "" ), noConflict: function( deep ) { if ( window.$ === jQuery ) { window.$ = _$; } if ( deep && window.jQuery === jQuery ) { window.jQuery = _jQuery; } return jQuery; }, // Is the DOM ready to be used? Set to true once it occurs. isReady: false, // A counter to track how many items to wait for before // the ready event fires. See #6781 readyWait: 1, // Hold (or release) the ready event holdReady: function( hold ) { if ( hold ) { jQuery.readyWait++; } else { jQuery.ready( true ); } }, // Handle when the DOM is ready ready: function( wait ) { // Abort if there are pending holds or we're already ready if ( wait === true ? --jQuery.readyWait : jQuery.isReady ) { return; } // Remember that the DOM is ready jQuery.isReady = true; // If a normal DOM Ready event fired, decrement, and wait if need be if ( wait !== true && --jQuery.readyWait > 0 ) { return; } // If there are functions bound, to execute readyList.resolveWith( document, [ jQuery ] ); // Trigger any bound ready events if ( jQuery.fn.trigger ) { jQuery( document ).trigger("ready").off("ready"); } }, // See test/unit/core.js for details concerning isFunction. // Since version 1.3, DOM methods and functions like alert // aren't supported. They return false on IE (#2968). isFunction: function( obj ) { return jQuery.type(obj) === "function"; }, isArray: Array.isArray, isWindow: function( obj ) { return obj != null && obj === obj.window; }, isNumeric: function( obj ) { return !isNaN( parseFloat(obj) ) && isFinite( obj ); }, type: function( obj ) { if ( obj == null ) { return String( obj ); } // Support: Safari <= 5.1 (functionish RegExp) return typeof obj === "object" || typeof obj === "function" ? class2type[ core_toString.call(obj) ] || "object" : typeof obj; }, isPlainObject: function( obj ) { // Not plain objects: // - Any object or value whose internal [[Class]] property is not "[object Object]" // - DOM nodes // - window if ( jQuery.type( obj ) !== "object" || obj.nodeType || jQuery.isWindow( obj ) ) { return false; } // Support: Firefox <20 // The try/catch suppresses exceptions thrown when attempting to access // the "constructor" property of certain host objects, ie. |window.location| // https://bugzilla.mozilla.org/show_bug.cgi?id=814622 try { if ( obj.constructor && !core_hasOwn.call( obj.constructor.prototype, "isPrototypeOf" ) ) { return false; } } catch ( e ) { return false; } // If the function hasn't returned already, we're confident that // |obj| is a plain object, created by {} or constructed with new Object return true; }, isEmptyObject: function( obj ) { var name; for ( name in obj ) { return false; } return true; }, error: function( msg ) { throw new Error( msg ); }, // data: string of html // context (optional): If specified, the fragment will be created in this context, defaults to document // keepScripts (optional): If true, will include scripts passed in the html string parseHTML: function( data, context, keepScripts ) { if ( !data || typeof data !== "string" ) { return null; } if ( typeof context === "boolean" ) { keepScripts = context; context = false; } context = context || document; var parsed = rsingleTag.exec( data ), scripts = !keepScripts && []; // Single tag if ( parsed ) { return [ context.createElement( parsed[1] ) ]; } parsed = jQuery.buildFragment( [ data ], context, scripts ); if ( scripts ) { jQuery( scripts ).remove(); } return jQuery.merge( [], parsed.childNodes ); }, parseJSON: JSON.parse, // Cross-browser xml parsing parseXML: function( data ) { var xml, tmp; if ( !data || typeof data !== "string" ) { return null; } // Support: IE9 try { tmp = new DOMParser(); xml = tmp.parseFromString( data , "text/xml" ); } catch ( e ) { xml = undefined; } if ( !xml || xml.getElementsByTagName( "parsererror" ).length ) { jQuery.error( "Invalid XML: " + data ); } return xml; }, noop: function() {}, // Evaluates a script in a global context globalEval: function( code ) { var script, indirect = eval; code = jQuery.trim( code ); if ( code ) { // If the code includes a valid, prologue position // strict mode pragma, execute code by injecting a // script tag into the document. if ( code.indexOf("use strict") === 1 ) { script = document.createElement("script"); script.text = code; document.head.appendChild( script ).parentNode.removeChild( script ); } else { // Otherwise, avoid the DOM node creation, insertion // and removal by using an indirect global eval indirect( code ); } } }, // Convert dashed to camelCase; used by the css and data modules // Microsoft forgot to hump their vendor prefix (#9572) camelCase: function( string ) { return string.replace( rmsPrefix, "ms-" ).replace( rdashAlpha, fcamelCase ); }, nodeName: function( elem, name ) { return elem.nodeName && elem.nodeName.toLowerCase() === name.toLowerCase(); }, // args is for internal usage only each: function( obj, callback, args ) { var value, i = 0, length = obj.length, isArray = isArraylike( obj ); if ( args ) { if ( isArray ) { for ( ; i < length; i++ ) { value = callback.apply( obj[ i ], args ); if ( value === false ) { break; } } } else { for ( i in obj ) { value = callback.apply( obj[ i ], args ); if ( value === false ) { break; } } } // A special, fast, case for the most common use of each } else { if ( isArray ) { for ( ; i < length; i++ ) { value = callback.call( obj[ i ], i, obj[ i ] ); if ( value === false ) { break; } } } else { for ( i in obj ) { value = callback.call( obj[ i ], i, obj[ i ] ); if ( value === false ) { break; } } } } return obj; }, trim: function( text ) { return text == null ? "" : core_trim.call( text ); }, // results is for internal usage only makeArray: function( arr, results ) { var ret = results || []; if ( arr != null ) { if ( isArraylike( Object(arr) ) ) { jQuery.merge( ret, typeof arr === "string" ? [ arr ] : arr ); } else { core_push.call( ret, arr ); } } return ret; }, inArray: function( elem, arr, i ) { return arr == null ? -1 : core_indexOf.call( arr, elem, i ); }, merge: function( first, second ) { var l = second.length, i = first.length, j = 0; if ( typeof l === "number" ) { for ( ; j < l; j++ ) { first[ i++ ] = second[ j ]; } } else { while ( second[j] !== undefined ) { first[ i++ ] = second[ j++ ]; } } first.length = i; return first; }, grep: function( elems, callback, inv ) { var retVal, ret = [], i = 0, length = elems.length; inv = !!inv; // Go through the array, only saving the items // that pass the validator function for ( ; i < length; i++ ) { retVal = !!callback( elems[ i ], i ); if ( inv !== retVal ) { ret.push( elems[ i ] ); } } return ret; }, // arg is for internal usage only map: function( elems, callback, arg ) { var value, i = 0, length = elems.length, isArray = isArraylike( elems ), ret = []; // Go through the array, translating each of the items to their if ( isArray ) { for ( ; i < length; i++ ) { value = callback( elems[ i ], i, arg ); if ( value != null ) { ret[ ret.length ] = value; } } // Go through every key on the object, } else { for ( i in elems ) { value = callback( elems[ i ], i, arg ); if ( value != null ) { ret[ ret.length ] = value; } } } // Flatten any nested arrays return core_concat.apply( [], ret ); }, // A global GUID counter for objects guid: 1, // Bind a function to a context, optionally partially applying any // arguments. proxy: function( fn, context ) { var tmp, args, proxy; if ( typeof context === "string" ) { tmp = fn[ context ]; context = fn; fn = tmp; } // Quick check to determine if target is callable, in the spec // this throws a TypeError, but we will just return undefined. if ( !jQuery.isFunction( fn ) ) { return undefined; } // Simulated bind args = core_slice.call( arguments, 2 ); proxy = function() { return fn.apply( context || this, args.concat( core_slice.call( arguments ) ) ); }; // Set the guid of unique handler to the same of original handler, so it can be removed proxy.guid = fn.guid = fn.guid || jQuery.guid++; return proxy; }, // Multifunctional method to get and set values of a collection // The value/s can optionally be executed if it's a function access: function( elems, fn, key, value, chainable, emptyGet, raw ) { var i = 0, length = elems.length, bulk = key == null; // Sets many values if ( jQuery.type( key ) === "object" ) { chainable = true; for ( i in key ) { jQuery.access( elems, fn, i, key[i], true, emptyGet, raw ); } // Sets one value } else if ( value !== undefined ) { chainable = true; if ( !jQuery.isFunction( value ) ) { raw = true; } if ( bulk ) { // Bulk operations run against the entire set if ( raw ) { fn.call( elems, value ); fn = null; // ...except when executing function values } else { bulk = fn; fn = function( elem, key, value ) { return bulk.call( jQuery( elem ), value ); }; } } if ( fn ) { for ( ; i < length; i++ ) { fn( elems[i], key, raw ? value : value.call( elems[i], i, fn( elems[i], key ) ) ); } } } return chainable ? elems : // Gets bulk ? fn.call( elems ) : length ? fn( elems[0], key ) : emptyGet; }, now: Date.now, // A method for quickly swapping in/out CSS properties to get correct calculations. // Note: this method belongs to the css module but it's needed here for the support module. // If support gets modularized, this method should be moved back to the css module. swap: function( elem, options, callback, args ) { var ret, name, old = {}; // Remember the old values, and insert the new ones for ( name in options ) { old[ name ] = elem.style[ name ]; elem.style[ name ] = options[ name ]; } ret = callback.apply( elem, args || [] ); // Revert the old values for ( name in options ) { elem.style[ name ] = old[ name ]; } return ret; } }); jQuery.ready.promise = function( obj ) { if ( !readyList ) { readyList = jQuery.Deferred(); // Catch cases where $(document).ready() is called after the browser event has already occurred. // we once tried to use readyState "interactive" here, but it caused issues like the one // discovered by ChrisS here: http://bugs.jquery.com/ticket/12282#comment:15 if ( document.readyState === "complete" ) { // Handle it asynchronously to allow scripts the opportunity to delay ready setTimeout( jQuery.ready ); } else { // Use the handy event callback document.addEventListener( "DOMContentLoaded", completed, false ); // A fallback to window.onload, that will always work window.addEventListener( "load", completed, false ); } } return readyList.promise( obj ); }; // Populate the class2type map jQuery.each("Boolean Number String Function Array Date RegExp Object Error".split(" "), function(i, name) { class2type[ "[object " + name + "]" ] = name.toLowerCase(); }); function isArraylike( obj ) { var length = obj.length, type = jQuery.type( obj ); if ( jQuery.isWindow( obj ) ) { return false; } if ( obj.nodeType === 1 && length ) { return true; } return type === "array" || type !== "function" && ( length === 0 || typeof length === "number" && length > 0 && ( length - 1 ) in obj ); } // All jQuery objects should point back to these rootjQuery = jQuery(document); /*! * Sizzle CSS Selector Engine v1.9.4-pre * http://sizzlejs.com/ * * Copyright 2013 jQuery Foundation, Inc. and other contributors * Released under the MIT license * http://jquery.org/license * * Date: 2013-06-03 */ (function( window, undefined ) { var i, support, cachedruns, Expr, getText, isXML, compile, outermostContext, sortInput, // Local document vars setDocument, document, docElem, documentIsHTML, rbuggyQSA, rbuggyMatches, matches, contains, // Instance-specific data expando = "sizzle" + -(new Date()), preferredDoc = window.document, dirruns = 0, done = 0, classCache = createCache(), tokenCache = createCache(), compilerCache = createCache(), hasDuplicate = false, sortOrder = function( a, b ) { if ( a === b ) { hasDuplicate = true; return 0; } return 0; }, // General-purpose constants strundefined = typeof undefined, MAX_NEGATIVE = 1 << 31, // Instance methods hasOwn = ({}).hasOwnProperty, arr = [], pop = arr.pop, push_native = arr.push, push = arr.push, slice = arr.slice, // Use a stripped-down indexOf if we can't use a native one indexOf = arr.indexOf || function( elem ) { var i = 0, len = this.length; for ( ; i < len; i++ ) { if ( this[i] === elem ) { return i; } } return -1; }, booleans = "checked|selected|async|autofocus|autoplay|controls|defer|disabled|hidden|ismap|loop|multiple|open|readonly|required|scoped", // Regular expressions // Whitespace characters http://www.w3.org/TR/css3-selectors/#whitespace whitespace = "[\\x20\\t\\r\\n\\f]", // http://www.w3.org/TR/css3-syntax/#characters characterEncoding = "(?:\\\\.|[\\w-]|[^\\x00-\\xa0])+", // Loosely modeled on CSS identifier characters // An unquoted value should be a CSS identifier http://www.w3.org/TR/css3-selectors/#attribute-selectors // Proper syntax: http://www.w3.org/TR/CSS21/syndata.html#value-def-identifier identifier = characterEncoding.replace( "w", "w#" ), // Acceptable operators http://www.w3.org/TR/selectors/#attribute-selectors attributes = "\\[" + whitespace + "*(" + characterEncoding + ")" + whitespace + "*(?:([*^$|!~]?=)" + whitespace + "*(?:(['\"])((?:\\\\.|[^\\\\])*?)\\3|(" + identifier + ")|)|)" + whitespace + "*\\]", // Prefer arguments quoted, // then not containing pseudos/brackets, // then attribute selectors/non-parenthetical expressions, // then anything else // These preferences are here to reduce the number of selectors // needing tokenize in the PSEUDO preFilter pseudos = ":(" + characterEncoding + ")(?:\\(((['\"])((?:\\\\.|[^\\\\])*?)\\3|((?:\\\\.|[^\\\\()[\\]]|" + attributes.replace( 3, 8 ) + ")*)|.*)\\)|)", // Leading and non-escaped trailing whitespace, capturing some non-whitespace characters preceding the latter rtrim = new RegExp( "^" + whitespace + "+|((?:^|[^\\\\])(?:\\\\.)*)" + whitespace + "+$", "g" ), rcomma = new RegExp( "^" + whitespace + "*," + whitespace + "*" ), rcombinators = new RegExp( "^" + whitespace + "*([>+~]|" + whitespace + ")" + whitespace + "*" ), rsibling = new RegExp( whitespace + "*[+~]" ), rattributeQuotes = new RegExp( "=" + whitespace + "*([^\\]'\"]*)" + whitespace + "*\\]", "g" ), rpseudo = new RegExp( pseudos ), ridentifier = new RegExp( "^" + identifier + "$" ), matchExpr = { "ID": new RegExp( "^#(" + characterEncoding + ")" ), "CLASS": new RegExp( "^\\.(" + characterEncoding + ")" ), "TAG": new RegExp( "^(" + characterEncoding.replace( "w", "w*" ) + ")" ), "ATTR": new RegExp( "^" + attributes ), "PSEUDO": new RegExp( "^" + pseudos ), "CHILD": new RegExp( "^:(only|first|last|nth|nth-last)-(child|of-type)(?:\\(" + whitespace + "*(even|odd|(([+-]|)(\\d*)n|)" + whitespace + "*(?:([+-]|)" + whitespace + "*(\\d+)|))" + whitespace + "*\\)|)", "i" ), "bool": new RegExp( "^(?:" + booleans + ")$", "i" ), // For use in libraries implementing .is() // We use this for POS matching in `select` "needsContext": new RegExp( "^" + whitespace + "*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\\(" + whitespace + "*((?:-\\d)?\\d*)" + whitespace + "*\\)|)(?=[^-]|$)", "i" ) }, rnative = /^[^{]+\{\s*\[native \w/, // Easily-parseable/retrievable ID or TAG or CLASS selectors rquickExpr = /^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/, rinputs = /^(?:input|select|textarea|button)$/i, rheader = /^h\d$/i, rescape = /'|\\/g, // CSS escapes http://www.w3.org/TR/CSS21/syndata.html#escaped-characters runescape = new RegExp( "\\\\([\\da-f]{1,6}" + whitespace + "?|(" + whitespace + ")|.)", "ig" ), funescape = function( _, escaped, escapedWhitespace ) { var high = "0x" + escaped - 0x10000; // NaN means non-codepoint // Support: Firefox // Workaround erroneous numeric interpretation of +"0x" return high !== high || escapedWhitespace ? escaped : // BMP codepoint high < 0 ? String.fromCharCode( high + 0x10000 ) : // Supplemental Plane codepoint (surrogate pair) String.fromCharCode( high >> 10 | 0xD800, high & 0x3FF | 0xDC00 ); }; // Optimize for push.apply( _, NodeList ) try { push.apply( (arr = slice.call( preferredDoc.childNodes )), preferredDoc.childNodes ); // Support: Android<4.0 // Detect silently failing push.apply arr[ preferredDoc.childNodes.length ].nodeType; } catch ( e ) { push = { apply: arr.length ? // Leverage slice if possible function( target, els ) { push_native.apply( target, slice.call(els) ); } : // Support: IE<9 // Otherwise append directly function( target, els ) { var j = target.length, i = 0; // Can't trust NodeList.length while ( (target[j++] = els[i++]) ) {} target.length = j - 1; } }; } function Sizzle( selector, context, results, seed ) { var match, elem, m, nodeType, // QSA vars i, groups, old, nid, newContext, newSelector; if ( ( context ? context.ownerDocument || context : preferredDoc ) !== document ) { setDocument( context ); } context = context || document; results = results || []; if ( !selector || typeof selector !== "string" ) { return results; } if ( (nodeType = context.nodeType) !== 1 && nodeType !== 9 ) { return []; } if ( documentIsHTML && !seed ) { // Shortcuts if ( (match = rquickExpr.exec( selector )) ) { // Speed-up: Sizzle("#ID") if ( (m = match[1]) ) { if ( nodeType === 9 ) { elem = context.getElementById( m ); // Check parentNode to catch when Blackberry 4.6 returns // nodes that are no longer in the document #6963 if ( elem && elem.parentNode ) { // Handle the case where IE, Opera, and Webkit return items // by name instead of ID if ( elem.id === m ) { results.push( elem ); return results; } } else { return results; } } else { // Context is not a document if ( context.ownerDocument && (elem = context.ownerDocument.getElementById( m )) && contains( context, elem ) && elem.id === m ) { results.push( elem ); return results; } } // Speed-up: Sizzle("TAG") } else if ( match[2] ) { push.apply( results, context.getElementsByTagName( selector ) ); return results; // Speed-up: Sizzle(".CLASS") } else if ( (m = match[3]) && support.getElementsByClassName && context.getElementsByClassName ) { push.apply( results, context.getElementsByClassName( m ) ); return results; } } // QSA path if ( support.qsa && (!rbuggyQSA || !rbuggyQSA.test( selector )) ) { nid = old = expando; newContext = context; newSelector = nodeType === 9 && selector; // qSA works strangely on Element-rooted queries // We can work around this by specifying an extra ID on the root // and working up from there (Thanks to Andrew Dupont for the technique) // IE 8 doesn't work on object elements if ( nodeType === 1 && context.nodeName.toLowerCase() !== "object" ) { groups = tokenize( selector ); if ( (old = context.getAttribute("id")) ) { nid = old.replace( rescape, "\\$&" ); } else { context.setAttribute( "id", nid ); } nid = "[id='" + nid + "'] "; i = groups.length; while ( i-- ) { groups[i] = nid + toSelector( groups[i] ); } newContext = rsibling.test( selector ) && context.parentNode || context; newSelector = groups.join(","); } if ( newSelector ) { try { push.apply( results, newContext.querySelectorAll( newSelector ) ); return results; } catch(qsaError) { } finally { if ( !old ) { context.removeAttribute("id"); } } } } } // All others return select( selector.replace( rtrim, "$1" ), context, results, seed ); } /** * Create key-value caches of limited size * @returns {Function(string, Object)} Returns the Object data after storing it on itself with * property name the (space-suffixed) string and (if the cache is larger than Expr.cacheLength) * deleting the oldest entry */ function createCache() { var keys = []; function cache( key, value ) { // Use (key + " ") to avoid collision with native prototype properties (see Issue #157) if ( keys.push( key += " " ) > Expr.cacheLength ) { // Only keep the most recent entries delete cache[ keys.shift() ]; } return (cache[ key ] = value); } return cache; } /** * Mark a function for special use by Sizzle * @param {Function} fn The function to mark */ function markFunction( fn ) { fn[ expando ] = true; return fn; } /** * Support testing using an element * @param {Function} fn Passed the created div and expects a boolean result */ function assert( fn ) { var div = document.createElement("div"); try { return !!fn( div ); } catch (e) { return false; } finally { // Remove from its parent by default if ( div.parentNode ) { div.parentNode.removeChild( div ); } // release memory in IE div = null; } } /** * Adds the same handler for all of the specified attrs * @param {String} attrs Pipe-separated list of attributes * @param {Function} handler The method that will be applied */ function addHandle( attrs, handler ) { var arr = attrs.split("|"), i = attrs.length; while ( i-- ) { Expr.attrHandle[ arr[i] ] = handler; } } /** * Checks document order of two siblings * @param {Element} a * @param {Element} b * @returns {Number} Returns less than 0 if a precedes b, greater than 0 if a follows b */ function siblingCheck( a, b ) { var cur = b && a, diff = cur && a.nodeType === 1 && b.nodeType === 1 && ( ~b.sourceIndex || MAX_NEGATIVE ) - ( ~a.sourceIndex || MAX_NEGATIVE ); // Use IE sourceIndex if available on both nodes if ( diff ) { return diff; } // Check if b follows a if ( cur ) { while ( (cur = cur.nextSibling) ) { if ( cur === b ) { return -1; } } } return a ? 1 : -1; } /** * Returns a function to use in pseudos for input types * @param {String} type */ function createInputPseudo( type ) { return function( elem ) { var name = elem.nodeName.toLowerCase(); return name === "input" && elem.type === type; }; } /** * Returns a function to use in pseudos for buttons * @param {String} type */ function createButtonPseudo( type ) { return function( elem ) { var name = elem.nodeName.toLowerCase(); return (name === "input" || name === "button") && elem.type === type; }; } /** * Returns a function to use in pseudos for positionals * @param {Function} fn */ function createPositionalPseudo( fn ) { return markFunction(function( argument ) { argument = +argument; return markFunction(function( seed, matches ) { var j, matchIndexes = fn( [], seed.length, argument ), i = matchIndexes.length; // Match elements found at the specified indexes while ( i-- ) { if ( seed[ (j = matchIndexes[i]) ] ) { seed[j] = !(matches[j] = seed[j]); } } }); }); } /** * Detect xml * @param {Element|Object} elem An element or a document */ isXML = Sizzle.isXML = function( elem ) { // documentElement is verified for cases where it doesn't yet exist // (such as loading iframes in IE - #4833) var documentElement = elem && (elem.ownerDocument || elem).documentElement; return documentElement ? documentElement.nodeName !== "HTML" : false; }; // Expose support vars for convenience support = Sizzle.support = {}; /** * Sets document-related variables once based on the current document * @param {Element|Object} [doc] An element or document object to use to set the document * @returns {Object} Returns the current document */ setDocument = Sizzle.setDocument = function( node ) { var doc = node ? node.ownerDocument || node : preferredDoc, parent = doc.defaultView; // If no document and documentElement is available, return if ( doc === document || doc.nodeType !== 9 || !doc.documentElement ) { return document; } // Set our document document = doc; docElem = doc.documentElement; // Support tests documentIsHTML = !isXML( doc ); // Support: IE>8 // If iframe document is assigned to "document" variable and if iframe has been reloaded, // IE will throw "permission denied" error when accessing "document" variable, see jQuery #13936 // IE6-8 do not support the defaultView property so parent will be undefined if ( parent && parent.attachEvent && parent !== parent.top ) { parent.attachEvent( "onbeforeunload", function() { setDocument(); }); } /* Attributes ---------------------------------------------------------------------- */ // Support: IE<8 // Verify that getAttribute really returns attributes and not properties (excepting IE8 booleans) support.attributes = assert(function( div ) { div.className = "i"; return !div.getAttribute("className"); }); /* getElement(s)By* ---------------------------------------------------------------------- */ // Check if getElementsByTagName("*") returns only elements support.getElementsByTagName = assert(function( div ) { div.appendChild( doc.createComment("") ); return !div.getElementsByTagName("*").length; }); // Check if getElementsByClassName can be trusted support.getElementsByClassName = assert(function( div ) { div.innerHTML = "<div class='a'></div><div class='a i'></div>"; // Support: Safari<4 // Catch class over-caching div.firstChild.className = "i"; // Support: Opera<10 // Catch gEBCN failure to find non-leading classes return div.getElementsByClassName("i").length === 2; }); // Support: IE<10 // Check if getElementById returns elements by name // The broken getElementById methods don't pick up programatically-set names, // so use a roundabout getElementsByName test support.getById = assert(function( div ) { docElem.appendChild( div ).id = expando; return !doc.getElementsByName || !doc.getElementsByName( expando ).length; }); // ID find and filter if ( support.getById ) { Expr.find["ID"] = function( id, context ) { if ( typeof context.getElementById !== strundefined && documentIsHTML ) { var m = context.getElementById( id ); // Check parentNode to catch when Blackberry 4.6 returns // nodes that are no longer in the document #6963 return m && m.parentNode ? [m] : []; } }; Expr.filter["ID"] = function( id ) { var attrId = id.replace( runescape, funescape ); return function( elem ) { return elem.getAttribute("id") === attrId; }; }; } else { // Support: IE6/7 // getElementById is not reliable as a find shortcut delete Expr.find["ID"]; Expr.filter["ID"] = function( id ) { var attrId = id.replace( runescape, funescape ); return function( elem ) { var node = typeof elem.getAttributeNode !== strundefined && elem.getAttributeNode("id"); return node && node.value === attrId; }; }; } // Tag Expr.find["TAG"] = support.getElementsByTagName ? function( tag, context ) { if ( typeof context.getElementsByTagName !== strundefined ) { return context.getElementsByTagName( tag ); } } : function( tag, context ) { var elem, tmp = [], i = 0, results = context.getElementsByTagName( tag ); // Filter out possible comments if ( tag === "*" ) { while ( (elem = results[i++]) ) { if ( elem.nodeType === 1 ) { tmp.push( elem ); } } return tmp; } return results; }; // Class Expr.find["CLASS"] = support.getElementsByClassName && function( className, context ) { if ( typeof context.getElementsByClassName !== strundefined && documentIsHTML ) { return context.getElementsByClassName( className ); } }; /* QSA/matchesSelector ---------------------------------------------------------------------- */ // QSA and matchesSelector support // matchesSelector(:active) reports false when true (IE9/Opera 11.5) rbuggyMatches = []; // qSa(:focus) reports false when true (Chrome 21) // We allow this because of a bug in IE8/9 that throws an error // whenever `document.activeElement` is accessed on an iframe // So, we allow :focus to pass through QSA all the time to avoid the IE error // See http://bugs.jquery.com/ticket/13378 rbuggyQSA = []; if ( (support.qsa = rnative.test( doc.querySelectorAll )) ) { // Build QSA regex // Regex strategy adopted from Diego Perini assert(function( div ) { // Select is set to empty string on purpose // This is to test IE's treatment of not explicitly // setting a boolean content attribute, // since its presence should be enough // http://bugs.jquery.com/ticket/12359 div.innerHTML = "<select><option selected=''></option></select>"; // Support: IE8 // Boolean attributes and "value" are not treated correctly if ( !div.querySelectorAll("[selected]").length ) { rbuggyQSA.push( "\\[" + whitespace + "*(?:value|" + booleans + ")" ); } // Webkit/Opera - :checked should return selected option elements // http://www.w3.org/TR/2011/REC-css3-selectors-20110929/#checked // IE8 throws error here and will not see later tests if ( !div.querySelectorAll(":checked").length ) { rbuggyQSA.push(":checked"); } }); assert(function( div ) { // Support: Opera 10-12/IE8 // ^= $= *= and empty values // Should not select anything // Support: Windows 8 Native Apps // The type attribute is restricted during .innerHTML assignment var input = doc.createElement("input"); input.setAttribute( "type", "hidden" ); div.appendChild( input ).setAttribute( "t", "" ); if ( div.querySelectorAll("[t^='']").length ) { rbuggyQSA.push( "[*^$]=" + whitespace + "*(?:''|\"\")" ); } // FF 3.5 - :enabled/:disabled and hidden elements (hidden elements are still enabled) // IE8 throws error here and will not see later tests if ( !div.querySelectorAll(":enabled").length ) { rbuggyQSA.push( ":enabled", ":disabled" ); } // Opera 10-11 does not throw on post-comma invalid pseudos div.querySelectorAll("*,:x"); rbuggyQSA.push(",.*:"); }); } if ( (support.matchesSelector = rnative.test( (matches = docElem.webkitMatchesSelector || docElem.mozMatchesSelector || docElem.oMatchesSelector || docElem.msMatchesSelector) )) ) { assert(function( div ) { // Check to see if it's possible to do matchesSelector // on a disconnected node (IE 9) support.disconnectedMatch = matches.call( div, "div" ); // This should fail with an exception // Gecko does not error, returns false instead matches.call( div, "[s!='']:x" ); rbuggyMatches.push( "!=", pseudos ); }); } rbuggyQSA = rbuggyQSA.length && new RegExp( rbuggyQSA.join("|") ); rbuggyMatches = rbuggyMatches.length && new RegExp( rbuggyMatches.join("|") ); /* Contains ---------------------------------------------------------------------- */ // Element contains another // Purposefully does not implement inclusive descendent // As in, an element does not contain itself contains = rnative.test( docElem.contains ) || docElem.compareDocumentPosition ? function( a, b ) { var adown = a.nodeType === 9 ? a.documentElement : a, bup = b && b.parentNode; return a === bup || !!( bup && bup.nodeType === 1 && ( adown.contains ? adown.contains( bup ) : a.compareDocumentPosition && a.compareDocumentPosition( bup ) & 16 )); } : function( a, b ) { if ( b ) { while ( (b = b.parentNode) ) { if ( b === a ) { return true; } } } return false; }; /* Sorting ---------------------------------------------------------------------- */ // Document order sorting sortOrder = docElem.compareDocumentPosition ? function( a, b ) { // Flag for duplicate removal if ( a === b ) { hasDuplicate = true; return 0; } var compare = b.compareDocumentPosition && a.compareDocumentPosition && a.compareDocumentPosition( b ); if ( compare ) { // Disconnected nodes if ( compare & 1 || (!support.sortDetached && b.compareDocumentPosition( a ) === compare) ) { // Choose the first element that is related to our preferred document if ( a === doc || contains(preferredDoc, a) ) { return -1; } if ( b === doc || contains(preferredDoc, b) ) { return 1; } // Maintain original order return sortInput ? ( indexOf.call( sortInput, a ) - indexOf.call( sortInput, b ) ) : 0; } return compare & 4 ? -1 : 1; } // Not directly comparable, sort on existence of method return a.compareDocumentPosition ? -1 : 1; } : function( a, b ) { var cur, i = 0, aup = a.parentNode, bup = b.parentNode, ap = [ a ], bp = [ b ]; // Exit early if the nodes are identical if ( a === b ) { hasDuplicate = true; return 0; // Parentless nodes are either documents or disconnected } else if ( !aup || !bup ) { return a === doc ? -1 : b === doc ? 1 : aup ? -1 : bup ? 1 : sortInput ? ( indexOf.call( sortInput, a ) - indexOf.call( sortInput, b ) ) : 0; // If the nodes are siblings, we can do a quick check } else if ( aup === bup ) { return siblingCheck( a, b ); } // Otherwise we need full lists of their ancestors for comparison cur = a; while ( (cur = cur.parentNode) ) { ap.unshift( cur ); } cur = b; while ( (cur = cur.parentNode) ) { bp.unshift( cur ); } // Walk down the tree looking for a discrepancy while ( ap[i] === bp[i] ) { i++; } return i ? // Do a sibling check if the nodes have a common ancestor siblingCheck( ap[i], bp[i] ) : // Otherwise nodes in our document sort first ap[i] === preferredDoc ? -1 : bp[i] === preferredDoc ? 1 : 0; }; return doc; }; Sizzle.matches = function( expr, elements ) { return Sizzle( expr, null, null, elements ); }; Sizzle.matchesSelector = function( elem, expr ) { // Set document vars if needed if ( ( elem.ownerDocument || elem ) !== document ) { setDocument( elem ); } // Make sure that attribute selectors are quoted expr = expr.replace( rattributeQuotes, "='$1']" ); if ( support.matchesSelector && documentIsHTML && ( !rbuggyMatches || !rbuggyMatches.test( expr ) ) && ( !rbuggyQSA || !rbuggyQSA.test( expr ) ) ) { try { var ret = matches.call( elem, expr ); // IE 9's matchesSelector returns false on disconnected nodes if ( ret || support.disconnectedMatch || // As well, disconnected nodes are said to be in a document // fragment in IE 9 elem.document && elem.document.nodeType !== 11 ) { return ret; } } catch(e) {} } return Sizzle( expr, document, null, [elem] ).length > 0; }; Sizzle.contains = function( context, elem ) { // Set document vars if needed if ( ( context.ownerDocument || context ) !== document ) { setDocument( context ); } return contains( context, elem ); }; Sizzle.attr = function( elem, name ) { // Set document vars if needed if ( ( elem.ownerDocument || elem ) !== document ) { setDocument( elem ); } var fn = Expr.attrHandle[ name.toLowerCase() ], // Don't get fooled by Object.prototype properties (jQuery #13807) val = fn && hasOwn.call( Expr.attrHandle, name.toLowerCase() ) ? fn( elem, name, !documentIsHTML ) : undefined; return val === undefined ? support.attributes || !documentIsHTML ? elem.getAttribute( name ) : (val = elem.getAttributeNode(name)) && val.specified ? val.value : null : val; }; Sizzle.error = function( msg ) { throw new Error( "Syntax error, unrecognized expression: " + msg ); }; /** * Document sorting and removing duplicates * @param {ArrayLike} results */ Sizzle.uniqueSort = function( results ) { var elem, duplicates = [], j = 0, i = 0; // Unless we *know* we can detect duplicates, assume their presence hasDuplicate = !support.detectDuplicates; sortInput = !support.sortStable && results.slice( 0 ); results.sort( sortOrder ); if ( hasDuplicate ) { while ( (elem = results[i++]) ) { if ( elem === results[ i ] ) { j = duplicates.push( i ); } } while ( j-- ) { results.splice( duplicates[ j ], 1 ); } } return results; }; /** * Utility function for retrieving the text value of an array of DOM nodes * @param {Array|Element} elem */ getText = Sizzle.getText = function( elem ) { var node, ret = "", i = 0, nodeType = elem.nodeType; if ( !nodeType ) { // If no nodeType, this is expected to be an array for ( ; (node = elem[i]); i++ ) { // Do not traverse comment nodes ret += getText( node ); } } else if ( nodeType === 1 || nodeType === 9 || nodeType === 11 ) { // Use textContent for elements // innerText usage removed for consistency of new lines (see #11153) if ( typeof elem.textContent === "string" ) { return elem.textContent; } else { // Traverse its children for ( elem = elem.firstChild; elem; elem = elem.nextSibling ) { ret += getText( elem ); } } } else if ( nodeType === 3 || nodeType === 4 ) { return elem.nodeValue; } // Do not include comment or processing instruction nodes return ret; }; Expr = Sizzle.selectors = { // Can be adjusted by the user cacheLength: 50, createPseudo: markFunction, match: matchExpr, attrHandle: {}, find: {}, relative: { ">": { dir: "parentNode", first: true }, " ": { dir: "parentNode" }, "+": { dir: "previousSibling", first: true }, "~": { dir: "previousSibling" } }, preFilter: { "ATTR": function( match ) { match[1] = match[1].replace( runescape, funescape ); // Move the given value to match[3] whether quoted or unquoted match[3] = ( match[4] || match[5] || "" ).replace( runescape, funescape ); if ( match[2] === "~=" ) { match[3] = " " + match[3] + " "; } return match.slice( 0, 4 ); }, "CHILD": function( match ) { /* matches from matchExpr["CHILD"] 1 type (only|nth|...) 2 what (child|of-type) 3 argument (even|odd|\d*|\d*n([+-]\d+)?|...) 4 xn-component of xn+y argument ([+-]?\d*n|) 5 sign of xn-component 6 x of xn-component 7 sign of y-component 8 y of y-component */ match[1] = match[1].toLowerCase(); if ( match[1].slice( 0, 3 ) === "nth" ) { // nth-* requires argument if ( !match[3] ) { Sizzle.error( match[0] ); } // numeric x and y parameters for Expr.filter.CHILD // remember that false/true cast respectively to 0/1 match[4] = +( match[4] ? match[5] + (match[6] || 1) : 2 * ( match[3] === "even" || match[3] === "odd" ) ); match[5] = +( ( match[7] + match[8] ) || match[3] === "odd" ); // other types prohibit arguments } else if ( match[3] ) { Sizzle.error( match[0] ); } return match; }, "PSEUDO": function( match ) { var excess, unquoted = !match[5] && match[2]; if ( matchExpr["CHILD"].test( match[0] ) ) { return null; } // Accept quoted arguments as-is if ( match[3] && match[4] !== undefined ) { match[2] = match[4]; // Strip excess characters from unquoted arguments } else if ( unquoted && rpseudo.test( unquoted ) && // Get excess from tokenize (recursively) (excess = tokenize( unquoted, true )) && // advance to the next closing parenthesis (excess = unquoted.indexOf( ")", unquoted.length - excess ) - unquoted.length) ) { // excess is a negative index match[0] = match[0].slice( 0, excess ); match[2] = unquoted.slice( 0, excess ); } // Return only captures needed by the pseudo filter method (type and argument) return match.slice( 0, 3 ); } }, filter: { "TAG": function( nodeNameSelector ) { var nodeName = nodeNameSelector.replace( runescape, funescape ).toLowerCase(); return nodeNameSelector === "*" ? function() { return true; } : function( elem ) { return elem.nodeName && elem.nodeName.toLowerCase() === nodeName; }; }, "CLASS": function( className ) { var pattern = classCache[ className + " " ]; return pattern || (pattern = new RegExp( "(^|" + whitespace + ")" + className + "(" + whitespace + "|$)" )) && classCache( className, function( elem ) { return pattern.test( typeof elem.className === "string" && elem.className || typeof elem.getAttribute !== strundefined && elem.getAttribute("class") || "" ); }); }, "ATTR": function( name, operator, check ) { return function( elem ) { var result = Sizzle.attr( elem, name ); if ( result == null ) { return operator === "!="; } if ( !operator ) { return true; } result += ""; return operator === "=" ? result === check : operator === "!=" ? result !== check : operator === "^=" ? check && result.indexOf( check ) === 0 : operator === "*=" ? check && result.indexOf( check ) > -1 : operator === "$=" ? check && result.slice( -check.length ) === check : operator === "~=" ? ( " " + result + " " ).indexOf( check ) > -1 : operator === "|=" ? result === check || result.slice( 0, check.length + 1 ) === check + "-" : false; }; }, "CHILD": function( type, what, argument, first, last ) { var simple = type.slice( 0, 3 ) !== "nth", forward = type.slice( -4 ) !== "last", ofType = what === "of-type"; return first === 1 && last === 0 ? // Shortcut for :nth-*(n) function( elem ) { return !!elem.parentNode; } : function( elem, context, xml ) { var cache, outerCache, node, diff, nodeIndex, start, dir = simple !== forward ? "nextSibling" : "previousSibling", parent = elem.parentNode, name = ofType && elem.nodeName.toLowerCase(), useCache = !xml && !ofType; if ( parent ) { // :(first|last|only)-(child|of-type) if ( simple ) { while ( dir ) { node = elem; while ( (node = node[ dir ]) ) { if ( ofType ? node.nodeName.toLowerCase() === name : node.nodeType === 1 ) { return false; } } // Reverse direction for :only-* (if we haven't yet done so) start = dir = type === "only" && !start && "nextSibling"; } return true; } start = [ forward ? parent.firstChild : parent.lastChild ]; // non-xml :nth-child(...) stores cache data on `parent` if ( forward && useCache ) { // Seek `elem` from a previously-cached index outerCache = parent[ expando ] || (parent[ expando ] = {}); cache = outerCache[ type ] || []; nodeIndex = cache[0] === dirruns && cache[1]; diff = cache[0] === dirruns && cache[2]; node = nodeIndex && parent.childNodes[ nodeIndex ]; while ( (node = ++nodeIndex && node && node[ dir ] || // Fallback to seeking `elem` from the start (diff = nodeIndex = 0) || start.pop()) ) { // When found, cache indexes on `parent` and break if ( node.nodeType === 1 && ++diff && node === elem ) { outerCache[ type ] = [ dirruns, nodeIndex, diff ]; break; } } // Use previously-cached element index if available } else if ( useCache && (cache = (elem[ expando ] || (elem[ expando ] = {}))[ type ]) && cache[0] === dirruns ) { diff = cache[1]; // xml :nth-child(...) or :nth-last-child(...) or :nth(-last)?-of-type(...) } else { // Use the same loop as above to seek `elem` from the start while ( (node = ++nodeIndex && node && node[ dir ] || (diff = nodeIndex = 0) || start.pop()) ) { if ( ( ofType ? node.nodeName.toLowerCase() === name : node.nodeType === 1 ) && ++diff ) { // Cache the index of each encountered element if ( useCache ) { (node[ expando ] || (node[ expando ] = {}))[ type ] = [ dirruns, diff ]; } if ( node === elem ) { break; } } } } // Incorporate the offset, then check against cycle size diff -= last; return diff === first || ( diff % first === 0 && diff / first >= 0 ); } }; }, "PSEUDO": function( pseudo, argument ) { // pseudo-class names are case-insensitive // http://www.w3.org/TR/selectors/#pseudo-classes // Prioritize by case sensitivity in case custom pseudos are added with uppercase letters // Remember that setFilters inherits from pseudos var args, fn = Expr.pseudos[ pseudo ] || Expr.setFilters[ pseudo.toLowerCase() ] || Sizzle.error( "unsupported pseudo: " + pseudo ); // The user may use createPseudo to indicate that // arguments are needed to create the filter function // just as Sizzle does if ( fn[ expando ] ) { return fn( argument ); } // But maintain support for old signatures if ( fn.length > 1 ) { args = [ pseudo, pseudo, "", argument ]; return Expr.setFilters.hasOwnProperty( pseudo.toLowerCase() ) ? markFunction(function( seed, matches ) { var idx, matched = fn( seed, argument ), i = matched.length; while ( i-- ) { idx = indexOf.call( seed, matched[i] ); seed[ idx ] = !( matches[ idx ] = matched[i] ); } }) : function( elem ) { return fn( elem, 0, args ); }; } return fn; } }, pseudos: { // Potentially complex pseudos "not": markFunction(function( selector ) { // Trim the selector passed to compile // to avoid treating leading and trailing // spaces as combinators var input = [], results = [], matcher = compile( selector.replace( rtrim, "$1" ) ); return matcher[ expando ] ? markFunction(function( seed, matches, context, xml ) { var elem, unmatched = matcher( seed, null, xml, [] ), i = seed.length; // Match elements unmatched by `matcher` while ( i-- ) { if ( (elem = unmatched[i]) ) { seed[i] = !(matches[i] = elem); } } }) : function( elem, context, xml ) { input[0] = elem; matcher( input, null, xml, results ); return !results.pop(); }; }), "has": markFunction(function( selector ) { return function( elem ) { return Sizzle( selector, elem ).length > 0; }; }), "contains": markFunction(function( text ) { return function( elem ) { return ( elem.textContent || elem.innerText || getText( elem ) ).indexOf( text ) > -1; }; }), // "Whether an element is represented by a :lang() selector // is based solely on the element's language value // being equal to the identifier C, // or beginning with the identifier C immediately followed by "-". // The matching of C against the element's language value is performed case-insensitively. // The identifier C does not have to be a valid language name." // http://www.w3.org/TR/selectors/#lang-pseudo "lang": markFunction( function( lang ) { // lang value must be a valid identifier if ( !ridentifier.test(lang || "") ) { Sizzle.error( "unsupported lang: " + lang ); } lang = lang.replace( runescape, funescape ).toLowerCase(); return function( elem ) { var elemLang; do { if ( (elemLang = documentIsHTML ? elem.lang : elem.getAttribute("xml:lang") || elem.getAttribute("lang")) ) { elemLang = elemLang.toLowerCase(); return elemLang === lang || elemLang.indexOf( lang + "-" ) === 0; } } while ( (elem = elem.parentNode) && elem.nodeType === 1 ); return false; }; }), // Miscellaneous "target": function( elem ) { var hash = window.location && window.location.hash; return hash && hash.slice( 1 ) === elem.id; }, "root": function( elem ) { return elem === docElem; }, "focus": function( elem ) { return elem === document.activeElement && (!document.hasFocus || document.hasFocus()) && !!(elem.type || elem.href || ~elem.tabIndex); }, // Boolean properties "enabled": function( elem ) { return elem.disabled === false; }, "disabled": function( elem ) { return elem.disabled === true; }, "checked": function( elem ) { // In CSS3, :checked should return both checked and selected elements // http://www.w3.org/TR/2011/REC-css3-selectors-20110929/#checked var nodeName = elem.nodeName.toLowerCase(); return (nodeName === "input" && !!elem.checked) || (nodeName === "option" && !!elem.selected); }, "selected": function( elem ) { // Accessing this property makes selected-by-default // options in Safari work properly if ( elem.parentNode ) { elem.parentNode.selectedIndex; } return elem.selected === true; }, // Contents "empty": function( elem ) { // http://www.w3.org/TR/selectors/#empty-pseudo // :empty is only affected by element nodes and content nodes(including text(3), cdata(4)), // not comment, processing instructions, or others // Thanks to Diego Perini for the nodeName shortcut // Greater than "@" means alpha characters (specifically not starting with "#" or "?") for ( elem = elem.firstChild; elem; elem = elem.nextSibling ) { if ( elem.nodeName > "@" || elem.nodeType === 3 || elem.nodeType === 4 ) { return false; } } return true; }, "parent": function( elem ) { return !Expr.pseudos["empty"]( elem ); }, // Element/input types "header": function( elem ) { return rheader.test( elem.nodeName ); }, "input": function( elem ) { return rinputs.test( elem.nodeName ); }, "button": function( elem ) { var name = elem.nodeName.toLowerCase(); return name === "input" && elem.type === "button" || name === "button"; }, "text": function( elem ) { var attr; // IE6 and 7 will map elem.type to 'text' for new HTML5 types (search, etc) // use getAttribute instead to test this case return elem.nodeName.toLowerCase() === "input" && elem.type === "text" && ( (attr = elem.getAttribute("type")) == null || attr.toLowerCase() === elem.type ); }, // Position-in-collection "first": createPositionalPseudo(function() { return [ 0 ]; }), "last": createPositionalPseudo(function( matchIndexes, length ) { return [ length - 1 ]; }), "eq": createPositionalPseudo(function( matchIndexes, length, argument ) { return [ argument < 0 ? argument + length : argument ]; }), "even": createPositionalPseudo(function( matchIndexes, length ) { var i = 0; for ( ; i < length; i += 2 ) { matchIndexes.push( i ); } return matchIndexes; }), "odd": createPositionalPseudo(function( matchIndexes, length ) { var i = 1; for ( ; i < length; i += 2 ) { matchIndexes.push( i ); } return matchIndexes; }), "lt": createPositionalPseudo(function( matchIndexes, length, argument ) { var i = argument < 0 ? argument + length : argument; for ( ; --i >= 0; ) { matchIndexes.push( i ); } return matchIndexes; }), "gt": createPositionalPseudo(function( matchIndexes, length, argument ) { var i = argument < 0 ? argument + length : argument; for ( ; ++i < length; ) { matchIndexes.push( i ); } return matchIndexes; }) } }; Expr.pseudos["nth"] = Expr.pseudos["eq"]; // Add button/input type pseudos for ( i in { radio: true, checkbox: true, file: true, password: true, image: true } ) { Expr.pseudos[ i ] = createInputPseudo( i ); } for ( i in { submit: true, reset: true } ) { Expr.pseudos[ i ] = createButtonPseudo( i ); } // Easy API for creating new setFilters function setFilters() {} setFilters.prototype = Expr.filters = Expr.pseudos; Expr.setFilters = new setFilters(); function tokenize( selector, parseOnly ) { var matched, match, tokens, type, soFar, groups, preFilters, cached = tokenCache[ selector + " " ]; if ( cached ) { return parseOnly ? 0 : cached.slice( 0 ); } soFar = selector; groups = []; preFilters = Expr.preFilter; while ( soFar ) { // Comma and first run if ( !matched || (match = rcomma.exec( soFar )) ) { if ( match ) { // Don't consume trailing commas as valid soFar = soFar.slice( match[0].length ) || soFar; } groups.push( tokens = [] ); } matched = false; // Combinators if ( (match = rcombinators.exec( soFar )) ) { matched = match.shift(); tokens.push({ value: matched, // Cast descendant combinators to space type: match[0].replace( rtrim, " " ) }); soFar = soFar.slice( matched.length ); } // Filters for ( type in Expr.filter ) { if ( (match = matchExpr[ type ].exec( soFar )) && (!preFilters[ type ] || (match = preFilters[ type ]( match ))) ) { matched = match.shift(); tokens.push({ value: matched, type: type, matches: match }); soFar = soFar.slice( matched.length ); } } if ( !matched ) { break; } } // Return the length of the invalid excess // if we're just parsing // Otherwise, throw an error or return tokens return parseOnly ? soFar.length : soFar ? Sizzle.error( selector ) : // Cache the tokens tokenCache( selector, groups ).slice( 0 ); } function toSelector( tokens ) { var i = 0, len = tokens.length, selector = ""; for ( ; i < len; i++ ) { selector += tokens[i].value; } return selector; } function addCombinator( matcher, combinator, base ) { var dir = combinator.dir, checkNonElements = base && dir === "parentNode", doneName = done++; return combinator.first ? // Check against closest ancestor/preceding element function( elem, context, xml ) { while ( (elem = elem[ dir ]) ) { if ( elem.nodeType === 1 || checkNonElements ) { return matcher( elem, context, xml ); } } } : // Check against all ancestor/preceding elements function( elem, context, xml ) { var data, cache, outerCache, dirkey = dirruns + " " + doneName; // We can't set arbitrary data on XML nodes, so they don't benefit from dir caching if ( xml ) { while ( (elem = elem[ dir ]) ) { if ( elem.nodeType === 1 || checkNonElements ) { if ( matcher( elem, context, xml ) ) { return true; } } } } else { while ( (elem = elem[ dir ]) ) { if ( elem.nodeType === 1 || checkNonElements ) { outerCache = elem[ expando ] || (elem[ expando ] = {}); if ( (cache = outerCache[ dir ]) && cache[0] === dirkey ) { if ( (data = cache[1]) === true || data === cachedruns ) { return data === true; } } else { cache = outerCache[ dir ] = [ dirkey ]; cache[1] = matcher( elem, context, xml ) || cachedruns; if ( cache[1] === true ) { return true; } } } } } }; } function elementMatcher( matchers ) { return matchers.length > 1 ? function( elem, context, xml ) { var i = matchers.length; while ( i-- ) { if ( !matchers[i]( elem, context, xml ) ) { return false; } } return true; } : matchers[0]; } function condense( unmatched, map, filter, context, xml ) { var elem, newUnmatched = [], i = 0, len = unmatched.length, mapped = map != null; for ( ; i < len; i++ ) { if ( (elem = unmatched[i]) ) { if ( !filter || filter( elem, context, xml ) ) { newUnmatched.push( elem ); if ( mapped ) { map.push( i ); } } } } return newUnmatched; } function setMatcher( preFilter, selector, matcher, postFilter, postFinder, postSelector ) { if ( postFilter && !postFilter[ expando ] ) { postFilter = setMatcher( postFilter ); } if ( postFinder && !postFinder[ expando ] ) { postFinder = setMatcher( postFinder, postSelector ); } return markFunction(function( seed, results, context, xml ) { var temp, i, elem, preMap = [], postMap = [], preexisting = results.length, // Get initial elements from seed or context elems = seed || multipleContexts( selector || "*", context.nodeType ? [ context ] : context, [] ), // Prefilter to get matcher input, preserving a map for seed-results synchronization matcherIn = preFilter && ( seed || !selector ) ? condense( elems, preMap, preFilter, context, xml ) : elems, matcherOut = matcher ? // If we have a postFinder, or filtered seed, or non-seed postFilter or preexisting results, postFinder || ( seed ? preFilter : preexisting || postFilter ) ? // ...intermediate processing is necessary [] : // ...otherwise use results directly results : matcherIn; // Find primary matches if ( matcher ) { matcher( matcherIn, matcherOut, context, xml ); } // Apply postFilter if ( postFilter ) { temp = condense( matcherOut, postMap ); postFilter( temp, [], context, xml ); // Un-match failing elements by moving them back to matcherIn i = temp.length; while ( i-- ) { if ( (elem = temp[i]) ) { matcherOut[ postMap[i] ] = !(matcherIn[ postMap[i] ] = elem); } } } if ( seed ) { if ( postFinder || preFilter ) { if ( postFinder ) { // Get the final matcherOut by condensing this intermediate into postFinder contexts temp = []; i = matcherOut.length; while ( i-- ) { if ( (elem = matcherOut[i]) ) { // Restore matcherIn since elem is not yet a final match temp.push( (matcherIn[i] = elem) ); } } postFinder( null, (matcherOut = []), temp, xml ); } // Move matched elements from seed to results to keep them synchronized i = matcherOut.length; while ( i-- ) { if ( (elem = matcherOut[i]) && (temp = postFinder ? indexOf.call( seed, elem ) : preMap[i]) > -1 ) { seed[temp] = !(results[temp] = elem); } } } // Add elements to results, through postFinder if defined } else { matcherOut = condense( matcherOut === results ? matcherOut.splice( preexisting, matcherOut.length ) : matcherOut ); if ( postFinder ) { postFinder( null, results, matcherOut, xml ); } else { push.apply( results, matcherOut ); } } }); } function matcherFromTokens( tokens ) { var checkContext, matcher, j, len = tokens.length, leadingRelative = Expr.relative[ tokens[0].type ], implicitRelative = leadingRelative || Expr.relative[" "], i = leadingRelative ? 1 : 0, // The foundational matcher ensures that elements are reachable from top-level context(s) matchContext = addCombinator( function( elem ) { return elem === checkContext; }, implicitRelative, true ), matchAnyContext = addCombinator( function( elem ) { return indexOf.call( checkContext, elem ) > -1; }, implicitRelative, true ), matchers = [ function( elem, context, xml ) { return ( !leadingRelative && ( xml || context !== outermostContext ) ) || ( (checkContext = context).nodeType ? matchContext( elem, context, xml ) : matchAnyContext( elem, context, xml ) ); } ]; for ( ; i < len; i++ ) { if ( (matcher = Expr.relative[ tokens[i].type ]) ) { matchers = [ addCombinator(elementMatcher( matchers ), matcher) ]; } else { matcher = Expr.filter[ tokens[i].type ].apply( null, tokens[i].matches ); // Return special upon seeing a positional matcher if ( matcher[ expando ] ) { // Find the next relative operator (if any) for proper handling j = ++i; for ( ; j < len; j++ ) { if ( Expr.relative[ tokens[j].type ] ) { break; } } return setMatcher( i > 1 && elementMatcher( matchers ), i > 1 && toSelector( // If the preceding token was a descendant combinator, insert an implicit any-element `*` tokens.slice( 0, i - 1 ).concat({ value: tokens[ i - 2 ].type === " " ? "*" : "" }) ).replace( rtrim, "$1" ), matcher, i < j && matcherFromTokens( tokens.slice( i, j ) ), j < len && matcherFromTokens( (tokens = tokens.slice( j )) ), j < len && toSelector( tokens ) ); } matchers.push( matcher ); } } return elementMatcher( matchers ); } function matcherFromGroupMatchers( elementMatchers, setMatchers ) { // A counter to specify which element is currently being matched var matcherCachedRuns = 0, bySet = setMatchers.length > 0, byElement = elementMatchers.length > 0, superMatcher = function( seed, context, xml, results, expandContext ) { var elem, j, matcher, setMatched = [], matchedCount = 0, i = "0", unmatched = seed && [], outermost = expandContext != null, contextBackup = outermostContext, // We must always have either seed elements or context elems = seed || byElement && Expr.find["TAG"]( "*", expandContext && context.parentNode || context ), // Use integer dirruns iff this is the outermost matcher dirrunsUnique = (dirruns += contextBackup == null ? 1 : Math.random() || 0.1); if ( outermost ) { outermostContext = context !== document && context; cachedruns = matcherCachedRuns; } // Add elements passing elementMatchers directly to results // Keep `i` a string if there are no elements so `matchedCount` will be "00" below for ( ; (elem = elems[i]) != null; i++ ) { if ( byElement && elem ) { j = 0; while ( (matcher = elementMatchers[j++]) ) { if ( matcher( elem, context, xml ) ) { results.push( elem ); break; } } if ( outermost ) { dirruns = dirrunsUnique; cachedruns = ++matcherCachedRuns; } } // Track unmatched elements for set filters if ( bySet ) { // They will have gone through all possible matchers if ( (elem = !matcher && elem) ) { matchedCount--; } // Lengthen the array for every element, matched or not if ( seed ) { unmatched.push( elem ); } } } // Apply set filters to unmatched elements matchedCount += i; if ( bySet && i !== matchedCount ) { j = 0; while ( (matcher = setMatchers[j++]) ) { matcher( unmatched, setMatched, context, xml ); } if ( seed ) { // Reintegrate element matches to eliminate the need for sorting if ( matchedCount > 0 ) { while ( i-- ) { if ( !(unmatched[i] || setMatched[i]) ) { setMatched[i] = pop.call( results ); } } } // Discard index placeholder values to get only actual matches setMatched = condense( setMatched ); } // Add matches to results push.apply( results, setMatched ); // Seedless set matches succeeding multiple successful matchers stipulate sorting if ( outermost && !seed && setMatched.length > 0 && ( matchedCount + setMatchers.length ) > 1 ) { Sizzle.uniqueSort( results ); } } // Override manipulation of globals by nested matchers if ( outermost ) { dirruns = dirrunsUnique; outermostContext = contextBackup; } return unmatched; }; return bySet ? markFunction( superMatcher ) : superMatcher; } compile = Sizzle.compile = function( selector, group /* Internal Use Only */ ) { var i, setMatchers = [], elementMatchers = [], cached = compilerCache[ selector + " " ]; if ( !cached ) { // Generate a function of recursive functions that can be used to check each element if ( !group ) { group = tokenize( selector ); } i = group.length; while ( i-- ) { cached = matcherFromTokens( group[i] ); if ( cached[ expando ] ) { setMatchers.push( cached ); } else { elementMatchers.push( cached ); } } // Cache the compiled function cached = compilerCache( selector, matcherFromGroupMatchers( elementMatchers, setMatchers ) ); } return cached; }; function multipleContexts( selector, contexts, results ) { var i = 0, len = contexts.length; for ( ; i < len; i++ ) { Sizzle( selector, contexts[i], results ); } return results; } function select( selector, context, results, seed ) { var i, tokens, token, type, find, match = tokenize( selector ); if ( !seed ) { // Try to minimize operations if there is only one group if ( match.length === 1 ) { // Take a shortcut and set the context if the root selector is an ID tokens = match[0] = match[0].slice( 0 ); if ( tokens.length > 2 && (token = tokens[0]).type === "ID" && support.getById && context.nodeType === 9 && documentIsHTML && Expr.relative[ tokens[1].type ] ) { context = ( Expr.find["ID"]( token.matches[0].replace(runescape, funescape), context ) || [] )[0]; if ( !context ) { return results; } selector = selector.slice( tokens.shift().value.length ); } // Fetch a seed set for right-to-left matching i = matchExpr["needsContext"].test( selector ) ? 0 : tokens.length; while ( i-- ) { token = tokens[i]; // Abort if we hit a combinator if ( Expr.relative[ (type = token.type) ] ) { break; } if ( (find = Expr.find[ type ]) ) { // Search, expanding context for leading sibling combinators if ( (seed = find( token.matches[0].replace( runescape, funescape ), rsibling.test( tokens[0].type ) && context.parentNode || context )) ) { // If seed is empty or no tokens remain, we can return early tokens.splice( i, 1 ); selector = seed.length && toSelector( tokens ); if ( !selector ) { push.apply( results, seed ); return results; } break; } } } } } // Compile and execute a filtering function // Provide `match` to avoid retokenization if we modified the selector above compile( selector, match )( seed, context, !documentIsHTML, results, rsibling.test( selector ) ); return results; } // One-time assignments // Sort stability support.sortStable = expando.split("").sort( sortOrder ).join("") === expando; // Support: Chrome<14 // Always assume duplicates if they aren't passed to the comparison function support.detectDuplicates = hasDuplicate; // Initialize against the default document setDocument(); // Support: Webkit<537.32 - Safari 6.0.3/Chrome 25 (fixed in Chrome 27) // Detached nodes confoundingly follow *each other* support.sortDetached = assert(function( div1 ) { // Should return 1, but returns 4 (following) return div1.compareDocumentPosition( document.createElement("div") ) & 1; }); // Support: IE<8 // Prevent attribute/property "interpolation" // http://msdn.microsoft.com/en-us/library/ms536429%28VS.85%29.aspx if ( !assert(function( div ) { div.innerHTML = "<a href='#'></a>"; return div.firstChild.getAttribute("href") === "#" ; }) ) { addHandle( "type|href|height|width", function( elem, name, isXML ) { if ( !isXML ) { return elem.getAttribute( name, name.toLowerCase() === "type" ? 1 : 2 ); } }); } // Support: IE<9 // Use defaultValue in place of getAttribute("value") if ( !support.attributes || !assert(function( div ) { div.innerHTML = "<input/>"; div.firstChild.setAttribute( "value", "" ); return div.firstChild.getAttribute( "value" ) === ""; }) ) { addHandle( "value", function( elem, name, isXML ) { if ( !isXML && elem.nodeName.toLowerCase() === "input" ) { return elem.defaultValue; } }); } // Support: IE<9 // Use getAttributeNode to fetch booleans when getAttribute lies if ( !assert(function( div ) { return div.getAttribute("disabled") == null; }) ) { addHandle( booleans, function( elem, name, isXML ) { var val; if ( !isXML ) { return (val = elem.getAttributeNode( name )) && val.specified ? val.value : elem[ name ] === true ? name.toLowerCase() : null; } }); } jQuery.find = Sizzle; jQuery.expr = Sizzle.selectors; jQuery.expr[":"] = jQuery.expr.pseudos; jQuery.unique = Sizzle.uniqueSort; jQuery.text = Sizzle.getText; jQuery.isXMLDoc = Sizzle.isXML; jQuery.contains = Sizzle.contains; })( window ); // String to Object options format cache var optionsCache = {}; // Convert String-formatted options into Object-formatted ones and store in cache function createOptions( options ) { var object = optionsCache[ options ] = {}; jQuery.each( options.match( core_rnotwhite ) || [], function( _, flag ) { object[ flag ] = true; }); return object; } /* * Create a callback list using the following parameters: * * options: an optional list of space-separated options that will change how * the callback list behaves or a more traditional option object * * By default a callback list will act like an event callback list and can be * "fired" multiple times. * * Possible options: * * once: will ensure the callback list can only be fired once (like a Deferred) * * memory: will keep track of previous values and will call any callback added * after the list has been fired right away with the latest "memorized" * values (like a Deferred) * * unique: will ensure a callback can only be added once (no duplicate in the list) * * stopOnFalse: interrupt callings when a callback returns false * */ jQuery.Callbacks = function( options ) { // Convert options from String-formatted to Object-formatted if needed // (we check in cache first) options = typeof options === "string" ? ( optionsCache[ options ] || createOptions( options ) ) : jQuery.extend( {}, options ); var // Last fire value (for non-forgettable lists) memory, // Flag to know if list was already fired fired, // Flag to know if list is currently firing firing, // First callback to fire (used internally by add and fireWith) firingStart, // End of the loop when firing firingLength, // Index of currently firing callback (modified by remove if needed) firingIndex, // Actual callback list list = [], // Stack of fire calls for repeatable lists stack = !options.once && [], // Fire callbacks fire = function( data ) { memory = options.memory && data; fired = true; firingIndex = firingStart || 0; firingStart = 0; firingLength = list.length; firing = true; for ( ; list && firingIndex < firingLength; firingIndex++ ) { if ( list[ firingIndex ].apply( data[ 0 ], data[ 1 ] ) === false && options.stopOnFalse ) { memory = false; // To prevent further calls using add break; } } firing = false; if ( list ) { if ( stack ) { if ( stack.length ) { fire( stack.shift() ); } } else if ( memory ) { list = []; } else { self.disable(); } } }, // Actual Callbacks object self = { // Add a callback or a collection of callbacks to the list add: function() { if ( list ) { // First, we save the current length var start = list.length; (function add( args ) { jQuery.each( args, function( _, arg ) { var type = jQuery.type( arg ); if ( type === "function" ) { if ( !options.unique || !self.has( arg ) ) { list.push( arg ); } } else if ( arg && arg.length && type !== "string" ) { // Inspect recursively add( arg ); } }); })( arguments ); // Do we need to add the callbacks to the // current firing batch? if ( firing ) { firingLength = list.length; // With memory, if we're not firing then // we should call right away } else if ( memory ) { firingStart = start; fire( memory ); } } return this; }, // Remove a callback from the list remove: function() { if ( list ) { jQuery.each( arguments, function( _, arg ) { var index; while( ( index = jQuery.inArray( arg, list, index ) ) > -1 ) { list.splice( index, 1 ); // Handle firing indexes if ( firing ) { if ( index <= firingLength ) { firingLength--; } if ( index <= firingIndex ) { firingIndex--; } } } }); } return this; }, // Check if a given callback is in the list. // If no argument is given, return whether or not list has callbacks attached. has: function( fn ) { return fn ? jQuery.inArray( fn, list ) > -1 : !!( list && list.length ); }, // Remove all callbacks from the list empty: function() { list = []; firingLength = 0; return this; }, // Have the list do nothing anymore disable: function() { list = stack = memory = undefined; return this; }, // Is it disabled? disabled: function() { return !list; }, // Lock the list in its current state lock: function() { stack = undefined; if ( !memory ) { self.disable(); } return this; }, // Is it locked? locked: function() { return !stack; }, // Call all callbacks with the given context and arguments fireWith: function( context, args ) { if ( list && ( !fired || stack ) ) { args = args || []; args = [ context, args.slice ? args.slice() : args ]; if ( firing ) { stack.push( args ); } else { fire( args ); } } return this; }, // Call all the callbacks with the given arguments fire: function() { self.fireWith( this, arguments ); return this; }, // To know if the callbacks have already been called at least once fired: function() { return !!fired; } }; return self; }; jQuery.extend({ Deferred: function( func ) { var tuples = [ // action, add listener, listener list, final state [ "resolve", "done", jQuery.Callbacks("once memory"), "resolved" ], [ "reject", "fail", jQuery.Callbacks("once memory"), "rejected" ], [ "notify", "progress", jQuery.Callbacks("memory") ] ], state = "pending", promise = { state: function() { return state; }, always: function() { deferred.done( arguments ).fail( arguments ); return this; }, then: function( /* fnDone, fnFail, fnProgress */ ) { var fns = arguments; return jQuery.Deferred(function( newDefer ) { jQuery.each( tuples, function( i, tuple ) { var action = tuple[ 0 ], fn = jQuery.isFunction( fns[ i ] ) && fns[ i ]; // deferred[ done | fail | progress ] for forwarding actions to newDefer deferred[ tuple[1] ](function() { var returned = fn && fn.apply( this, arguments ); if ( returned && jQuery.isFunction( returned.promise ) ) { returned.promise() .done( newDefer.resolve ) .fail( newDefer.reject ) .progress( newDefer.notify ); } else { newDefer[ action + "With" ]( this === promise ? newDefer.promise() : this, fn ? [ returned ] : arguments ); } }); }); fns = null; }).promise(); }, // Get a promise for this deferred // If obj is provided, the promise aspect is added to the object promise: function( obj ) { return obj != null ? jQuery.extend( obj, promise ) : promise; } }, deferred = {}; // Keep pipe for back-compat promise.pipe = promise.then; // Add list-specific methods jQuery.each( tuples, function( i, tuple ) { var list = tuple[ 2 ], stateString = tuple[ 3 ]; // promise[ done | fail | progress ] = list.add promise[ tuple[1] ] = list.add; // Handle state if ( stateString ) { list.add(function() { // state = [ resolved | rejected ] state = stateString; // [ reject_list | resolve_list ].disable; progress_list.lock }, tuples[ i ^ 1 ][ 2 ].disable, tuples[ 2 ][ 2 ].lock ); } // deferred[ resolve | reject | notify ] deferred[ tuple[0] ] = function() { deferred[ tuple[0] + "With" ]( this === deferred ? promise : this, arguments ); return this; }; deferred[ tuple[0] + "With" ] = list.fireWith; }); // Make the deferred a promise promise.promise( deferred ); // Call given func if any if ( func ) { func.call( deferred, deferred ); } // All done! return deferred; }, // Deferred helper when: function( subordinate /* , ..., subordinateN */ ) { var i = 0, resolveValues = core_slice.call( arguments ), length = resolveValues.length, // the count of uncompleted subordinates remaining = length !== 1 || ( subordinate && jQuery.isFunction( subordinate.promise ) ) ? length : 0, // the master Deferred. If resolveValues consist of only a single Deferred, just use that. deferred = remaining === 1 ? subordinate : jQuery.Deferred(), // Update function for both resolve and progress values updateFunc = function( i, contexts, values ) { return function( value ) { contexts[ i ] = this; values[ i ] = arguments.length > 1 ? core_slice.call( arguments ) : value; if( values === progressValues ) { deferred.notifyWith( contexts, values ); } else if ( !( --remaining ) ) { deferred.resolveWith( contexts, values ); } }; }, progressValues, progressContexts, resolveContexts; // add listeners to Deferred subordinates; treat others as resolved if ( length > 1 ) { progressValues = new Array( length ); progressContexts = new Array( length ); resolveContexts = new Array( length ); for ( ; i < length; i++ ) { if ( resolveValues[ i ] && jQuery.isFunction( resolveValues[ i ].promise ) ) { resolveValues[ i ].promise() .done( updateFunc( i, resolveContexts, resolveValues ) ) .fail( deferred.reject ) .progress( updateFunc( i, progressContexts, progressValues ) ); } else { --remaining; } } } // if we're not waiting on anything, resolve the master if ( !remaining ) { deferred.resolveWith( resolveContexts, resolveValues ); } return deferred.promise(); } }); jQuery.support = (function( support ) { var input = document.createElement("input"), fragment = document.createDocumentFragment(), div = document.createElement("div"), select = document.createElement("select"), opt = select.appendChild( document.createElement("option") ); // Finish early in limited environments if ( !input.type ) { return support; } input.type = "checkbox"; // Support: Safari 5.1, iOS 5.1, Android 4.x, Android 2.3 // Check the default checkbox/radio value ("" on old WebKit; "on" elsewhere) support.checkOn = input.value !== ""; // Must access the parent to make an option select properly // Support: IE9, IE10 support.optSelected = opt.selected; // Will be defined later support.reliableMarginRight = true; support.boxSizingReliable = true; support.pixelPosition = false; // Make sure checked status is properly cloned // Support: IE9, IE10 input.checked = true; support.noCloneChecked = input.cloneNode( true ).checked; // Make sure that the options inside disabled selects aren't marked as disabled // (WebKit marks them as disabled) select.disabled = true; support.optDisabled = !opt.disabled; // Check if an input maintains its value after becoming a radio // Support: IE9, IE10 input = document.createElement("input"); input.value = "t"; input.type = "radio"; support.radioValue = input.value === "t"; // #11217 - WebKit loses check when the name is after the checked attribute input.setAttribute( "checked", "t" ); input.setAttribute( "name", "t" ); fragment.appendChild( input ); // Support: Safari 5.1, Android 4.x, Android 2.3 // old WebKit doesn't clone checked state correctly in fragments support.checkClone = fragment.cloneNode( true ).cloneNode( true ).lastChild.checked; // Support: Firefox, Chrome, Safari // Beware of CSP restrictions (https://developer.mozilla.org/en/Security/CSP) support.focusinBubbles = "onfocusin" in window; div.style.backgroundClip = "content-box"; div.cloneNode( true ).style.backgroundClip = ""; support.clearCloneStyle = div.style.backgroundClip === "content-box"; // Run tests that need a body at doc ready jQuery(function() { var container, marginDiv, // Support: Firefox, Android 2.3 (Prefixed box-sizing versions). divReset = "padding:0;margin:0;border:0;display:block;-webkit-box-sizing:content-box;-moz-box-sizing:content-box;box-sizing:content-box", body = document.getElementsByTagName("body")[ 0 ]; if ( !body ) { // Return for frameset docs that don't have a body return; } container = document.createElement("div"); container.style.cssText = "border:0;width:0;height:0;position:absolute;top:0;left:-9999px;margin-top:1px"; // Check box-sizing and margin behavior. body.appendChild( container ).appendChild( div ); div.innerHTML = ""; // Support: Firefox, Android 2.3 (Prefixed box-sizing versions). div.style.cssText = "-webkit-box-sizing:border-box;-moz-box-sizing:border-box;box-sizing:border-box;padding:1px;border:1px;display:block;width:4px;margin-top:1%;position:absolute;top:1%"; // Workaround failing boxSizing test due to offsetWidth returning wrong value // with some non-1 values of body zoom, ticket #13543 jQuery.swap( body, body.style.zoom != null ? { zoom: 1 } : {}, function() { support.boxSizing = div.offsetWidth === 4; }); // Use window.getComputedStyle because jsdom on node.js will break without it. if ( window.getComputedStyle ) { support.pixelPosition = ( window.getComputedStyle( div, null ) || {} ).top !== "1%"; support.boxSizingReliable = ( window.getComputedStyle( div, null ) || { width: "4px" } ).width === "4px"; // Support: Android 2.3 // Check if div with explicit width and no margin-right incorrectly // gets computed margin-right based on width of container. (#3333) // WebKit Bug 13343 - getComputedStyle returns wrong value for margin-right marginDiv = div.appendChild( document.createElement("div") ); marginDiv.style.cssText = div.style.cssText = divReset; marginDiv.style.marginRight = marginDiv.style.width = "0"; div.style.width = "1px"; support.reliableMarginRight = !parseFloat( ( window.getComputedStyle( marginDiv, null ) || {} ).marginRight ); } body.removeChild( container ); }); return support; })( {} ); /* Implementation Summary 1. Enforce API surface and semantic compatibility with 1.9.x branch 2. Improve the module's maintainability by reducing the storage paths to a single mechanism. 3. Use the same single mechanism to support "private" and "user" data. 4. _Never_ expose "private" data to user code (TODO: Drop _data, _removeData) 5. Avoid exposing implementation details on user objects (eg. expando properties) 6. Provide a clear path for implementation upgrade to WeakMap in 2014 */ var data_user, data_priv, rbrace = /(?:\{[\s\S]*\}|\[[\s\S]*\])$/, rmultiDash = /([A-Z])/g; function Data() { // Support: Android < 4, // Old WebKit does not have Object.preventExtensions/freeze method, // return new empty object instead with no [[set]] accessor Object.defineProperty( this.cache = {}, 0, { get: function() { return {}; } }); this.expando = jQuery.expando + Math.random(); } Data.uid = 1; Data.accepts = function( owner ) { // Accepts only: // - Node // - Node.ELEMENT_NODE // - Node.DOCUMENT_NODE // - Object // - Any return owner.nodeType ? owner.nodeType === 1 || owner.nodeType === 9 : true; }; Data.prototype = { key: function( owner ) { // We can accept data for non-element nodes in modern browsers, // but we should not, see #8335. // Always return the key for a frozen object. if ( !Data.accepts( owner ) ) { return 0; } var descriptor = {}, // Check if the owner object already has a cache key unlock = owner[ this.expando ]; // If not, create one if ( !unlock ) { unlock = Data.uid++; // Secure it in a non-enumerable, non-writable property try { descriptor[ this.expando ] = { value: unlock }; Object.defineProperties( owner, descriptor ); // Support: Android < 4 // Fallback to a less secure definition } catch ( e ) { descriptor[ this.expando ] = unlock; jQuery.extend( owner, descriptor ); } } // Ensure the cache object if ( !this.cache[ unlock ] ) { this.cache[ unlock ] = {}; } return unlock; }, set: function( owner, data, value ) { var prop, // There may be an unlock assigned to this node, // if there is no entry for this "owner", create one inline // and set the unlock as though an owner entry had always existed unlock = this.key( owner ), cache = this.cache[ unlock ]; // Handle: [ owner, key, value ] args if ( typeof data === "string" ) { cache[ data ] = value; // Handle: [ owner, { properties } ] args } else { // Fresh assignments by object are shallow copied if ( jQuery.isEmptyObject( cache ) ) { jQuery.extend( this.cache[ unlock ], data ); // Otherwise, copy the properties one-by-one to the cache object } else { for ( prop in data ) { cache[ prop ] = data[ prop ]; } } } return cache; }, get: function( owner, key ) { // Either a valid cache is found, or will be created. // New caches will be created and the unlock returned, // allowing direct access to the newly created // empty data object. A valid owner object must be provided. var cache = this.cache[ this.key( owner ) ]; return key === undefined ? cache : cache[ key ]; }, access: function( owner, key, value ) { var stored; // In cases where either: // // 1. No key was specified // 2. A string key was specified, but no value provided // // Take the "read" path and allow the get method to determine // which value to return, respectively either: // // 1. The entire cache object // 2. The data stored at the key // if ( key === undefined || ((key && typeof key === "string") && value === undefined) ) { stored = this.get( owner, key ); return stored !== undefined ? stored : this.get( owner, jQuery.camelCase(key) ); } // [*]When the key is not a string, or both a key and value // are specified, set or extend (existing objects) with either: // // 1. An object of properties // 2. A key and value // this.set( owner, key, value ); // Since the "set" path can have two possible entry points // return the expected data based on which path was taken[*] return value !== undefined ? value : key; }, remove: function( owner, key ) { var i, name, camel, unlock = this.key( owner ), cache = this.cache[ unlock ]; if ( key === undefined ) { this.cache[ unlock ] = {}; } else { // Support array or space separated string of keys if ( jQuery.isArray( key ) ) { // If "name" is an array of keys... // When data is initially created, via ("key", "val") signature, // keys will be converted to camelCase. // Since there is no way to tell _how_ a key was added, remove // both plain key and camelCase key. #12786 // This will only penalize the array argument path. name = key.concat( key.map( jQuery.camelCase ) ); } else { camel = jQuery.camelCase( key ); // Try the string as a key before any manipulation if ( key in cache ) { name = [ key, camel ]; } else { // If a key with the spaces exists, use it. // Otherwise, create an array by matching non-whitespace name = camel; name = name in cache ? [ name ] : ( name.match( core_rnotwhite ) || [] ); } } i = name.length; while ( i-- ) { delete cache[ name[ i ] ]; } } }, hasData: function( owner ) { return !jQuery.isEmptyObject( this.cache[ owner[ this.expando ] ] || {} ); }, discard: function( owner ) { if ( owner[ this.expando ] ) { delete this.cache[ owner[ this.expando ] ]; } } }; // These may be used throughout the jQuery core codebase data_user = new Data(); data_priv = new Data(); jQuery.extend({ acceptData: Data.accepts, hasData: function( elem ) { return data_user.hasData( elem ) || data_priv.hasData( elem ); }, data: function( elem, name, data ) { return data_user.access( elem, name, data ); }, removeData: function( elem, name ) { data_user.remove( elem, name ); }, // TODO: Now that all calls to _data and _removeData have been replaced // with direct calls to data_priv methods, these can be deprecated. _data: function( elem, name, data ) { return data_priv.access( elem, name, data ); }, _removeData: function( elem, name ) { data_priv.remove( elem, name ); } }); jQuery.fn.extend({ data: function( key, value ) { var attrs, name, elem = this[ 0 ], i = 0, data = null; // Gets all values if ( key === undefined ) { if ( this.length ) { data = data_user.get( elem ); if ( elem.nodeType === 1 && !data_priv.get( elem, "hasDataAttrs" ) ) { attrs = elem.attributes; for ( ; i < attrs.length; i++ ) { name = attrs[ i ].name; if ( name.indexOf( "data-" ) === 0 ) { name = jQuery.camelCase( name.slice(5) ); dataAttr( elem, name, data[ name ] ); } } data_priv.set( elem, "hasDataAttrs", true ); } } return data; } // Sets multiple values if ( typeof key === "object" ) { return this.each(function() { data_user.set( this, key ); }); } return jQuery.access( this, function( value ) { var data, camelKey = jQuery.camelCase( key ); // The calling jQuery object (element matches) is not empty // (and therefore has an element appears at this[ 0 ]) and the // `value` parameter was not undefined. An empty jQuery object // will result in `undefined` for elem = this[ 0 ] which will // throw an exception if an attempt to read a data cache is made. if ( elem && value === undefined ) { // Attempt to get data from the cache // with the key as-is data = data_user.get( elem, key ); if ( data !== undefined ) { return data; } // Attempt to get data from the cache // with the key camelized data = data_user.get( elem, camelKey ); if ( data !== undefined ) { return data; } // Attempt to "discover" the data in // HTML5 custom data-* attrs data = dataAttr( elem, camelKey, undefined ); if ( data !== undefined ) { return data; } // We tried really hard, but the data doesn't exist. return; } // Set the data... this.each(function() { // First, attempt to store a copy or reference of any // data that might've been store with a camelCased key. var data = data_user.get( this, camelKey ); // For HTML5 data-* attribute interop, we have to // store property names with dashes in a camelCase form. // This might not apply to all properties...* data_user.set( this, camelKey, value ); // *... In the case of properties that might _actually_ // have dashes, we need to also store a copy of that // unchanged property. if ( key.indexOf("-") !== -1 && data !== undefined ) { data_user.set( this, key, value ); } }); }, null, value, arguments.length > 1, null, true ); }, removeData: function( key ) { return this.each(function() { data_user.remove( this, key ); }); } }); function dataAttr( elem, key, data ) { var name; // If nothing was found internally, try to fetch any // data from the HTML5 data-* attribute if ( data === undefined && elem.nodeType === 1 ) { name = "data-" + key.replace( rmultiDash, "-$1" ).toLowerCase(); data = elem.getAttribute( name ); if ( typeof data === "string" ) { try { data = data === "true" ? true : data === "false" ? false : data === "null" ? null : // Only convert to a number if it doesn't change the string +data + "" === data ? +data : rbrace.test( data ) ? JSON.parse( data ) : data; } catch( e ) {} // Make sure we set the data so it isn't changed later data_user.set( elem, key, data ); } else { data = undefined; } } return data; } jQuery.extend({ queue: function( elem, type, data ) { var queue; if ( elem ) { type = ( type || "fx" ) + "queue"; queue = data_priv.get( elem, type ); // Speed up dequeue by getting out quickly if this is just a lookup if ( data ) { if ( !queue || jQuery.isArray( data ) ) { queue = data_priv.access( elem, type, jQuery.makeArray(data) ); } else { queue.push( data ); } } return queue || []; } }, dequeue: function( elem, type ) { type = type || "fx"; var queue = jQuery.queue( elem, type ), startLength = queue.length, fn = queue.shift(), hooks = jQuery._queueHooks( elem, type ), next = function() { jQuery.dequeue( elem, type ); }; // If the fx queue is dequeued, always remove the progress sentinel if ( fn === "inprogress" ) { fn = queue.shift(); startLength--; } if ( fn ) { // Add a progress sentinel to prevent the fx queue from being // automatically dequeued if ( type === "fx" ) { queue.unshift( "inprogress" ); } // clear up the last queue stop function delete hooks.stop; fn.call( elem, next, hooks ); } if ( !startLength && hooks ) { hooks.empty.fire(); } }, // not intended for public consumption - generates a queueHooks object, or returns the current one _queueHooks: function( elem, type ) { var key = type + "queueHooks"; return data_priv.get( elem, key ) || data_priv.access( elem, key, { empty: jQuery.Callbacks("once memory").add(function() { data_priv.remove( elem, [ type + "queue", key ] ); }) }); } }); jQuery.fn.extend({ queue: function( type, data ) { var setter = 2; if ( typeof type !== "string" ) { data = type; type = "fx"; setter--; } if ( arguments.length < setter ) { return jQuery.queue( this[0], type ); } return data === undefined ? this : this.each(function() { var queue = jQuery.queue( this, type, data ); // ensure a hooks for this queue jQuery._queueHooks( this, type ); if ( type === "fx" && queue[0] !== "inprogress" ) { jQuery.dequeue( this, type ); } }); }, dequeue: function( type ) { return this.each(function() { jQuery.dequeue( this, type ); }); }, // Based off of the plugin by Clint Helfers, with permission. // http://blindsignals.com/index.php/2009/07/jquery-delay/ delay: function( time, type ) { time = jQuery.fx ? jQuery.fx.speeds[ time ] || time : time; type = type || "fx"; return this.queue( type, function( next, hooks ) { var timeout = setTimeout( next, time ); hooks.stop = function() { clearTimeout( timeout ); }; }); }, clearQueue: function( type ) { return this.queue( type || "fx", [] ); }, // Get a promise resolved when queues of a certain type // are emptied (fx is the type by default) promise: function( type, obj ) { var tmp, count = 1, defer = jQuery.Deferred(), elements = this, i = this.length, resolve = function() { if ( !( --count ) ) { defer.resolveWith( elements, [ elements ] ); } }; if ( typeof type !== "string" ) { obj = type; type = undefined; } type = type || "fx"; while( i-- ) { tmp = data_priv.get( elements[ i ], type + "queueHooks" ); if ( tmp && tmp.empty ) { count++; tmp.empty.add( resolve ); } } resolve(); return defer.promise( obj ); } }); var nodeHook, boolHook, rclass = /[\t\r\n\f]/g, rreturn = /\r/g, rfocusable = /^(?:input|select|textarea|button)$/i; jQuery.fn.extend({ attr: function( name, value ) { return jQuery.access( this, jQuery.attr, name, value, arguments.length > 1 ); }, removeAttr: function( name ) { return this.each(function() { jQuery.removeAttr( this, name ); }); }, prop: function( name, value ) { return jQuery.access( this, jQuery.prop, name, value, arguments.length > 1 ); }, removeProp: function( name ) { return this.each(function() { delete this[ jQuery.propFix[ name ] || name ]; }); }, addClass: function( value ) { var classes, elem, cur, clazz, j, i = 0, len = this.length, proceed = typeof value === "string" && value; if ( jQuery.isFunction( value ) ) { return this.each(function( j ) { jQuery( this ).addClass( value.call( this, j, this.className ) ); }); } if ( proceed ) { // The disjunction here is for better compressibility (see removeClass) classes = ( value || "" ).match( core_rnotwhite ) || []; for ( ; i < len; i++ ) { elem = this[ i ]; cur = elem.nodeType === 1 && ( elem.className ? ( " " + elem.className + " " ).replace( rclass, " " ) : " " ); if ( cur ) { j = 0; while ( (clazz = classes[j++]) ) { if ( cur.indexOf( " " + clazz + " " ) < 0 ) { cur += clazz + " "; } } elem.className = jQuery.trim( cur ); } } } return this; }, removeClass: function( value ) { var classes, elem, cur, clazz, j, i = 0, len = this.length, proceed = arguments.length === 0 || typeof value === "string" && value; if ( jQuery.isFunction( value ) ) { return this.each(function( j ) { jQuery( this ).removeClass( value.call( this, j, this.className ) ); }); } if ( proceed ) { classes = ( value || "" ).match( core_rnotwhite ) || []; for ( ; i < len; i++ ) { elem = this[ i ]; // This expression is here for better compressibility (see addClass) cur = elem.nodeType === 1 && ( elem.className ? ( " " + elem.className + " " ).replace( rclass, " " ) : "" ); if ( cur ) { j = 0; while ( (clazz = classes[j++]) ) { // Remove *all* instances while ( cur.indexOf( " " + clazz + " " ) >= 0 ) { cur = cur.replace( " " + clazz + " ", " " ); } } elem.className = value ? jQuery.trim( cur ) : ""; } } } return this; }, toggleClass: function( value, stateVal ) { var type = typeof value; if ( typeof stateVal === "boolean" && type === "string" ) { return stateVal ? this.addClass( value ) : this.removeClass( value ); } if ( jQuery.isFunction( value ) ) { return this.each(function( i ) { jQuery( this ).toggleClass( value.call(this, i, this.className, stateVal), stateVal ); }); } return this.each(function() { if ( type === "string" ) { // toggle individual class names var className, i = 0, self = jQuery( this ), classNames = value.match( core_rnotwhite ) || []; while ( (className = classNames[ i++ ]) ) { // check each className given, space separated list if ( self.hasClass( className ) ) { self.removeClass( className ); } else { self.addClass( className ); } } // Toggle whole class name } else if ( type === core_strundefined || type === "boolean" ) { if ( this.className ) { // store className if set data_priv.set( this, "__className__", this.className ); } // If the element has a class name or if we're passed "false", // then remove the whole classname (if there was one, the above saved it). // Otherwise bring back whatever was previously saved (if anything), // falling back to the empty string if nothing was stored. this.className = this.className || value === false ? "" : data_priv.get( this, "__className__" ) || ""; } }); }, hasClass: function( selector ) { var className = " " + selector + " ", i = 0, l = this.length; for ( ; i < l; i++ ) { if ( this[i].nodeType === 1 && (" " + this[i].className + " ").replace(rclass, " ").indexOf( className ) >= 0 ) { return true; } } return false; }, val: function( value ) { var hooks, ret, isFunction, elem = this[0]; if ( !arguments.length ) { if ( elem ) { hooks = jQuery.valHooks[ elem.type ] || jQuery.valHooks[ elem.nodeName.toLowerCase() ]; if ( hooks && "get" in hooks && (ret = hooks.get( elem, "value" )) !== undefined ) { return ret; } ret = elem.value; return typeof ret === "string" ? // handle most common string cases ret.replace(rreturn, "") : // handle cases where value is null/undef or number ret == null ? "" : ret; } return; } isFunction = jQuery.isFunction( value ); return this.each(function( i ) { var val; if ( this.nodeType !== 1 ) { return; } if ( isFunction ) { val = value.call( this, i, jQuery( this ).val() ); } else { val = value; } // Treat null/undefined as ""; convert numbers to string if ( val == null ) { val = ""; } else if ( typeof val === "number" ) { val += ""; } else if ( jQuery.isArray( val ) ) { val = jQuery.map(val, function ( value ) { return value == null ? "" : value + ""; }); } hooks = jQuery.valHooks[ this.type ] || jQuery.valHooks[ this.nodeName.toLowerCase() ]; // If set returns undefined, fall back to normal setting if ( !hooks || !("set" in hooks) || hooks.set( this, val, "value" ) === undefined ) { this.value = val; } }); } }); jQuery.extend({ valHooks: { option: { get: function( elem ) { // attributes.value is undefined in Blackberry 4.7 but // uses .value. See #6932 var val = elem.attributes.value; return !val || val.specified ? elem.value : elem.text; } }, select: { get: function( elem ) { var value, option, options = elem.options, index = elem.selectedIndex, one = elem.type === "select-one" || index < 0, values = one ? null : [], max = one ? index + 1 : options.length, i = index < 0 ? max : one ? index : 0; // Loop through all the selected options for ( ; i < max; i++ ) { option = options[ i ]; // IE6-9 doesn't update selected after form reset (#2551) if ( ( option.selected || i === index ) && // Don't return options that are disabled or in a disabled optgroup ( jQuery.support.optDisabled ? !option.disabled : option.getAttribute("disabled") === null ) && ( !option.parentNode.disabled || !jQuery.nodeName( option.parentNode, "optgroup" ) ) ) { // Get the specific value for the option value = jQuery( option ).val(); // We don't need an array for one selects if ( one ) { return value; } // Multi-Selects return an array values.push( value ); } } return values; }, set: function( elem, value ) { var optionSet, option, options = elem.options, values = jQuery.makeArray( value ), i = options.length; while ( i-- ) { option = options[ i ]; if ( (option.selected = jQuery.inArray( jQuery(option).val(), values ) >= 0) ) { optionSet = true; } } // force browsers to behave consistently when non-matching value is set if ( !optionSet ) { elem.selectedIndex = -1; } return values; } } }, attr: function( elem, name, value ) { var hooks, ret, nType = elem.nodeType; // don't get/set attributes on text, comment and attribute nodes if ( !elem || nType === 3 || nType === 8 || nType === 2 ) { return; } // Fallback to prop when attributes are not supported if ( typeof elem.getAttribute === core_strundefined ) { return jQuery.prop( elem, name, value ); } // All attributes are lowercase // Grab necessary hook if one is defined if ( nType !== 1 || !jQuery.isXMLDoc( elem ) ) { name = name.toLowerCase(); hooks = jQuery.attrHooks[ name ] || ( jQuery.expr.match.bool.test( name ) ? boolHook : nodeHook ); } if ( value !== undefined ) { if ( value === null ) { jQuery.removeAttr( elem, name ); } else if ( hooks && "set" in hooks && (ret = hooks.set( elem, value, name )) !== undefined ) { return ret; } else { elem.setAttribute( name, value + "" ); return value; } } else if ( hooks && "get" in hooks && (ret = hooks.get( elem, name )) !== null ) { return ret; } else { ret = jQuery.find.attr( elem, name ); // Non-existent attributes return null, we normalize to undefined return ret == null ? undefined : ret; } }, removeAttr: function( elem, value ) { var name, propName, i = 0, attrNames = value && value.match( core_rnotwhite ); if ( attrNames && elem.nodeType === 1 ) { while ( (name = attrNames[i++]) ) { propName = jQuery.propFix[ name ] || name; // Boolean attributes get special treatment (#10870) if ( jQuery.expr.match.bool.test( name ) ) { // Set corresponding property to false elem[ propName ] = false; } elem.removeAttribute( name ); } } }, attrHooks: { type: { set: function( elem, value ) { if ( !jQuery.support.radioValue && value === "radio" && jQuery.nodeName(elem, "input") ) { // Setting the type on a radio button after the value resets the value in IE6-9 // Reset value to default in case type is set after value during creation var val = elem.value; elem.setAttribute( "type", value ); if ( val ) { elem.value = val; } return value; } } } }, propFix: { "for": "htmlFor", "class": "className" }, prop: function( elem, name, value ) { var ret, hooks, notxml, nType = elem.nodeType; // don't get/set properties on text, comment and attribute nodes if ( !elem || nType === 3 || nType === 8 || nType === 2 ) { return; } notxml = nType !== 1 || !jQuery.isXMLDoc( elem ); if ( notxml ) { // Fix name and attach hooks name = jQuery.propFix[ name ] || name; hooks = jQuery.propHooks[ name ]; } if ( value !== undefined ) { return hooks && "set" in hooks && (ret = hooks.set( elem, value, name )) !== undefined ? ret : ( elem[ name ] = value ); } else { return hooks && "get" in hooks && (ret = hooks.get( elem, name )) !== null ? ret : elem[ name ]; } }, propHooks: { tabIndex: { get: function( elem ) { return elem.hasAttribute( "tabindex" ) || rfocusable.test( elem.nodeName ) || elem.href ? elem.tabIndex : -1; } } } }); // Hooks for boolean attributes boolHook = { set: function( elem, value, name ) { if ( value === false ) { // Remove boolean attributes when set to false jQuery.removeAttr( elem, name ); } else { elem.setAttribute( name, name ); } return name; } }; jQuery.each( jQuery.expr.match.bool.source.match( /\w+/g ), function( i, name ) { var getter = jQuery.expr.attrHandle[ name ] || jQuery.find.attr; jQuery.expr.attrHandle[ name ] = function( elem, name, isXML ) { var fn = jQuery.expr.attrHandle[ name ], ret = isXML ? undefined : /* jshint eqeqeq: false */ // Temporarily disable this handler to check existence (jQuery.expr.attrHandle[ name ] = undefined) != getter( elem, name, isXML ) ? name.toLowerCase() : null; // Restore handler jQuery.expr.attrHandle[ name ] = fn; return ret; }; }); // Support: IE9+ // Selectedness for an option in an optgroup can be inaccurate if ( !jQuery.support.optSelected ) { jQuery.propHooks.selected = { get: function( elem ) { var parent = elem.parentNode; if ( parent && parent.parentNode ) { parent.parentNode.selectedIndex; } return null; } }; } jQuery.each([ "tabIndex", "readOnly", "maxLength", "cellSpacing", "cellPadding", "rowSpan", "colSpan", "useMap", "frameBorder", "contentEditable" ], function() { jQuery.propFix[ this.toLowerCase() ] = this; }); // Radios and checkboxes getter/setter jQuery.each([ "radio", "checkbox" ], function() { jQuery.valHooks[ this ] = { set: function( elem, value ) { if ( jQuery.isArray( value ) ) { return ( elem.checked = jQuery.inArray( jQuery(elem).val(), value ) >= 0 ); } } }; if ( !jQuery.support.checkOn ) { jQuery.valHooks[ this ].get = function( elem ) { // Support: Webkit // "" is returned instead of "on" if a value isn't specified return elem.getAttribute("value") === null ? "on" : elem.value; }; } }); var rkeyEvent = /^key/, rmouseEvent = /^(?:mouse|contextmenu)|click/, rfocusMorph = /^(?:focusinfocus|focusoutblur)$/, rtypenamespace = /^([^.]*)(?:\.(.+)|)$/; function returnTrue() { return true; } function returnFalse() { return false; } function safeActiveElement() { try { return document.activeElement; } catch ( err ) { } } /* * Helper functions for managing events -- not part of the public interface. * Props to Dean Edwards' addEvent library for many of the ideas. */ jQuery.event = { global: {}, add: function( elem, types, handler, data, selector ) { var handleObjIn, eventHandle, tmp, events, t, handleObj, special, handlers, type, namespaces, origType, elemData = data_priv.get( elem ); // Don't attach events to noData or text/comment nodes (but allow plain objects) if ( !elemData ) { return; } // Caller can pass in an object of custom data in lieu of the handler if ( handler.handler ) { handleObjIn = handler; handler = handleObjIn.handler; selector = handleObjIn.selector; } // Make sure that the handler has a unique ID, used to find/remove it later if ( !handler.guid ) { handler.guid = jQuery.guid++; } // Init the element's event structure and main handler, if this is the first if ( !(events = elemData.events) ) { events = elemData.events = {}; } if ( !(eventHandle = elemData.handle) ) { eventHandle = elemData.handle = function( e ) { // Discard the second event of a jQuery.event.trigger() and // when an event is called after a page has unloaded return typeof jQuery !== core_strundefined && (!e || jQuery.event.triggered !== e.type) ? jQuery.event.dispatch.apply( eventHandle.elem, arguments ) : undefined; }; // Add elem as a property of the handle fn to prevent a memory leak with IE non-native events eventHandle.elem = elem; } // Handle multiple events separated by a space types = ( types || "" ).match( core_rnotwhite ) || [""]; t = types.length; while ( t-- ) { tmp = rtypenamespace.exec( types[t] ) || []; type = origType = tmp[1]; namespaces = ( tmp[2] || "" ).split( "." ).sort(); // There *must* be a type, no attaching namespace-only handlers if ( !type ) { continue; } // If event changes its type, use the special event handlers for the changed type special = jQuery.event.special[ type ] || {}; // If selector defined, determine special event api type, otherwise given type type = ( selector ? special.delegateType : special.bindType ) || type; // Update special based on newly reset type special = jQuery.event.special[ type ] || {}; // handleObj is passed to all event handlers handleObj = jQuery.extend({ type: type, origType: origType, data: data, handler: handler, guid: handler.guid, selector: selector, needsContext: selector && jQuery.expr.match.needsContext.test( selector ), namespace: namespaces.join(".") }, handleObjIn ); // Init the event handler queue if we're the first if ( !(handlers = events[ type ]) ) { handlers = events[ type ] = []; handlers.delegateCount = 0; // Only use addEventListener if the special events handler returns false if ( !special.setup || special.setup.call( elem, data, namespaces, eventHandle ) === false ) { if ( elem.addEventListener ) { elem.addEventListener( type, eventHandle, false ); } } } if ( special.add ) { special.add.call( elem, handleObj ); if ( !handleObj.handler.guid ) { handleObj.handler.guid = handler.guid; } } // Add to the element's handler list, delegates in front if ( selector ) { handlers.splice( handlers.delegateCount++, 0, handleObj ); } else { handlers.push( handleObj ); } // Keep track of which events have ever been used, for event optimization jQuery.event.global[ type ] = true; } // Nullify elem to prevent memory leaks in IE elem = null; }, // Detach an event or set of events from an element remove: function( elem, types, handler, selector, mappedTypes ) { var j, origCount, tmp, events, t, handleObj, special, handlers, type, namespaces, origType, elemData = data_priv.hasData( elem ) && data_priv.get( elem ); if ( !elemData || !(events = elemData.events) ) { return; } // Once for each type.namespace in types; type may be omitted types = ( types || "" ).match( core_rnotwhite ) || [""]; t = types.length; while ( t-- ) { tmp = rtypenamespace.exec( types[t] ) || []; type = origType = tmp[1]; namespaces = ( tmp[2] || "" ).split( "." ).sort(); // Unbind all events (on this namespace, if provided) for the element if ( !type ) { for ( type in events ) { jQuery.event.remove( elem, type + types[ t ], handler, selector, true ); } continue; } special = jQuery.event.special[ type ] || {}; type = ( selector ? special.delegateType : special.bindType ) || type; handlers = events[ type ] || []; tmp = tmp[2] && new RegExp( "(^|\\.)" + namespaces.join("\\.(?:.*\\.|)") + "(\\.|$)" ); // Remove matching events origCount = j = handlers.length; while ( j-- ) { handleObj = handlers[ j ]; if ( ( mappedTypes || origType === handleObj.origType ) && ( !handler || handler.guid === handleObj.guid ) && ( !tmp || tmp.test( handleObj.namespace ) ) && ( !selector || selector === handleObj.selector || selector === "**" && handleObj.selector ) ) { handlers.splice( j, 1 ); if ( handleObj.selector ) { handlers.delegateCount--; } if ( special.remove ) { special.remove.call( elem, handleObj ); } } } // Remove generic event handler if we removed something and no more handlers exist // (avoids potential for endless recursion during removal of special event handlers) if ( origCount && !handlers.length ) { if ( !special.teardown || special.teardown.call( elem, namespaces, elemData.handle ) === false ) { jQuery.removeEvent( elem, type, elemData.handle ); } delete events[ type ]; } } // Remove the expando if it's no longer used if ( jQuery.isEmptyObject( events ) ) { delete elemData.handle; data_priv.remove( elem, "events" ); } }, trigger: function( event, data, elem, onlyHandlers ) { var i, cur, tmp, bubbleType, ontype, handle, special, eventPath = [ elem || document ], type = core_hasOwn.call( event, "type" ) ? event.type : event, namespaces = core_hasOwn.call( event, "namespace" ) ? event.namespace.split(".") : []; cur = tmp = elem = elem || document; // Don't do events on text and comment nodes if ( elem.nodeType === 3 || elem.nodeType === 8 ) { return; } // focus/blur morphs to focusin/out; ensure we're not firing them right now if ( rfocusMorph.test( type + jQuery.event.triggered ) ) { return; } if ( type.indexOf(".") >= 0 ) { // Namespaced trigger; create a regexp to match event type in handle() namespaces = type.split("."); type = namespaces.shift(); namespaces.sort(); } ontype = type.indexOf(":") < 0 && "on" + type; // Caller can pass in a jQuery.Event object, Object, or just an event type string event = event[ jQuery.expando ] ? event : new jQuery.Event( type, typeof event === "object" && event ); // Trigger bitmask: & 1 for native handlers; & 2 for jQuery (always true) event.isTrigger = onlyHandlers ? 2 : 3; event.namespace = namespaces.join("."); event.namespace_re = event.namespace ? new RegExp( "(^|\\.)" + namespaces.join("\\.(?:.*\\.|)") + "(\\.|$)" ) : null; // Clean up the event in case it is being reused event.result = undefined; if ( !event.target ) { event.target = elem; } // Clone any incoming data and prepend the event, creating the handler arg list data = data == null ? [ event ] : jQuery.makeArray( data, [ event ] ); // Allow special events to draw outside the lines special = jQuery.event.special[ type ] || {}; if ( !onlyHandlers && special.trigger && special.trigger.apply( elem, data ) === false ) { return; } // Determine event propagation path in advance, per W3C events spec (#9951) // Bubble up to document, then to window; watch for a global ownerDocument var (#9724) if ( !onlyHandlers && !special.noBubble && !jQuery.isWindow( elem ) ) { bubbleType = special.delegateType || type; if ( !rfocusMorph.test( bubbleType + type ) ) { cur = cur.parentNode; } for ( ; cur; cur = cur.parentNode ) { eventPath.push( cur ); tmp = cur; } // Only add window if we got to document (e.g., not plain obj or detached DOM) if ( tmp === (elem.ownerDocument || document) ) { eventPath.push( tmp.defaultView || tmp.parentWindow || window ); } } // Fire handlers on the event path i = 0; while ( (cur = eventPath[i++]) && !event.isPropagationStopped() ) { event.type = i > 1 ? bubbleType : special.bindType || type; // jQuery handler handle = ( data_priv.get( cur, "events" ) || {} )[ event.type ] && data_priv.get( cur, "handle" ); if ( handle ) { handle.apply( cur, data ); } // Native handler handle = ontype && cur[ ontype ]; if ( handle && jQuery.acceptData( cur ) && handle.apply && handle.apply( cur, data ) === false ) { event.preventDefault(); } } event.type = type; // If nobody prevented the default action, do it now if ( !onlyHandlers && !event.isDefaultPrevented() ) { if ( (!special._default || special._default.apply( eventPath.pop(), data ) === false) && jQuery.acceptData( elem ) ) { // Call a native DOM method on the target with the same name name as the event. // Don't do default actions on window, that's where global variables be (#6170) if ( ontype && jQuery.isFunction( elem[ type ] ) && !jQuery.isWindow( elem ) ) { // Don't re-trigger an onFOO event when we call its FOO() method tmp = elem[ ontype ]; if ( tmp ) { elem[ ontype ] = null; } // Prevent re-triggering of the same event, since we already bubbled it above jQuery.event.triggered = type; elem[ type ](); jQuery.event.triggered = undefined; if ( tmp ) { elem[ ontype ] = tmp; } } } } return event.result; }, dispatch: function( event ) { // Make a writable jQuery.Event from the native event object event = jQuery.event.fix( event ); var i, j, ret, matched, handleObj, handlerQueue = [], args = core_slice.call( arguments ), handlers = ( data_priv.get( this, "events" ) || {} )[ event.type ] || [], special = jQuery.event.special[ event.type ] || {}; // Use the fix-ed jQuery.Event rather than the (read-only) native event args[0] = event; event.delegateTarget = this; // Call the preDispatch hook for the mapped type, and let it bail if desired if ( special.preDispatch && special.preDispatch.call( this, event ) === false ) { return; } // Determine handlers handlerQueue = jQuery.event.handlers.call( this, event, handlers ); // Run delegates first; they may want to stop propagation beneath us i = 0; while ( (matched = handlerQueue[ i++ ]) && !event.isPropagationStopped() ) { event.currentTarget = matched.elem; j = 0; while ( (handleObj = matched.handlers[ j++ ]) && !event.isImmediatePropagationStopped() ) { // Triggered event must either 1) have no namespace, or // 2) have namespace(s) a subset or equal to those in the bound event (both can have no namespace). if ( !event.namespace_re || event.namespace_re.test( handleObj.namespace ) ) { event.handleObj = handleObj; event.data = handleObj.data; ret = ( (jQuery.event.special[ handleObj.origType ] || {}).handle || handleObj.handler ) .apply( matched.elem, args ); if ( ret !== undefined ) { if ( (event.result = ret) === false ) { event.preventDefault(); event.stopPropagation(); } } } } } // Call the postDispatch hook for the mapped type if ( special.postDispatch ) { special.postDispatch.call( this, event ); } return event.result; }, handlers: function( event, handlers ) { var i, matches, sel, handleObj, handlerQueue = [], delegateCount = handlers.delegateCount, cur = event.target; // Find delegate handlers // Black-hole SVG <use> instance trees (#13180) // Avoid non-left-click bubbling in Firefox (#3861) if ( delegateCount && cur.nodeType && (!event.button || event.type !== "click") ) { for ( ; cur !== this; cur = cur.parentNode || this ) { // Don't process clicks on disabled elements (#6911, #8165, #11382, #11764) if ( cur.disabled !== true || event.type !== "click" ) { matches = []; for ( i = 0; i < delegateCount; i++ ) { handleObj = handlers[ i ]; // Don't conflict with Object.prototype properties (#13203) sel = handleObj.selector + " "; if ( matches[ sel ] === undefined ) { matches[ sel ] = handleObj.needsContext ? jQuery( sel, this ).index( cur ) >= 0 : jQuery.find( sel, this, null, [ cur ] ).length; } if ( matches[ sel ] ) { matches.push( handleObj ); } } if ( matches.length ) { handlerQueue.push({ elem: cur, handlers: matches }); } } } } // Add the remaining (directly-bound) handlers if ( delegateCount < handlers.length ) { handlerQueue.push({ elem: this, handlers: handlers.slice( delegateCount ) }); } return handlerQueue; }, // Includes some event props shared by KeyEvent and MouseEvent props: "altKey bubbles cancelable ctrlKey currentTarget eventPhase metaKey relatedTarget shiftKey target timeStamp view which".split(" "), fixHooks: {}, keyHooks: { props: "char charCode key keyCode".split(" "), filter: function( event, original ) { // Add which for key events if ( event.which == null ) { event.which = original.charCode != null ? original.charCode : original.keyCode; } return event; } }, mouseHooks: { props: "button buttons clientX clientY offsetX offsetY pageX pageY screenX screenY toElement".split(" "), filter: function( event, original ) { var eventDoc, doc, body, button = original.button; // Calculate pageX/Y if missing and clientX/Y available if ( event.pageX == null && original.clientX != null ) { eventDoc = event.target.ownerDocument || document; doc = eventDoc.documentElement; body = eventDoc.body; event.pageX = original.clientX + ( doc && doc.scrollLeft || body && body.scrollLeft || 0 ) - ( doc && doc.clientLeft || body && body.clientLeft || 0 ); event.pageY = original.clientY + ( doc && doc.scrollTop || body && body.scrollTop || 0 ) - ( doc && doc.clientTop || body && body.clientTop || 0 ); } // Add which for click: 1 === left; 2 === middle; 3 === right // Note: button is not normalized, so don't use it if ( !event.which && button !== undefined ) { event.which = ( button & 1 ? 1 : ( button & 2 ? 3 : ( button & 4 ? 2 : 0 ) ) ); } return event; } }, fix: function( event ) { if ( event[ jQuery.expando ] ) { return event; } // Create a writable copy of the event object and normalize some properties var i, prop, copy, type = event.type, originalEvent = event, fixHook = this.fixHooks[ type ]; if ( !fixHook ) { this.fixHooks[ type ] = fixHook = rmouseEvent.test( type ) ? this.mouseHooks : rkeyEvent.test( type ) ? this.keyHooks : {}; } copy = fixHook.props ? this.props.concat( fixHook.props ) : this.props; event = new jQuery.Event( originalEvent ); i = copy.length; while ( i-- ) { prop = copy[ i ]; event[ prop ] = originalEvent[ prop ]; } // Support: Cordova 2.5 (WebKit) (#13255) // All events should have a target; Cordova deviceready doesn't if ( !event.target ) { event.target = document; } // Support: Safari 6.0+, Chrome < 28 // Target should not be a text node (#504, #13143) if ( event.target.nodeType === 3 ) { event.target = event.target.parentNode; } return fixHook.filter? fixHook.filter( event, originalEvent ) : event; }, special: { load: { // Prevent triggered image.load events from bubbling to window.load noBubble: true }, focus: { // Fire native event if possible so blur/focus sequence is correct trigger: function() { if ( this !== safeActiveElement() && this.focus ) { this.focus(); return false; } }, delegateType: "focusin" }, blur: { trigger: function() { if ( this === safeActiveElement() && this.blur ) { this.blur(); return false; } }, delegateType: "focusout" }, click: { // For checkbox, fire native event so checked state will be right trigger: function() { if ( this.type === "checkbox" && this.click && jQuery.nodeName( this, "input" ) ) { this.click(); return false; } }, // For cross-browser consistency, don't fire native .click() on links _default: function( event ) { return jQuery.nodeName( event.target, "a" ); } }, beforeunload: { postDispatch: function( event ) { // Support: Firefox 20+ // Firefox doesn't alert if the returnValue field is not set. if ( event.result !== undefined ) { event.originalEvent.returnValue = event.result; } } } }, simulate: function( type, elem, event, bubble ) { // Piggyback on a donor event to simulate a different one. // Fake originalEvent to avoid donor's stopPropagation, but if the // simulated event prevents default then we do the same on the donor. var e = jQuery.extend( new jQuery.Event(), event, { type: type, isSimulated: true, originalEvent: {} } ); if ( bubble ) { jQuery.event.trigger( e, null, elem ); } else { jQuery.event.dispatch.call( elem, e ); } if ( e.isDefaultPrevented() ) { event.preventDefault(); } } }; jQuery.removeEvent = function( elem, type, handle ) { if ( elem.removeEventListener ) { elem.removeEventListener( type, handle, false ); } }; jQuery.Event = function( src, props ) { // Allow instantiation without the 'new' keyword if ( !(this instanceof jQuery.Event) ) { return new jQuery.Event( src, props ); } // Event object if ( src && src.type ) { this.originalEvent = src; this.type = src.type; // Events bubbling up the document may have been marked as prevented // by a handler lower down the tree; reflect the correct value. this.isDefaultPrevented = ( src.defaultPrevented || src.getPreventDefault && src.getPreventDefault() ) ? returnTrue : returnFalse; // Event type } else { this.type = src; } // Put explicitly provided properties onto the event object if ( props ) { jQuery.extend( this, props ); } // Create a timestamp if incoming event doesn't have one this.timeStamp = src && src.timeStamp || jQuery.now(); // Mark it as fixed this[ jQuery.expando ] = true; }; // jQuery.Event is based on DOM3 Events as specified by the ECMAScript Language Binding // http://www.w3.org/TR/2003/WD-DOM-Level-3-Events-20030331/ecma-script-binding.html jQuery.Event.prototype = { isDefaultPrevented: returnFalse, isPropagationStopped: returnFalse, isImmediatePropagationStopped: returnFalse, preventDefault: function() { var e = this.originalEvent; this.isDefaultPrevented = returnTrue; if ( e && e.preventDefault ) { e.preventDefault(); } }, stopPropagation: function() { var e = this.originalEvent; this.isPropagationStopped = returnTrue; if ( e && e.stopPropagation ) { e.stopPropagation(); } }, stopImmediatePropagation: function() { this.isImmediatePropagationStopped = returnTrue; this.stopPropagation(); } }; // Create mouseenter/leave events using mouseover/out and event-time checks // Support: Chrome 15+ jQuery.each({ mouseenter: "mouseover", mouseleave: "mouseout" }, function( orig, fix ) { jQuery.event.special[ orig ] = { delegateType: fix, bindType: fix, handle: function( event ) { var ret, target = this, related = event.relatedTarget, handleObj = event.handleObj; // For mousenter/leave call the handler if related is outside the target. // NB: No relatedTarget if the mouse left/entered the browser window if ( !related || (related !== target && !jQuery.contains( target, related )) ) { event.type = handleObj.origType; ret = handleObj.handler.apply( this, arguments ); event.type = fix; } return ret; } }; }); // Create "bubbling" focus and blur events // Support: Firefox, Chrome, Safari if ( !jQuery.support.focusinBubbles ) { jQuery.each({ focus: "focusin", blur: "focusout" }, function( orig, fix ) { // Attach a single capturing handler while someone wants focusin/focusout var attaches = 0, handler = function( event ) { jQuery.event.simulate( fix, event.target, jQuery.event.fix( event ), true ); }; jQuery.event.special[ fix ] = { setup: function() { if ( attaches++ === 0 ) { document.addEventListener( orig, handler, true ); } }, teardown: function() { if ( --attaches === 0 ) { document.removeEventListener( orig, handler, true ); } } }; }); } jQuery.fn.extend({ on: function( types, selector, data, fn, /*INTERNAL*/ one ) { var origFn, type; // Types can be a map of types/handlers if ( typeof types === "object" ) { // ( types-Object, selector, data ) if ( typeof selector !== "string" ) { // ( types-Object, data ) data = data || selector; selector = undefined; } for ( type in types ) { this.on( type, selector, data, types[ type ], one ); } return this; } if ( data == null && fn == null ) { // ( types, fn ) fn = selector; data = selector = undefined; } else if ( fn == null ) { if ( typeof selector === "string" ) { // ( types, selector, fn ) fn = data; data = undefined; } else { // ( types, data, fn ) fn = data; data = selector; selector = undefined; } } if ( fn === false ) { fn = returnFalse; } else if ( !fn ) { return this; } if ( one === 1 ) { origFn = fn; fn = function( event ) { // Can use an empty set, since event contains the info jQuery().off( event ); return origFn.apply( this, arguments ); }; // Use same guid so caller can remove using origFn fn.guid = origFn.guid || ( origFn.guid = jQuery.guid++ ); } return this.each( function() { jQuery.event.add( this, types, fn, data, selector ); }); }, one: function( types, selector, data, fn ) { return this.on( types, selector, data, fn, 1 ); }, off: function( types, selector, fn ) { var handleObj, type; if ( types && types.preventDefault && types.handleObj ) { // ( event ) dispatched jQuery.Event handleObj = types.handleObj; jQuery( types.delegateTarget ).off( handleObj.namespace ? handleObj.origType + "." + handleObj.namespace : handleObj.origType, handleObj.selector, handleObj.handler ); return this; } if ( typeof types === "object" ) { // ( types-object [, selector] ) for ( type in types ) { this.off( type, selector, types[ type ] ); } return this; } if ( selector === false || typeof selector === "function" ) { // ( types [, fn] ) fn = selector; selector = undefined; } if ( fn === false ) { fn = returnFalse; } return this.each(function() { jQuery.event.remove( this, types, fn, selector ); }); }, trigger: function( type, data ) { return this.each(function() { jQuery.event.trigger( type, data, this ); }); }, triggerHandler: function( type, data ) { var elem = this[0]; if ( elem ) { return jQuery.event.trigger( type, data, elem, true ); } } }); var isSimple = /^.[^:#\[\.,]*$/, rparentsprev = /^(?:parents|prev(?:Until|All))/, rneedsContext = jQuery.expr.match.needsContext, // methods guaranteed to produce a unique set when starting from a unique set guaranteedUnique = { children: true, contents: true, next: true, prev: true }; jQuery.fn.extend({ find: function( selector ) { var i, ret = [], self = this, len = self.length; if ( typeof selector !== "string" ) { return this.pushStack( jQuery( selector ).filter(function() { for ( i = 0; i < len; i++ ) { if ( jQuery.contains( self[ i ], this ) ) { return true; } } }) ); } for ( i = 0; i < len; i++ ) { jQuery.find( selector, self[ i ], ret ); } // Needed because $( selector, context ) becomes $( context ).find( selector ) ret = this.pushStack( len > 1 ? jQuery.unique( ret ) : ret ); ret.selector = this.selector ? this.selector + " " + selector : selector; return ret; }, has: function( target ) { var targets = jQuery( target, this ), l = targets.length; return this.filter(function() { var i = 0; for ( ; i < l; i++ ) { if ( jQuery.contains( this, targets[i] ) ) { return true; } } }); }, not: function( selector ) { return this.pushStack( winnow(this, selector || [], true) ); }, filter: function( selector ) { return this.pushStack( winnow(this, selector || [], false) ); }, is: function( selector ) { return !!winnow( this, // If this is a positional/relative selector, check membership in the returned set // so $("p:first").is("p:last") won't return true for a doc with two "p". typeof selector === "string" && rneedsContext.test( selector ) ? jQuery( selector ) : selector || [], false ).length; }, closest: function( selectors, context ) { var cur, i = 0, l = this.length, matched = [], pos = ( rneedsContext.test( selectors ) || typeof selectors !== "string" ) ? jQuery( selectors, context || this.context ) : 0; for ( ; i < l; i++ ) { for ( cur = this[i]; cur && cur !== context; cur = cur.parentNode ) { // Always skip document fragments if ( cur.nodeType < 11 && (pos ? pos.index(cur) > -1 : // Don't pass non-elements to Sizzle cur.nodeType === 1 && jQuery.find.matchesSelector(cur, selectors)) ) { cur = matched.push( cur ); break; } } } return this.pushStack( matched.length > 1 ? jQuery.unique( matched ) : matched ); }, // Determine the position of an element within // the matched set of elements index: function( elem ) { // No argument, return index in parent if ( !elem ) { return ( this[ 0 ] && this[ 0 ].parentNode ) ? this.first().prevAll().length : -1; } // index in selector if ( typeof elem === "string" ) { return core_indexOf.call( jQuery( elem ), this[ 0 ] ); } // Locate the position of the desired element return core_indexOf.call( this, // If it receives a jQuery object, the first element is used elem.jquery ? elem[ 0 ] : elem ); }, add: function( selector, context ) { var set = typeof selector === "string" ? jQuery( selector, context ) : jQuery.makeArray( selector && selector.nodeType ? [ selector ] : selector ), all = jQuery.merge( this.get(), set ); return this.pushStack( jQuery.unique(all) ); }, addBack: function( selector ) { return this.add( selector == null ? this.prevObject : this.prevObject.filter(selector) ); } }); function sibling( cur, dir ) { while ( (cur = cur[dir]) && cur.nodeType !== 1 ) {} return cur; } jQuery.each({ parent: function( elem ) { var parent = elem.parentNode; return parent && parent.nodeType !== 11 ? parent : null; }, parents: function( elem ) { return jQuery.dir( elem, "parentNode" ); }, parentsUntil: function( elem, i, until ) { return jQuery.dir( elem, "parentNode", until ); }, next: function( elem ) { return sibling( elem, "nextSibling" ); }, prev: function( elem ) { return sibling( elem, "previousSibling" ); }, nextAll: function( elem ) { return jQuery.dir( elem, "nextSibling" ); }, prevAll: function( elem ) { return jQuery.dir( elem, "previousSibling" ); }, nextUntil: function( elem, i, until ) { return jQuery.dir( elem, "nextSibling", until ); }, prevUntil: function( elem, i, until ) { return jQuery.dir( elem, "previousSibling", until ); }, siblings: function( elem ) { return jQuery.sibling( ( elem.parentNode || {} ).firstChild, elem ); }, children: function( elem ) { return jQuery.sibling( elem.firstChild ); }, contents: function( elem ) { return elem.contentDocument || jQuery.merge( [], elem.childNodes ); } }, function( name, fn ) { jQuery.fn[ name ] = function( until, selector ) { var matched = jQuery.map( this, fn, until ); if ( name.slice( -5 ) !== "Until" ) { selector = until; } if ( selector && typeof selector === "string" ) { matched = jQuery.filter( selector, matched ); } if ( this.length > 1 ) { // Remove duplicates if ( !guaranteedUnique[ name ] ) { jQuery.unique( matched ); } // Reverse order for parents* and prev-derivatives if ( rparentsprev.test( name ) ) { matched.reverse(); } } return this.pushStack( matched ); }; }); jQuery.extend({ filter: function( expr, elems, not ) { var elem = elems[ 0 ]; if ( not ) { expr = ":not(" + expr + ")"; } return elems.length === 1 && elem.nodeType === 1 ? jQuery.find.matchesSelector( elem, expr ) ? [ elem ] : [] : jQuery.find.matches( expr, jQuery.grep( elems, function( elem ) { return elem.nodeType === 1; })); }, dir: function( elem, dir, until ) { var matched = [], truncate = until !== undefined; while ( (elem = elem[ dir ]) && elem.nodeType !== 9 ) { if ( elem.nodeType === 1 ) { if ( truncate && jQuery( elem ).is( until ) ) { break; } matched.push( elem ); } } return matched; }, sibling: function( n, elem ) { var matched = []; for ( ; n; n = n.nextSibling ) { if ( n.nodeType === 1 && n !== elem ) { matched.push( n ); } } return matched; } }); // Implement the identical functionality for filter and not function winnow( elements, qualifier, not ) { if ( jQuery.isFunction( qualifier ) ) { return jQuery.grep( elements, function( elem, i ) { /* jshint -W018 */ return !!qualifier.call( elem, i, elem ) !== not; }); } if ( qualifier.nodeType ) { return jQuery.grep( elements, function( elem ) { return ( elem === qualifier ) !== not; }); } if ( typeof qualifier === "string" ) { if ( isSimple.test( qualifier ) ) { return jQuery.filter( qualifier, elements, not ); } qualifier = jQuery.filter( qualifier, elements ); } return jQuery.grep( elements, function( elem ) { return ( core_indexOf.call( qualifier, elem ) >= 0 ) !== not; }); } var rxhtmlTag = /<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/gi, rtagName = /<([\w:]+)/, rhtml = /<|&#?\w+;/, rnoInnerhtml = /<(?:script|style|link)/i, manipulation_rcheckableType = /^(?:checkbox|radio)$/i, // checked="checked" or checked rchecked = /checked\s*(?:[^=]|=\s*.checked.)/i, rscriptType = /^$|\/(?:java|ecma)script/i, rscriptTypeMasked = /^true\/(.*)/, rcleanScript = /^\s*<!(?:\[CDATA\[|--)|(?:\]\]|--)>\s*$/g, // We have to close these tags to support XHTML (#13200) wrapMap = { // Support: IE 9 option: [ 1, "<select multiple='multiple'>", "</select>" ], thead: [ 1, "<table>", "</table>" ], col: [ 2, "<table><colgroup>", "</colgroup></table>" ], tr: [ 2, "<table><tbody>", "</tbody></table>" ], td: [ 3, "<table><tbody><tr>", "</tr></tbody></table>" ], _default: [ 0, "", "" ] }; // Support: IE 9 wrapMap.optgroup = wrapMap.option; wrapMap.tbody = wrapMap.tfoot = wrapMap.colgroup = wrapMap.caption = wrapMap.thead; wrapMap.th = wrapMap.td; jQuery.fn.extend({ text: function( value ) { return jQuery.access( this, function( value ) { return value === undefined ? jQuery.text( this ) : this.empty().append( ( this[ 0 ] && this[ 0 ].ownerDocument || document ).createTextNode( value ) ); }, null, value, arguments.length ); }, append: function() { return this.domManip( arguments, function( elem ) { if ( this.nodeType === 1 || this.nodeType === 11 || this.nodeType === 9 ) { var target = manipulationTarget( this, elem ); target.appendChild( elem ); } }); }, prepend: function() { return this.domManip( arguments, function( elem ) { if ( this.nodeType === 1 || this.nodeType === 11 || this.nodeType === 9 ) { var target = manipulationTarget( this, elem ); target.insertBefore( elem, target.firstChild ); } }); }, before: function() { return this.domManip( arguments, function( elem ) { if ( this.parentNode ) { this.parentNode.insertBefore( elem, this ); } }); }, after: function() { return this.domManip( arguments, function( elem ) { if ( this.parentNode ) { this.parentNode.insertBefore( elem, this.nextSibling ); } }); }, // keepData is for internal use only--do not document remove: function( selector, keepData ) { var elem, elems = selector ? jQuery.filter( selector, this ) : this, i = 0; for ( ; (elem = elems[i]) != null; i++ ) { if ( !keepData && elem.nodeType === 1 ) { jQuery.cleanData( getAll( elem ) ); } if ( elem.parentNode ) { if ( keepData && jQuery.contains( elem.ownerDocument, elem ) ) { setGlobalEval( getAll( elem, "script" ) ); } elem.parentNode.removeChild( elem ); } } return this; }, empty: function() { var elem, i = 0; for ( ; (elem = this[i]) != null; i++ ) { if ( elem.nodeType === 1 ) { // Prevent memory leaks jQuery.cleanData( getAll( elem, false ) ); // Remove any remaining nodes elem.textContent = ""; } } return this; }, clone: function( dataAndEvents, deepDataAndEvents ) { dataAndEvents = dataAndEvents == null ? false : dataAndEvents; deepDataAndEvents = deepDataAndEvents == null ? dataAndEvents : deepDataAndEvents; return this.map( function () { return jQuery.clone( this, dataAndEvents, deepDataAndEvents ); }); }, html: function( value ) { return jQuery.access( this, function( value ) { var elem = this[ 0 ] || {}, i = 0, l = this.length; if ( value === undefined && elem.nodeType === 1 ) { return elem.innerHTML; } // See if we can take a shortcut and just use innerHTML if ( typeof value === "string" && !rnoInnerhtml.test( value ) && !wrapMap[ ( rtagName.exec( value ) || [ "", "" ] )[ 1 ].toLowerCase() ] ) { value = value.replace( rxhtmlTag, "<$1></$2>" ); try { for ( ; i < l; i++ ) { elem = this[ i ] || {}; // Remove element nodes and prevent memory leaks if ( elem.nodeType === 1 ) { jQuery.cleanData( getAll( elem, false ) ); elem.innerHTML = value; } } elem = 0; // If using innerHTML throws an exception, use the fallback method } catch( e ) {} } if ( elem ) { this.empty().append( value ); } }, null, value, arguments.length ); }, replaceWith: function() { var // Snapshot the DOM in case .domManip sweeps something relevant into its fragment args = jQuery.map( this, function( elem ) { return [ elem.nextSibling, elem.parentNode ]; }), i = 0; // Make the changes, replacing each context element with the new content this.domManip( arguments, function( elem ) { var next = args[ i++ ], parent = args[ i++ ]; if ( parent ) { // Don't use the snapshot next if it has moved (#13810) if ( next && next.parentNode !== parent ) { next = this.nextSibling; } jQuery( this ).remove(); parent.insertBefore( elem, next ); } // Allow new content to include elements from the context set }, true ); // Force removal if there was no new content (e.g., from empty arguments) return i ? this : this.remove(); }, detach: function( selector ) { return this.remove( selector, true ); }, domManip: function( args, callback, allowIntersection ) { // Flatten any nested arrays args = core_concat.apply( [], args ); var fragment, first, scripts, hasScripts, node, doc, i = 0, l = this.length, set = this, iNoClone = l - 1, value = args[ 0 ], isFunction = jQuery.isFunction( value ); // We can't cloneNode fragments that contain checked, in WebKit if ( isFunction || !( l <= 1 || typeof value !== "string" || jQuery.support.checkClone || !rchecked.test( value ) ) ) { return this.each(function( index ) { var self = set.eq( index ); if ( isFunction ) { args[ 0 ] = value.call( this, index, self.html() ); } self.domManip( args, callback, allowIntersection ); }); } if ( l ) { fragment = jQuery.buildFragment( args, this[ 0 ].ownerDocument, false, !allowIntersection && this ); first = fragment.firstChild; if ( fragment.childNodes.length === 1 ) { fragment = first; } if ( first ) { scripts = jQuery.map( getAll( fragment, "script" ), disableScript ); hasScripts = scripts.length; // Use the original fragment for the last item instead of the first because it can end up // being emptied incorrectly in certain situations (#8070). for ( ; i < l; i++ ) { node = fragment; if ( i !== iNoClone ) { node = jQuery.clone( node, true, true ); // Keep references to cloned scripts for later restoration if ( hasScripts ) { // Support: QtWebKit // jQuery.merge because core_push.apply(_, arraylike) throws jQuery.merge( scripts, getAll( node, "script" ) ); } } callback.call( this[ i ], node, i ); } if ( hasScripts ) { doc = scripts[ scripts.length - 1 ].ownerDocument; // Reenable scripts jQuery.map( scripts, restoreScript ); // Evaluate executable scripts on first document insertion for ( i = 0; i < hasScripts; i++ ) { node = scripts[ i ]; if ( rscriptType.test( node.type || "" ) && !data_priv.access( node, "globalEval" ) && jQuery.contains( doc, node ) ) { if ( node.src ) { // Hope ajax is available... jQuery._evalUrl( node.src ); } else { jQuery.globalEval( node.textContent.replace( rcleanScript, "" ) ); } } } } } } return this; } }); jQuery.each({ appendTo: "append", prependTo: "prepend", insertBefore: "before", insertAfter: "after", replaceAll: "replaceWith" }, function( name, original ) { jQuery.fn[ name ] = function( selector ) { var elems, ret = [], insert = jQuery( selector ), last = insert.length - 1, i = 0; for ( ; i <= last; i++ ) { elems = i === last ? this : this.clone( true ); jQuery( insert[ i ] )[ original ]( elems ); // Support: QtWebKit // .get() because core_push.apply(_, arraylike) throws core_push.apply( ret, elems.get() ); } return this.pushStack( ret ); }; }); jQuery.extend({ clone: function( elem, dataAndEvents, deepDataAndEvents ) { var i, l, srcElements, destElements, clone = elem.cloneNode( true ), inPage = jQuery.contains( elem.ownerDocument, elem ); // Support: IE >= 9 // Fix Cloning issues if ( !jQuery.support.noCloneChecked && ( elem.nodeType === 1 || elem.nodeType === 11 ) && !jQuery.isXMLDoc( elem ) ) { // We eschew Sizzle here for performance reasons: http://jsperf.com/getall-vs-sizzle/2 destElements = getAll( clone ); srcElements = getAll( elem ); for ( i = 0, l = srcElements.length; i < l; i++ ) { fixInput( srcElements[ i ], destElements[ i ] ); } } // Copy the events from the original to the clone if ( dataAndEvents ) { if ( deepDataAndEvents ) { srcElements = srcElements || getAll( elem ); destElements = destElements || getAll( clone ); for ( i = 0, l = srcElements.length; i < l; i++ ) { cloneCopyEvent( srcElements[ i ], destElements[ i ] ); } } else { cloneCopyEvent( elem, clone ); } } // Preserve script evaluation history destElements = getAll( clone, "script" ); if ( destElements.length > 0 ) { setGlobalEval( destElements, !inPage && getAll( elem, "script" ) ); } // Return the cloned set return clone; }, buildFragment: function( elems, context, scripts, selection ) { var elem, tmp, tag, wrap, contains, j, i = 0, l = elems.length, fragment = context.createDocumentFragment(), nodes = []; for ( ; i < l; i++ ) { elem = elems[ i ]; if ( elem || elem === 0 ) { // Add nodes directly if ( jQuery.type( elem ) === "object" ) { // Support: QtWebKit // jQuery.merge because core_push.apply(_, arraylike) throws jQuery.merge( nodes, elem.nodeType ? [ elem ] : elem ); // Convert non-html into a text node } else if ( !rhtml.test( elem ) ) { nodes.push( context.createTextNode( elem ) ); // Convert html into DOM nodes } else { tmp = tmp || fragment.appendChild( context.createElement("div") ); // Deserialize a standard representation tag = ( rtagName.exec( elem ) || ["", ""] )[ 1 ].toLowerCase(); wrap = wrapMap[ tag ] || wrapMap._default; tmp.innerHTML = wrap[ 1 ] + elem.replace( rxhtmlTag, "<$1></$2>" ) + wrap[ 2 ]; // Descend through wrappers to the right content j = wrap[ 0 ]; while ( j-- ) { tmp = tmp.lastChild; } // Support: QtWebKit // jQuery.merge because core_push.apply(_, arraylike) throws jQuery.merge( nodes, tmp.childNodes ); // Remember the top-level container tmp = fragment.firstChild; // Fixes #12346 // Support: Webkit, IE tmp.textContent = ""; } } } // Remove wrapper from fragment fragment.textContent = ""; i = 0; while ( (elem = nodes[ i++ ]) ) { // #4087 - If origin and destination elements are the same, and this is // that element, do not do anything if ( selection && jQuery.inArray( elem, selection ) !== -1 ) { continue; } contains = jQuery.contains( elem.ownerDocument, elem ); // Append to fragment tmp = getAll( fragment.appendChild( elem ), "script" ); // Preserve script evaluation history if ( contains ) { setGlobalEval( tmp ); } // Capture executables if ( scripts ) { j = 0; while ( (elem = tmp[ j++ ]) ) { if ( rscriptType.test( elem.type || "" ) ) { scripts.push( elem ); } } } } return fragment; }, cleanData: function( elems ) { var data, elem, events, type, key, j, special = jQuery.event.special, i = 0; for ( ; (elem = elems[ i ]) !== undefined; i++ ) { if ( Data.accepts( elem ) ) { key = elem[ data_priv.expando ]; if ( key && (data = data_priv.cache[ key ]) ) { events = Object.keys( data.events || {} ); if ( events.length ) { for ( j = 0; (type = events[j]) !== undefined; j++ ) { if ( special[ type ] ) { jQuery.event.remove( elem, type ); // This is a shortcut to avoid jQuery.event.remove's overhead } else { jQuery.removeEvent( elem, type, data.handle ); } } } if ( data_priv.cache[ key ] ) { // Discard any remaining `private` data delete data_priv.cache[ key ]; } } } // Discard any remaining `user` data delete data_user.cache[ elem[ data_user.expando ] ]; } }, _evalUrl: function( url ) { return jQuery.ajax({ url: url, type: "GET", dataType: "script", async: false, global: false, "throws": true }); } }); // Support: 1.x compatibility // Manipulating tables requires a tbody function manipulationTarget( elem, content ) { return jQuery.nodeName( elem, "table" ) && jQuery.nodeName( content.nodeType === 1 ? content : content.firstChild, "tr" ) ? elem.getElementsByTagName("tbody")[0] || elem.appendChild( elem.ownerDocument.createElement("tbody") ) : elem; } // Replace/restore the type attribute of script elements for safe DOM manipulation function disableScript( elem ) { elem.type = (elem.getAttribute("type") !== null) + "/" + elem.type; return elem; } function restoreScript( elem ) { var match = rscriptTypeMasked.exec( elem.type ); if ( match ) { elem.type = match[ 1 ]; } else { elem.removeAttribute("type"); } return elem; } // Mark scripts as having already been evaluated function setGlobalEval( elems, refElements ) { var l = elems.length, i = 0; for ( ; i < l; i++ ) { data_priv.set( elems[ i ], "globalEval", !refElements || data_priv.get( refElements[ i ], "globalEval" ) ); } } function cloneCopyEvent( src, dest ) { var i, l, type, pdataOld, pdataCur, udataOld, udataCur, events; if ( dest.nodeType !== 1 ) { return; } // 1. Copy private data: events, handlers, etc. if ( data_priv.hasData( src ) ) { pdataOld = data_priv.access( src ); pdataCur = data_priv.set( dest, pdataOld ); events = pdataOld.events; if ( events ) { delete pdataCur.handle; pdataCur.events = {}; for ( type in events ) { for ( i = 0, l = events[ type ].length; i < l; i++ ) { jQuery.event.add( dest, type, events[ type ][ i ] ); } } } } // 2. Copy user data if ( data_user.hasData( src ) ) { udataOld = data_user.access( src ); udataCur = jQuery.extend( {}, udataOld ); data_user.set( dest, udataCur ); } } function getAll( context, tag ) { var ret = context.getElementsByTagName ? context.getElementsByTagName( tag || "*" ) : context.querySelectorAll ? context.querySelectorAll( tag || "*" ) : []; return tag === undefined || tag && jQuery.nodeName( context, tag ) ? jQuery.merge( [ context ], ret ) : ret; } // Support: IE >= 9 function fixInput( src, dest ) { var nodeName = dest.nodeName.toLowerCase(); // Fails to persist the checked state of a cloned checkbox or radio button. if ( nodeName === "input" && manipulation_rcheckableType.test( src.type ) ) { dest.checked = src.checked; // Fails to return the selected option to the default selected state when cloning options } else if ( nodeName === "input" || nodeName === "textarea" ) { dest.defaultValue = src.defaultValue; } } jQuery.fn.extend({ wrapAll: function( html ) { var wrap; if ( jQuery.isFunction( html ) ) { return this.each(function( i ) { jQuery( this ).wrapAll( html.call(this, i) ); }); } if ( this[ 0 ] ) { // The elements to wrap the target around wrap = jQuery( html, this[ 0 ].ownerDocument ).eq( 0 ).clone( true ); if ( this[ 0 ].parentNode ) { wrap.insertBefore( this[ 0 ] ); } wrap.map(function() { var elem = this; while ( elem.firstElementChild ) { elem = elem.firstElementChild; } return elem; }).append( this ); } return this; }, wrapInner: function( html ) { if ( jQuery.isFunction( html ) ) { return this.each(function( i ) { jQuery( this ).wrapInner( html.call(this, i) ); }); } return this.each(function() { var self = jQuery( this ), contents = self.contents(); if ( contents.length ) { contents.wrapAll( html ); } else { self.append( html ); } }); }, wrap: function( html ) { var isFunction = jQuery.isFunction( html ); return this.each(function( i ) { jQuery( this ).wrapAll( isFunction ? html.call(this, i) : html ); }); }, unwrap: function() { return this.parent().each(function() { if ( !jQuery.nodeName( this, "body" ) ) { jQuery( this ).replaceWith( this.childNodes ); } }).end(); } }); var curCSS, iframe, // swappable if display is none or starts with table except "table", "table-cell", or "table-caption" // see here for display values: https://developer.mozilla.org/en-US/docs/CSS/display rdisplayswap = /^(none|table(?!-c[ea]).+)/, rmargin = /^margin/, rnumsplit = new RegExp( "^(" + core_pnum + ")(.*)$", "i" ), rnumnonpx = new RegExp( "^(" + core_pnum + ")(?!px)[a-z%]+$", "i" ), rrelNum = new RegExp( "^([+-])=(" + core_pnum + ")", "i" ), elemdisplay = { BODY: "block" }, cssShow = { position: "absolute", visibility: "hidden", display: "block" }, cssNormalTransform = { letterSpacing: 0, fontWeight: 400 }, cssExpand = [ "Top", "Right", "Bottom", "Left" ], cssPrefixes = [ "Webkit", "O", "Moz", "ms" ]; // return a css property mapped to a potentially vendor prefixed property function vendorPropName( style, name ) { // shortcut for names that are not vendor prefixed if ( name in style ) { return name; } // check for vendor prefixed names var capName = name.charAt(0).toUpperCase() + name.slice(1), origName = name, i = cssPrefixes.length; while ( i-- ) { name = cssPrefixes[ i ] + capName; if ( name in style ) { return name; } } return origName; } function isHidden( elem, el ) { // isHidden might be called from jQuery#filter function; // in that case, element will be second argument elem = el || elem; return jQuery.css( elem, "display" ) === "none" || !jQuery.contains( elem.ownerDocument, elem ); } // NOTE: we've included the "window" in window.getComputedStyle // because jsdom on node.js will break without it. function getStyles( elem ) { return window.getComputedStyle( elem, null ); } function showHide( elements, show ) { var display, elem, hidden, values = [], index = 0, length = elements.length; for ( ; index < length; index++ ) { elem = elements[ index ]; if ( !elem.style ) { continue; } values[ index ] = data_priv.get( elem, "olddisplay" ); display = elem.style.display; if ( show ) { // Reset the inline display of this element to learn if it is // being hidden by cascaded rules or not if ( !values[ index ] && display === "none" ) { elem.style.display = ""; } // Set elements which have been overridden with display: none // in a stylesheet to whatever the default browser style is // for such an element if ( elem.style.display === "" && isHidden( elem ) ) { values[ index ] = data_priv.access( elem, "olddisplay", css_defaultDisplay(elem.nodeName) ); } } else { if ( !values[ index ] ) { hidden = isHidden( elem ); if ( display && display !== "none" || !hidden ) { data_priv.set( elem, "olddisplay", hidden ? display : jQuery.css(elem, "display") ); } } } } // Set the display of most of the elements in a second loop // to avoid the constant reflow for ( index = 0; index < length; index++ ) { elem = elements[ index ]; if ( !elem.style ) { continue; } if ( !show || elem.style.display === "none" || elem.style.display === "" ) { elem.style.display = show ? values[ index ] || "" : "none"; } } return elements; } jQuery.fn.extend({ css: function( name, value ) { return jQuery.access( this, function( elem, name, value ) { var styles, len, map = {}, i = 0; if ( jQuery.isArray( name ) ) { styles = getStyles( elem ); len = name.length; for ( ; i < len; i++ ) { map[ name[ i ] ] = jQuery.css( elem, name[ i ], false, styles ); } return map; } return value !== undefined ? jQuery.style( elem, name, value ) : jQuery.css( elem, name ); }, name, value, arguments.length > 1 ); }, show: function() { return showHide( this, true ); }, hide: function() { return showHide( this ); }, toggle: function( state ) { if ( typeof state === "boolean" ) { return state ? this.show() : this.hide(); } return this.each(function() { if ( isHidden( this ) ) { jQuery( this ).show(); } else { jQuery( this ).hide(); } }); } }); jQuery.extend({ // Add in style property hooks for overriding the default // behavior of getting and setting a style property cssHooks: { opacity: { get: function( elem, computed ) { if ( computed ) { // We should always get a number back from opacity var ret = curCSS( elem, "opacity" ); return ret === "" ? "1" : ret; } } } }, // Don't automatically add "px" to these possibly-unitless properties cssNumber: { "columnCount": true, "fillOpacity": true, "fontWeight": true, "lineHeight": true, "opacity": true, "order": true, "orphans": true, "widows": true, "zIndex": true, "zoom": true }, // Add in properties whose names you wish to fix before // setting or getting the value cssProps: { // normalize float css property "float": "cssFloat" }, // Get and set the style property on a DOM Node style: function( elem, name, value, extra ) { // Don't set styles on text and comment nodes if ( !elem || elem.nodeType === 3 || elem.nodeType === 8 || !elem.style ) { return; } // Make sure that we're working with the right name var ret, type, hooks, origName = jQuery.camelCase( name ), style = elem.style; name = jQuery.cssProps[ origName ] || ( jQuery.cssProps[ origName ] = vendorPropName( style, origName ) ); // gets hook for the prefixed version // followed by the unprefixed version hooks = jQuery.cssHooks[ name ] || jQuery.cssHooks[ origName ]; // Check if we're setting a value if ( value !== undefined ) { type = typeof value; // convert relative number strings (+= or -=) to relative numbers. #7345 if ( type === "string" && (ret = rrelNum.exec( value )) ) { value = ( ret[1] + 1 ) * ret[2] + parseFloat( jQuery.css( elem, name ) ); // Fixes bug #9237 type = "number"; } // Make sure that NaN and null values aren't set. See: #7116 if ( value == null || type === "number" && isNaN( value ) ) { return; } // If a number was passed in, add 'px' to the (except for certain CSS properties) if ( type === "number" && !jQuery.cssNumber[ origName ] ) { value += "px"; } // Fixes #8908, it can be done more correctly by specifying setters in cssHooks, // but it would mean to define eight (for every problematic property) identical functions if ( !jQuery.support.clearCloneStyle && value === "" && name.indexOf("background") === 0 ) { style[ name ] = "inherit"; } // If a hook was provided, use that value, otherwise just set the specified value if ( !hooks || !("set" in hooks) || (value = hooks.set( elem, value, extra )) !== undefined ) { style[ name ] = value; } } else { // If a hook was provided get the non-computed value from there if ( hooks && "get" in hooks && (ret = hooks.get( elem, false, extra )) !== undefined ) { return ret; } // Otherwise just get the value from the style object return style[ name ]; } }, css: function( elem, name, extra, styles ) { var val, num, hooks, origName = jQuery.camelCase( name ); // Make sure that we're working with the right name name = jQuery.cssProps[ origName ] || ( jQuery.cssProps[ origName ] = vendorPropName( elem.style, origName ) ); // gets hook for the prefixed version // followed by the unprefixed version hooks = jQuery.cssHooks[ name ] || jQuery.cssHooks[ origName ]; // If a hook was provided get the computed value from there if ( hooks && "get" in hooks ) { val = hooks.get( elem, true, extra ); } // Otherwise, if a way to get the computed value exists, use that if ( val === undefined ) { val = curCSS( elem, name, styles ); } //convert "normal" to computed value if ( val === "normal" && name in cssNormalTransform ) { val = cssNormalTransform[ name ]; } // Return, converting to number if forced or a qualifier was provided and val looks numeric if ( extra === "" || extra ) { num = parseFloat( val ); return extra === true || jQuery.isNumeric( num ) ? num || 0 : val; } return val; } }); curCSS = function( elem, name, _computed ) { var width, minWidth, maxWidth, computed = _computed || getStyles( elem ), // Support: IE9 // getPropertyValue is only needed for .css('filter') in IE9, see #12537 ret = computed ? computed.getPropertyValue( name ) || computed[ name ] : undefined, style = elem.style; if ( computed ) { if ( ret === "" && !jQuery.contains( elem.ownerDocument, elem ) ) { ret = jQuery.style( elem, name ); } // Support: Safari 5.1 // A tribute to the "awesome hack by Dean Edwards" // Safari 5.1.7 (at least) returns percentage for a larger set of values, but width seems to be reliably pixels // this is against the CSSOM draft spec: http://dev.w3.org/csswg/cssom/#resolved-values if ( rnumnonpx.test( ret ) && rmargin.test( name ) ) { // Remember the original values width = style.width; minWidth = style.minWidth; maxWidth = style.maxWidth; // Put in the new values to get a computed value out style.minWidth = style.maxWidth = style.width = ret; ret = computed.width; // Revert the changed values style.width = width; style.minWidth = minWidth; style.maxWidth = maxWidth; } } return ret; }; function setPositiveNumber( elem, value, subtract ) { var matches = rnumsplit.exec( value ); return matches ? // Guard against undefined "subtract", e.g., when used as in cssHooks Math.max( 0, matches[ 1 ] - ( subtract || 0 ) ) + ( matches[ 2 ] || "px" ) : value; } function augmentWidthOrHeight( elem, name, extra, isBorderBox, styles ) { var i = extra === ( isBorderBox ? "border" : "content" ) ? // If we already have the right measurement, avoid augmentation 4 : // Otherwise initialize for horizontal or vertical properties name === "width" ? 1 : 0, val = 0; for ( ; i < 4; i += 2 ) { // both box models exclude margin, so add it if we want it if ( extra === "margin" ) { val += jQuery.css( elem, extra + cssExpand[ i ], true, styles ); } if ( isBorderBox ) { // border-box includes padding, so remove it if we want content if ( extra === "content" ) { val -= jQuery.css( elem, "padding" + cssExpand[ i ], true, styles ); } // at this point, extra isn't border nor margin, so remove border if ( extra !== "margin" ) { val -= jQuery.css( elem, "border" + cssExpand[ i ] + "Width", true, styles ); } } else { // at this point, extra isn't content, so add padding val += jQuery.css( elem, "padding" + cssExpand[ i ], true, styles ); // at this point, extra isn't content nor padding, so add border if ( extra !== "padding" ) { val += jQuery.css( elem, "border" + cssExpand[ i ] + "Width", true, styles ); } } } return val; } function getWidthOrHeight( elem, name, extra ) { // Start with offset property, which is equivalent to the border-box value var valueIsBorderBox = true, val = name === "width" ? elem.offsetWidth : elem.offsetHeight, styles = getStyles( elem ), isBorderBox = jQuery.support.boxSizing && jQuery.css( elem, "boxSizing", false, styles ) === "border-box"; // some non-html elements return undefined for offsetWidth, so check for null/undefined // svg - https://bugzilla.mozilla.org/show_bug.cgi?id=649285 // MathML - https://bugzilla.mozilla.org/show_bug.cgi?id=491668 if ( val <= 0 || val == null ) { // Fall back to computed then uncomputed css if necessary val = curCSS( elem, name, styles ); if ( val < 0 || val == null ) { val = elem.style[ name ]; } // Computed unit is not pixels. Stop here and return. if ( rnumnonpx.test(val) ) { return val; } // we need the check for style in case a browser which returns unreliable values // for getComputedStyle silently falls back to the reliable elem.style valueIsBorderBox = isBorderBox && ( jQuery.support.boxSizingReliable || val === elem.style[ name ] ); // Normalize "", auto, and prepare for extra val = parseFloat( val ) || 0; } // use the active box-sizing model to add/subtract irrelevant styles return ( val + augmentWidthOrHeight( elem, name, extra || ( isBorderBox ? "border" : "content" ), valueIsBorderBox, styles ) ) + "px"; } // Try to determine the default display value of an element function css_defaultDisplay( nodeName ) { var doc = document, display = elemdisplay[ nodeName ]; if ( !display ) { display = actualDisplay( nodeName, doc ); // If the simple way fails, read from inside an iframe if ( display === "none" || !display ) { // Use the already-created iframe if possible iframe = ( iframe || jQuery("<iframe frameborder='0' width='0' height='0'/>") .css( "cssText", "display:block !important" ) ).appendTo( doc.documentElement ); // Always write a new HTML skeleton so Webkit and Firefox don't choke on reuse doc = ( iframe[0].contentWindow || iframe[0].contentDocument ).document; doc.write("<!doctype html><html><body>"); doc.close(); display = actualDisplay( nodeName, doc ); iframe.detach(); } // Store the correct default display elemdisplay[ nodeName ] = display; } return display; } // Called ONLY from within css_defaultDisplay function actualDisplay( name, doc ) { var elem = jQuery( doc.createElement( name ) ).appendTo( doc.body ), display = jQuery.css( elem[0], "display" ); elem.remove(); return display; } jQuery.each([ "height", "width" ], function( i, name ) { jQuery.cssHooks[ name ] = { get: function( elem, computed, extra ) { if ( computed ) { // certain elements can have dimension info if we invisibly show them // however, it must have a current display style that would benefit from this return elem.offsetWidth === 0 && rdisplayswap.test( jQuery.css( elem, "display" ) ) ? jQuery.swap( elem, cssShow, function() { return getWidthOrHeight( elem, name, extra ); }) : getWidthOrHeight( elem, name, extra ); } }, set: function( elem, value, extra ) { var styles = extra && getStyles( elem ); return setPositiveNumber( elem, value, extra ? augmentWidthOrHeight( elem, name, extra, jQuery.support.boxSizing && jQuery.css( elem, "boxSizing", false, styles ) === "border-box", styles ) : 0 ); } }; }); // These hooks cannot be added until DOM ready because the support test // for it is not run until after DOM ready jQuery(function() { // Support: Android 2.3 if ( !jQuery.support.reliableMarginRight ) { jQuery.cssHooks.marginRight = { get: function( elem, computed ) { if ( computed ) { // Support: Android 2.3 // WebKit Bug 13343 - getComputedStyle returns wrong value for margin-right // Work around by temporarily setting element display to inline-block return jQuery.swap( elem, { "display": "inline-block" }, curCSS, [ elem, "marginRight" ] ); } } }; } // Webkit bug: https://bugs.webkit.org/show_bug.cgi?id=29084 // getComputedStyle returns percent when specified for top/left/bottom/right // rather than make the css module depend on the offset module, we just check for it here if ( !jQuery.support.pixelPosition && jQuery.fn.position ) { jQuery.each( [ "top", "left" ], function( i, prop ) { jQuery.cssHooks[ prop ] = { get: function( elem, computed ) { if ( computed ) { computed = curCSS( elem, prop ); // if curCSS returns percentage, fallback to offset return rnumnonpx.test( computed ) ? jQuery( elem ).position()[ prop ] + "px" : computed; } } }; }); } }); if ( jQuery.expr && jQuery.expr.filters ) { jQuery.expr.filters.hidden = function( elem ) { // Support: Opera <= 12.12 // Opera reports offsetWidths and offsetHeights less than zero on some elements return elem.offsetWidth <= 0 && elem.offsetHeight <= 0; }; jQuery.expr.filters.visible = function( elem ) { return !jQuery.expr.filters.hidden( elem ); }; } // These hooks are used by animate to expand properties jQuery.each({ margin: "", padding: "", border: "Width" }, function( prefix, suffix ) { jQuery.cssHooks[ prefix + suffix ] = { expand: function( value ) { var i = 0, expanded = {}, // assumes a single number if not a string parts = typeof value === "string" ? value.split(" ") : [ value ]; for ( ; i < 4; i++ ) { expanded[ prefix + cssExpand[ i ] + suffix ] = parts[ i ] || parts[ i - 2 ] || parts[ 0 ]; } return expanded; } }; if ( !rmargin.test( prefix ) ) { jQuery.cssHooks[ prefix + suffix ].set = setPositiveNumber; } }); var r20 = /%20/g, rbracket = /\[\]$/, rCRLF = /\r?\n/g, rsubmitterTypes = /^(?:submit|button|image|reset|file)$/i, rsubmittable = /^(?:input|select|textarea|keygen)/i; jQuery.fn.extend({ serialize: function() { return jQuery.param( this.serializeArray() ); }, serializeArray: function() { return this.map(function(){ // Can add propHook for "elements" to filter or add form elements var elements = jQuery.prop( this, "elements" ); return elements ? jQuery.makeArray( elements ) : this; }) .filter(function(){ var type = this.type; // Use .is(":disabled") so that fieldset[disabled] works return this.name && !jQuery( this ).is( ":disabled" ) && rsubmittable.test( this.nodeName ) && !rsubmitterTypes.test( type ) && ( this.checked || !manipulation_rcheckableType.test( type ) ); }) .map(function( i, elem ){ var val = jQuery( this ).val(); return val == null ? null : jQuery.isArray( val ) ? jQuery.map( val, function( val ){ return { name: elem.name, value: val.replace( rCRLF, "\r\n" ) }; }) : { name: elem.name, value: val.replace( rCRLF, "\r\n" ) }; }).get(); } }); //Serialize an array of form elements or a set of //key/values into a query string jQuery.param = function( a, traditional ) { var prefix, s = [], add = function( key, value ) { // If value is a function, invoke it and return its value value = jQuery.isFunction( value ) ? value() : ( value == null ? "" : value ); s[ s.length ] = encodeURIComponent( key ) + "=" + encodeURIComponent( value ); }; // Set traditional to true for jQuery <= 1.3.2 behavior. if ( traditional === undefined ) { traditional = jQuery.ajaxSettings && jQuery.ajaxSettings.traditional; } // If an array was passed in, assume that it is an array of form elements. if ( jQuery.isArray( a ) || ( a.jquery && !jQuery.isPlainObject( a ) ) ) { // Serialize the form elements jQuery.each( a, function() { add( this.name, this.value ); }); } else { // If traditional, encode the "old" way (the way 1.3.2 or older // did it), otherwise encode params recursively. for ( prefix in a ) { buildParams( prefix, a[ prefix ], traditional, add ); } } // Return the resulting serialization return s.join( "&" ).replace( r20, "+" ); }; function buildParams( prefix, obj, traditional, add ) { var name; if ( jQuery.isArray( obj ) ) { // Serialize array item. jQuery.each( obj, function( i, v ) { if ( traditional || rbracket.test( prefix ) ) { // Treat each array item as a scalar. add( prefix, v ); } else { // Item is non-scalar (array or object), encode its numeric index. buildParams( prefix + "[" + ( typeof v === "object" ? i : "" ) + "]", v, traditional, add ); } }); } else if ( !traditional && jQuery.type( obj ) === "object" ) { // Serialize object item. for ( name in obj ) { buildParams( prefix + "[" + name + "]", obj[ name ], traditional, add ); } } else { // Serialize scalar item. add( prefix, obj ); } } jQuery.each( ("blur focus focusin focusout load resize scroll unload click dblclick " + "mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave " + "change select submit keydown keypress keyup error contextmenu").split(" "), function( i, name ) { // Handle event binding jQuery.fn[ name ] = function( data, fn ) { return arguments.length > 0 ? this.on( name, null, data, fn ) : this.trigger( name ); }; }); jQuery.fn.extend({ hover: function( fnOver, fnOut ) { return this.mouseenter( fnOver ).mouseleave( fnOut || fnOver ); }, bind: function( types, data, fn ) { return this.on( types, null, data, fn ); }, unbind: function( types, fn ) { return this.off( types, null, fn ); }, delegate: function( selector, types, data, fn ) { return this.on( types, selector, data, fn ); }, undelegate: function( selector, types, fn ) { // ( namespace ) or ( selector, types [, fn] ) return arguments.length === 1 ? this.off( selector, "**" ) : this.off( types, selector || "**", fn ); } }); var // Document location ajaxLocParts, ajaxLocation, ajax_nonce = jQuery.now(), ajax_rquery = /\?/, rhash = /#.*$/, rts = /([?&])_=[^&]*/, rheaders = /^(.*?):[ \t]*([^\r\n]*)$/mg, // #7653, #8125, #8152: local protocol detection rlocalProtocol = /^(?:about|app|app-storage|.+-extension|file|res|widget):$/, rnoContent = /^(?:GET|HEAD)$/, rprotocol = /^\/\//, rurl = /^([\w.+-]+:)(?:\/\/([^\/?#:]*)(?::(\d+)|)|)/, // Keep a copy of the old load method _load = jQuery.fn.load, /* Prefilters * 1) They are useful to introduce custom dataTypes (see ajax/jsonp.js for an example) * 2) These are called: * - BEFORE asking for a transport * - AFTER param serialization (s.data is a string if s.processData is true) * 3) key is the dataType * 4) the catchall symbol "*" can be used * 5) execution will start with transport dataType and THEN continue down to "*" if needed */ prefilters = {}, /* Transports bindings * 1) key is the dataType * 2) the catchall symbol "*" can be used * 3) selection will start with transport dataType and THEN go to "*" if needed */ transports = {}, // Avoid comment-prolog char sequence (#10098); must appease lint and evade compression allTypes = "*/".concat("*"); // #8138, IE may throw an exception when accessing // a field from window.location if document.domain has been set try { ajaxLocation = location.href; } catch( e ) { // Use the href attribute of an A element // since IE will modify it given document.location ajaxLocation = document.createElement( "a" ); ajaxLocation.href = ""; ajaxLocation = ajaxLocation.href; } // Segment location into parts ajaxLocParts = rurl.exec( ajaxLocation.toLowerCase() ) || []; // Base "constructor" for jQuery.ajaxPrefilter and jQuery.ajaxTransport function addToPrefiltersOrTransports( structure ) { // dataTypeExpression is optional and defaults to "*" return function( dataTypeExpression, func ) { if ( typeof dataTypeExpression !== "string" ) { func = dataTypeExpression; dataTypeExpression = "*"; } var dataType, i = 0, dataTypes = dataTypeExpression.toLowerCase().match( core_rnotwhite ) || []; if ( jQuery.isFunction( func ) ) { // For each dataType in the dataTypeExpression while ( (dataType = dataTypes[i++]) ) { // Prepend if requested if ( dataType[0] === "+" ) { dataType = dataType.slice( 1 ) || "*"; (structure[ dataType ] = structure[ dataType ] || []).unshift( func ); // Otherwise append } else { (structure[ dataType ] = structure[ dataType ] || []).push( func ); } } } }; } // Base inspection function for prefilters and transports function inspectPrefiltersOrTransports( structure, options, originalOptions, jqXHR ) { var inspected = {}, seekingTransport = ( structure === transports ); function inspect( dataType ) { var selected; inspected[ dataType ] = true; jQuery.each( structure[ dataType ] || [], function( _, prefilterOrFactory ) { var dataTypeOrTransport = prefilterOrFactory( options, originalOptions, jqXHR ); if( typeof dataTypeOrTransport === "string" && !seekingTransport && !inspected[ dataTypeOrTransport ] ) { options.dataTypes.unshift( dataTypeOrTransport ); inspect( dataTypeOrTransport ); return false; } else if ( seekingTransport ) { return !( selected = dataTypeOrTransport ); } }); return selected; } return inspect( options.dataTypes[ 0 ] ) || !inspected[ "*" ] && inspect( "*" ); } // A special extend for ajax options // that takes "flat" options (not to be deep extended) // Fixes #9887 function ajaxExtend( target, src ) { var key, deep, flatOptions = jQuery.ajaxSettings.flatOptions || {}; for ( key in src ) { if ( src[ key ] !== undefined ) { ( flatOptions[ key ] ? target : ( deep || (deep = {}) ) )[ key ] = src[ key ]; } } if ( deep ) { jQuery.extend( true, target, deep ); } return target; } jQuery.fn.load = function( url, params, callback ) { if ( typeof url !== "string" && _load ) { return _load.apply( this, arguments ); } var selector, type, response, self = this, off = url.indexOf(" "); if ( off >= 0 ) { selector = url.slice( off ); url = url.slice( 0, off ); } // If it's a function if ( jQuery.isFunction( params ) ) { // We assume that it's the callback callback = params; params = undefined; // Otherwise, build a param string } else if ( params && typeof params === "object" ) { type = "POST"; } // If we have elements to modify, make the request if ( self.length > 0 ) { jQuery.ajax({ url: url, // if "type" variable is undefined, then "GET" method will be used type: type, dataType: "html", data: params }).done(function( responseText ) { // Save response for use in complete callback response = arguments; self.html( selector ? // If a selector was specified, locate the right elements in a dummy div // Exclude scripts to avoid IE 'Permission Denied' errors jQuery("<div>").append( jQuery.parseHTML( responseText ) ).find( selector ) : // Otherwise use the full result responseText ); }).complete( callback && function( jqXHR, status ) { self.each( callback, response || [ jqXHR.responseText, status, jqXHR ] ); }); } return this; }; // Attach a bunch of functions for handling common AJAX events jQuery.each( [ "ajaxStart", "ajaxStop", "ajaxComplete", "ajaxError", "ajaxSuccess", "ajaxSend" ], function( i, type ){ jQuery.fn[ type ] = function( fn ){ return this.on( type, fn ); }; }); jQuery.extend({ // Counter for holding the number of active queries active: 0, // Last-Modified header cache for next request lastModified: {}, etag: {}, ajaxSettings: { url: ajaxLocation, type: "GET", isLocal: rlocalProtocol.test( ajaxLocParts[ 1 ] ), global: true, processData: true, async: true, contentType: "application/x-www-form-urlencoded; charset=UTF-8", /* timeout: 0, data: null, dataType: null, username: null, password: null, cache: null, throws: false, traditional: false, headers: {}, */ accepts: { "*": allTypes, text: "text/plain", html: "text/html", xml: "application/xml, text/xml", json: "application/json, text/javascript" }, contents: { xml: /xml/, html: /html/, json: /json/ }, responseFields: { xml: "responseXML", text: "responseText", json: "responseJSON" }, // Data converters // Keys separate source (or catchall "*") and destination types with a single space converters: { // Convert anything to text "* text": String, // Text to html (true = no transformation) "text html": true, // Evaluate text as a json expression "text json": jQuery.parseJSON, // Parse text as xml "text xml": jQuery.parseXML }, // For options that shouldn't be deep extended: // you can add your own custom options here if // and when you create one that shouldn't be // deep extended (see ajaxExtend) flatOptions: { url: true, context: true } }, // Creates a full fledged settings object into target // with both ajaxSettings and settings fields. // If target is omitted, writes into ajaxSettings. ajaxSetup: function( target, settings ) { return settings ? // Building a settings object ajaxExtend( ajaxExtend( target, jQuery.ajaxSettings ), settings ) : // Extending ajaxSettings ajaxExtend( jQuery.ajaxSettings, target ); }, ajaxPrefilter: addToPrefiltersOrTransports( prefilters ), ajaxTransport: addToPrefiltersOrTransports( transports ), // Main method ajax: function( url, options ) { // If url is an object, simulate pre-1.5 signature if ( typeof url === "object" ) { options = url; url = undefined; } // Force options to be an object options = options || {}; var transport, // URL without anti-cache param cacheURL, // Response headers responseHeadersString, responseHeaders, // timeout handle timeoutTimer, // Cross-domain detection vars parts, // To know if global events are to be dispatched fireGlobals, // Loop variable i, // Create the final options object s = jQuery.ajaxSetup( {}, options ), // Callbacks context callbackContext = s.context || s, // Context for global events is callbackContext if it is a DOM node or jQuery collection globalEventContext = s.context && ( callbackContext.nodeType || callbackContext.jquery ) ? jQuery( callbackContext ) : jQuery.event, // Deferreds deferred = jQuery.Deferred(), completeDeferred = jQuery.Callbacks("once memory"), // Status-dependent callbacks statusCode = s.statusCode || {}, // Headers (they are sent all at once) requestHeaders = {}, requestHeadersNames = {}, // The jqXHR state state = 0, // Default abort message strAbort = "canceled", // Fake xhr jqXHR = { readyState: 0, // Builds headers hashtable if needed getResponseHeader: function( key ) { var match; if ( state === 2 ) { if ( !responseHeaders ) { responseHeaders = {}; while ( (match = rheaders.exec( responseHeadersString )) ) { responseHeaders[ match[1].toLowerCase() ] = match[ 2 ]; } } match = responseHeaders[ key.toLowerCase() ]; } return match == null ? null : match; }, // Raw string getAllResponseHeaders: function() { return state === 2 ? responseHeadersString : null; }, // Caches the header setRequestHeader: function( name, value ) { var lname = name.toLowerCase(); if ( !state ) { name = requestHeadersNames[ lname ] = requestHeadersNames[ lname ] || name; requestHeaders[ name ] = value; } return this; }, // Overrides response content-type header overrideMimeType: function( type ) { if ( !state ) { s.mimeType = type; } return this; }, // Status-dependent callbacks statusCode: function( map ) { var code; if ( map ) { if ( state < 2 ) { for ( code in map ) { // Lazy-add the new callback in a way that preserves old ones statusCode[ code ] = [ statusCode[ code ], map[ code ] ]; } } else { // Execute the appropriate callbacks jqXHR.always( map[ jqXHR.status ] ); } } return this; }, // Cancel the request abort: function( statusText ) { var finalText = statusText || strAbort; if ( transport ) { transport.abort( finalText ); } done( 0, finalText ); return this; } }; // Attach deferreds deferred.promise( jqXHR ).complete = completeDeferred.add; jqXHR.success = jqXHR.done; jqXHR.error = jqXHR.fail; // Remove hash character (#7531: and string promotion) // Add protocol if not provided (prefilters might expect it) // Handle falsy url in the settings object (#10093: consistency with old signature) // We also use the url parameter if available s.url = ( ( url || s.url || ajaxLocation ) + "" ).replace( rhash, "" ) .replace( rprotocol, ajaxLocParts[ 1 ] + "//" ); // Alias method option to type as per ticket #12004 s.type = options.method || options.type || s.method || s.type; // Extract dataTypes list s.dataTypes = jQuery.trim( s.dataType || "*" ).toLowerCase().match( core_rnotwhite ) || [""]; // A cross-domain request is in order when we have a protocol:host:port mismatch if ( s.crossDomain == null ) { parts = rurl.exec( s.url.toLowerCase() ); s.crossDomain = !!( parts && ( parts[ 1 ] !== ajaxLocParts[ 1 ] || parts[ 2 ] !== ajaxLocParts[ 2 ] || ( parts[ 3 ] || ( parts[ 1 ] === "http:" ? "80" : "443" ) ) !== ( ajaxLocParts[ 3 ] || ( ajaxLocParts[ 1 ] === "http:" ? "80" : "443" ) ) ) ); } // Convert data if not already a string if ( s.data && s.processData && typeof s.data !== "string" ) { s.data = jQuery.param( s.data, s.traditional ); } // Apply prefilters inspectPrefiltersOrTransports( prefilters, s, options, jqXHR ); // If request was aborted inside a prefilter, stop there if ( state === 2 ) { return jqXHR; } // We can fire global events as of now if asked to fireGlobals = s.global; // Watch for a new set of requests if ( fireGlobals && jQuery.active++ === 0 ) { jQuery.event.trigger("ajaxStart"); } // Uppercase the type s.type = s.type.toUpperCase(); // Determine if request has content s.hasContent = !rnoContent.test( s.type ); // Save the URL in case we're toying with the If-Modified-Since // and/or If-None-Match header later on cacheURL = s.url; // More options handling for requests with no content if ( !s.hasContent ) { // If data is available, append data to url if ( s.data ) { cacheURL = ( s.url += ( ajax_rquery.test( cacheURL ) ? "&" : "?" ) + s.data ); // #9682: remove data so that it's not used in an eventual retry delete s.data; } // Add anti-cache in url if needed if ( s.cache === false ) { s.url = rts.test( cacheURL ) ? // If there is already a '_' parameter, set its value cacheURL.replace( rts, "$1_=" + ajax_nonce++ ) : // Otherwise add one to the end cacheURL + ( ajax_rquery.test( cacheURL ) ? "&" : "?" ) + "_=" + ajax_nonce++; } } // Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode. if ( s.ifModified ) { if ( jQuery.lastModified[ cacheURL ] ) { jqXHR.setRequestHeader( "If-Modified-Since", jQuery.lastModified[ cacheURL ] ); } if ( jQuery.etag[ cacheURL ] ) { jqXHR.setRequestHeader( "If-None-Match", jQuery.etag[ cacheURL ] ); } } // Set the correct header, if data is being sent if ( s.data && s.hasContent && s.contentType !== false || options.contentType ) { jqXHR.setRequestHeader( "Content-Type", s.contentType ); } // Set the Accepts header for the server, depending on the dataType jqXHR.setRequestHeader( "Accept", s.dataTypes[ 0 ] && s.accepts[ s.dataTypes[0] ] ? s.accepts[ s.dataTypes[0] ] + ( s.dataTypes[ 0 ] !== "*" ? ", " + allTypes + "; q=0.01" : "" ) : s.accepts[ "*" ] ); // Check for headers option for ( i in s.headers ) { jqXHR.setRequestHeader( i, s.headers[ i ] ); } // Allow custom headers/mimetypes and early abort if ( s.beforeSend && ( s.beforeSend.call( callbackContext, jqXHR, s ) === false || state === 2 ) ) { // Abort if not done already and return return jqXHR.abort(); } // aborting is no longer a cancellation strAbort = "abort"; // Install callbacks on deferreds for ( i in { success: 1, error: 1, complete: 1 } ) { jqXHR[ i ]( s[ i ] ); } // Get transport transport = inspectPrefiltersOrTransports( transports, s, options, jqXHR ); // If no transport, we auto-abort if ( !transport ) { done( -1, "No Transport" ); } else { jqXHR.readyState = 1; // Send global event if ( fireGlobals ) { globalEventContext.trigger( "ajaxSend", [ jqXHR, s ] ); } // Timeout if ( s.async && s.timeout > 0 ) { timeoutTimer = setTimeout(function() { jqXHR.abort("timeout"); }, s.timeout ); } try { state = 1; transport.send( requestHeaders, done ); } catch ( e ) { // Propagate exception as error if not done if ( state < 2 ) { done( -1, e ); // Simply rethrow otherwise } else { throw e; } } } // Callback for when everything is done function done( status, nativeStatusText, responses, headers ) { var isSuccess, success, error, response, modified, statusText = nativeStatusText; // Called once if ( state === 2 ) { return; } // State is "done" now state = 2; // Clear timeout if it exists if ( timeoutTimer ) { clearTimeout( timeoutTimer ); } // Dereference transport for early garbage collection // (no matter how long the jqXHR object will be used) transport = undefined; // Cache response headers responseHeadersString = headers || ""; // Set readyState jqXHR.readyState = status > 0 ? 4 : 0; // Determine if successful isSuccess = status >= 200 && status < 300 || status === 304; // Get response data if ( responses ) { response = ajaxHandleResponses( s, jqXHR, responses ); } // Convert no matter what (that way responseXXX fields are always set) response = ajaxConvert( s, response, jqXHR, isSuccess ); // If successful, handle type chaining if ( isSuccess ) { // Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode. if ( s.ifModified ) { modified = jqXHR.getResponseHeader("Last-Modified"); if ( modified ) { jQuery.lastModified[ cacheURL ] = modified; } modified = jqXHR.getResponseHeader("etag"); if ( modified ) { jQuery.etag[ cacheURL ] = modified; } } // if no content if ( status === 204 || s.type === "HEAD" ) { statusText = "nocontent"; // if not modified } else if ( status === 304 ) { statusText = "notmodified"; // If we have data, let's convert it } else { statusText = response.state; success = response.data; error = response.error; isSuccess = !error; } } else { // We extract error from statusText // then normalize statusText and status for non-aborts error = statusText; if ( status || !statusText ) { statusText = "error"; if ( status < 0 ) { status = 0; } } } // Set data for the fake xhr object jqXHR.status = status; jqXHR.statusText = ( nativeStatusText || statusText ) + ""; // Success/Error if ( isSuccess ) { deferred.resolveWith( callbackContext, [ success, statusText, jqXHR ] ); } else { deferred.rejectWith( callbackContext, [ jqXHR, statusText, error ] ); } // Status-dependent callbacks jqXHR.statusCode( statusCode ); statusCode = undefined; if ( fireGlobals ) { globalEventContext.trigger( isSuccess ? "ajaxSuccess" : "ajaxError", [ jqXHR, s, isSuccess ? success : error ] ); } // Complete completeDeferred.fireWith( callbackContext, [ jqXHR, statusText ] ); if ( fireGlobals ) { globalEventContext.trigger( "ajaxComplete", [ jqXHR, s ] ); // Handle the global AJAX counter if ( !( --jQuery.active ) ) { jQuery.event.trigger("ajaxStop"); } } } return jqXHR; }, getJSON: function( url, data, callback ) { return jQuery.get( url, data, callback, "json" ); }, getScript: function( url, callback ) { return jQuery.get( url, undefined, callback, "script" ); } }); jQuery.each( [ "get", "post" ], function( i, method ) { jQuery[ method ] = function( url, data, callback, type ) { // shift arguments if data argument was omitted if ( jQuery.isFunction( data ) ) { type = type || callback; callback = data; data = undefined; } return jQuery.ajax({ url: url, type: method, dataType: type, data: data, success: callback }); }; }); /* Handles responses to an ajax request: * - finds the right dataType (mediates between content-type and expected dataType) * - returns the corresponding response */ function ajaxHandleResponses( s, jqXHR, responses ) { var ct, type, finalDataType, firstDataType, contents = s.contents, dataTypes = s.dataTypes; // Remove auto dataType and get content-type in the process while( dataTypes[ 0 ] === "*" ) { dataTypes.shift(); if ( ct === undefined ) { ct = s.mimeType || jqXHR.getResponseHeader("Content-Type"); } } // Check if we're dealing with a known content-type if ( ct ) { for ( type in contents ) { if ( contents[ type ] && contents[ type ].test( ct ) ) { dataTypes.unshift( type ); break; } } } // Check to see if we have a response for the expected dataType if ( dataTypes[ 0 ] in responses ) { finalDataType = dataTypes[ 0 ]; } else { // Try convertible dataTypes for ( type in responses ) { if ( !dataTypes[ 0 ] || s.converters[ type + " " + dataTypes[0] ] ) { finalDataType = type; break; } if ( !firstDataType ) { firstDataType = type; } } // Or just use first one finalDataType = finalDataType || firstDataType; } // If we found a dataType // We add the dataType to the list if needed // and return the corresponding response if ( finalDataType ) { if ( finalDataType !== dataTypes[ 0 ] ) { dataTypes.unshift( finalDataType ); } return responses[ finalDataType ]; } } /* Chain conversions given the request and the original response * Also sets the responseXXX fields on the jqXHR instance */ function ajaxConvert( s, response, jqXHR, isSuccess ) { var conv2, current, conv, tmp, prev, converters = {}, // Work with a copy of dataTypes in case we need to modify it for conversion dataTypes = s.dataTypes.slice(); // Create converters map with lowercased keys if ( dataTypes[ 1 ] ) { for ( conv in s.converters ) { converters[ conv.toLowerCase() ] = s.converters[ conv ]; } } current = dataTypes.shift(); // Convert to each sequential dataType while ( current ) { if ( s.responseFields[ current ] ) { jqXHR[ s.responseFields[ current ] ] = response; } // Apply the dataFilter if provided if ( !prev && isSuccess && s.dataFilter ) { response = s.dataFilter( response, s.dataType ); } prev = current; current = dataTypes.shift(); if ( current ) { // There's only work to do if current dataType is non-auto if ( current === "*" ) { current = prev; // Convert response if prev dataType is non-auto and differs from current } else if ( prev !== "*" && prev !== current ) { // Seek a direct converter conv = converters[ prev + " " + current ] || converters[ "* " + current ]; // If none found, seek a pair if ( !conv ) { for ( conv2 in converters ) { // If conv2 outputs current tmp = conv2.split( " " ); if ( tmp[ 1 ] === current ) { // If prev can be converted to accepted input conv = converters[ prev + " " + tmp[ 0 ] ] || converters[ "* " + tmp[ 0 ] ]; if ( conv ) { // Condense equivalence converters if ( conv === true ) { conv = converters[ conv2 ]; // Otherwise, insert the intermediate dataType } else if ( converters[ conv2 ] !== true ) { current = tmp[ 0 ]; dataTypes.unshift( tmp[ 1 ] ); } break; } } } } // Apply converter (if not an equivalence) if ( conv !== true ) { // Unless errors are allowed to bubble, catch and return them if ( conv && s[ "throws" ] ) { response = conv( response ); } else { try { response = conv( response ); } catch ( e ) { return { state: "parsererror", error: conv ? e : "No conversion from " + prev + " to " + current }; } } } } } } return { state: "success", data: response }; } // Install script dataType jQuery.ajaxSetup({ accepts: { script: "text/javascript, application/javascript, application/ecmascript, application/x-ecmascript" }, contents: { script: /(?:java|ecma)script/ }, converters: { "text script": function( text ) { jQuery.globalEval( text ); return text; } } }); // Handle cache's special case and crossDomain jQuery.ajaxPrefilter( "script", function( s ) { if ( s.cache === undefined ) { s.cache = false; } if ( s.crossDomain ) { s.type = "GET"; } }); // Bind script tag hack transport jQuery.ajaxTransport( "script", function( s ) { // This transport only deals with cross domain requests if ( s.crossDomain ) { var script, callback; return { send: function( _, complete ) { script = jQuery("<script>").prop({ async: true, charset: s.scriptCharset, src: s.url }).on( "load error", callback = function( evt ) { script.remove(); callback = null; if ( evt ) { complete( evt.type === "error" ? 404 : 200, evt.type ); } } ); document.head.appendChild( script[ 0 ] ); }, abort: function() { if ( callback ) { callback(); } } }; } }); var oldCallbacks = [], rjsonp = /(=)\?(?=&|$)|\?\?/; // Default jsonp settings jQuery.ajaxSetup({ jsonp: "callback", jsonpCallback: function() { var callback = oldCallbacks.pop() || ( jQuery.expando + "_" + ( ajax_nonce++ ) ); this[ callback ] = true; return callback; } }); // Detect, normalize options and install callbacks for jsonp requests jQuery.ajaxPrefilter( "json jsonp", function( s, originalSettings, jqXHR ) { var callbackName, overwritten, responseContainer, jsonProp = s.jsonp !== false && ( rjsonp.test( s.url ) ? "url" : typeof s.data === "string" && !( s.contentType || "" ).indexOf("application/x-www-form-urlencoded") && rjsonp.test( s.data ) && "data" ); // Handle iff the expected data type is "jsonp" or we have a parameter to set if ( jsonProp || s.dataTypes[ 0 ] === "jsonp" ) { // Get callback name, remembering preexisting value associated with it callbackName = s.jsonpCallback = jQuery.isFunction( s.jsonpCallback ) ? s.jsonpCallback() : s.jsonpCallback; // Insert callback into url or form data if ( jsonProp ) { s[ jsonProp ] = s[ jsonProp ].replace( rjsonp, "$1" + callbackName ); } else if ( s.jsonp !== false ) { s.url += ( ajax_rquery.test( s.url ) ? "&" : "?" ) + s.jsonp + "=" + callbackName; } // Use data converter to retrieve json after script execution s.converters["script json"] = function() { if ( !responseContainer ) { jQuery.error( callbackName + " was not called" ); } return responseContainer[ 0 ]; }; // force json dataType s.dataTypes[ 0 ] = "json"; // Install callback overwritten = window[ callbackName ]; window[ callbackName ] = function() { responseContainer = arguments; }; // Clean-up function (fires after converters) jqXHR.always(function() { // Restore preexisting value window[ callbackName ] = overwritten; // Save back as free if ( s[ callbackName ] ) { // make sure that re-using the options doesn't screw things around s.jsonpCallback = originalSettings.jsonpCallback; // save the callback name for future use oldCallbacks.push( callbackName ); } // Call if it was a function and we have a response if ( responseContainer && jQuery.isFunction( overwritten ) ) { overwritten( responseContainer[ 0 ] ); } responseContainer = overwritten = undefined; }); // Delegate to script return "script"; } }); jQuery.ajaxSettings.xhr = function() { try { return new XMLHttpRequest(); } catch( e ) {} }; var xhrSupported = jQuery.ajaxSettings.xhr(), xhrSuccessStatus = { // file protocol always yields status code 0, assume 200 0: 200, // Support: IE9 // #1450: sometimes IE returns 1223 when it should be 204 1223: 204 }, // Support: IE9 // We need to keep track of outbound xhr and abort them manually // because IE is not smart enough to do it all by itself xhrId = 0, xhrCallbacks = {}; if ( window.ActiveXObject ) { jQuery( window ).on( "unload", function() { for( var key in xhrCallbacks ) { xhrCallbacks[ key ](); } xhrCallbacks = undefined; }); } jQuery.support.cors = !!xhrSupported && ( "withCredentials" in xhrSupported ); jQuery.support.ajax = xhrSupported = !!xhrSupported; jQuery.ajaxTransport(function( options ) { var callback; // Cross domain only allowed if supported through XMLHttpRequest if ( jQuery.support.cors || xhrSupported && !options.crossDomain ) { return { send: function( headers, complete ) { var i, id, xhr = options.xhr(); xhr.open( options.type, options.url, options.async, options.username, options.password ); // Apply custom fields if provided if ( options.xhrFields ) { for ( i in options.xhrFields ) { xhr[ i ] = options.xhrFields[ i ]; } } // Override mime type if needed if ( options.mimeType && xhr.overrideMimeType ) { xhr.overrideMimeType( options.mimeType ); } // X-Requested-With header // For cross-domain requests, seeing as conditions for a preflight are // akin to a jigsaw puzzle, we simply never set it to be sure. // (it can always be set on a per-request basis or even using ajaxSetup) // For same-domain requests, won't change header if already provided. if ( !options.crossDomain && !headers["X-Requested-With"] ) { headers["X-Requested-With"] = "XMLHttpRequest"; } // Set headers for ( i in headers ) { xhr.setRequestHeader( i, headers[ i ] ); } // Callback callback = function( type ) { return function() { if ( callback ) { delete xhrCallbacks[ id ]; callback = xhr.onload = xhr.onerror = null; if ( type === "abort" ) { xhr.abort(); } else if ( type === "error" ) { complete( // file protocol always yields status 0, assume 404 xhr.status || 404, xhr.statusText ); } else { complete( xhrSuccessStatus[ xhr.status ] || xhr.status, xhr.statusText, // Support: IE9 // #11426: When requesting binary data, IE9 will throw an exception // on any attempt to access responseText typeof xhr.responseText === "string" ? { text: xhr.responseText } : undefined, xhr.getAllResponseHeaders() ); } } }; }; // Listen to events xhr.onload = callback(); xhr.onerror = callback("error"); // Create the abort callback callback = xhrCallbacks[( id = xhrId++ )] = callback("abort"); // Do send the request // This may raise an exception which is actually // handled in jQuery.ajax (so no try/catch here) xhr.send( options.hasContent && options.data || null ); }, abort: function() { if ( callback ) { callback(); } } }; } }); var fxNow, timerId, rfxtypes = /^(?:toggle|show|hide)$/, rfxnum = new RegExp( "^(?:([+-])=|)(" + core_pnum + ")([a-z%]*)$", "i" ), rrun = /queueHooks$/, animationPrefilters = [ defaultPrefilter ], tweeners = { "*": [function( prop, value ) { var tween = this.createTween( prop, value ), target = tween.cur(), parts = rfxnum.exec( value ), unit = parts && parts[ 3 ] || ( jQuery.cssNumber[ prop ] ? "" : "px" ), // Starting value computation is required for potential unit mismatches start = ( jQuery.cssNumber[ prop ] || unit !== "px" && +target ) && rfxnum.exec( jQuery.css( tween.elem, prop ) ), scale = 1, maxIterations = 20; if ( start && start[ 3 ] !== unit ) { // Trust units reported by jQuery.css unit = unit || start[ 3 ]; // Make sure we update the tween properties later on parts = parts || []; // Iteratively approximate from a nonzero starting point start = +target || 1; do { // If previous iteration zeroed out, double until we get *something* // Use a string for doubling factor so we don't accidentally see scale as unchanged below scale = scale || ".5"; // Adjust and apply start = start / scale; jQuery.style( tween.elem, prop, start + unit ); // Update scale, tolerating zero or NaN from tween.cur() // And breaking the loop if scale is unchanged or perfect, or if we've just had enough } while ( scale !== (scale = tween.cur() / target) && scale !== 1 && --maxIterations ); } // Update tween properties if ( parts ) { start = tween.start = +start || +target || 0; tween.unit = unit; // If a +=/-= token was provided, we're doing a relative animation tween.end = parts[ 1 ] ? start + ( parts[ 1 ] + 1 ) * parts[ 2 ] : +parts[ 2 ]; } return tween; }] }; // Animations created synchronously will run synchronously function createFxNow() { setTimeout(function() { fxNow = undefined; }); return ( fxNow = jQuery.now() ); } function createTween( value, prop, animation ) { var tween, collection = ( tweeners[ prop ] || [] ).concat( tweeners[ "*" ] ), index = 0, length = collection.length; for ( ; index < length; index++ ) { if ( (tween = collection[ index ].call( animation, prop, value )) ) { // we're done with this property return tween; } } } function Animation( elem, properties, options ) { var result, stopped, index = 0, length = animationPrefilters.length, deferred = jQuery.Deferred().always( function() { // don't match elem in the :animated selector delete tick.elem; }), tick = function() { if ( stopped ) { return false; } var currentTime = fxNow || createFxNow(), remaining = Math.max( 0, animation.startTime + animation.duration - currentTime ), // archaic crash bug won't allow us to use 1 - ( 0.5 || 0 ) (#12497) temp = remaining / animation.duration || 0, percent = 1 - temp, index = 0, length = animation.tweens.length; for ( ; index < length ; index++ ) { animation.tweens[ index ].run( percent ); } deferred.notifyWith( elem, [ animation, percent, remaining ]); if ( percent < 1 && length ) { return remaining; } else { deferred.resolveWith( elem, [ animation ] ); return false; } }, animation = deferred.promise({ elem: elem, props: jQuery.extend( {}, properties ), opts: jQuery.extend( true, { specialEasing: {} }, options ), originalProperties: properties, originalOptions: options, startTime: fxNow || createFxNow(), duration: options.duration, tweens: [], createTween: function( prop, end ) { var tween = jQuery.Tween( elem, animation.opts, prop, end, animation.opts.specialEasing[ prop ] || animation.opts.easing ); animation.tweens.push( tween ); return tween; }, stop: function( gotoEnd ) { var index = 0, // if we are going to the end, we want to run all the tweens // otherwise we skip this part length = gotoEnd ? animation.tweens.length : 0; if ( stopped ) { return this; } stopped = true; for ( ; index < length ; index++ ) { animation.tweens[ index ].run( 1 ); } // resolve when we played the last frame // otherwise, reject if ( gotoEnd ) { deferred.resolveWith( elem, [ animation, gotoEnd ] ); } else { deferred.rejectWith( elem, [ animation, gotoEnd ] ); } return this; } }), props = animation.props; propFilter( props, animation.opts.specialEasing ); for ( ; index < length ; index++ ) { result = animationPrefilters[ index ].call( animation, elem, props, animation.opts ); if ( result ) { return result; } } jQuery.map( props, createTween, animation ); if ( jQuery.isFunction( animation.opts.start ) ) { animation.opts.start.call( elem, animation ); } jQuery.fx.timer( jQuery.extend( tick, { elem: elem, anim: animation, queue: animation.opts.queue }) ); // attach callbacks from options return animation.progress( animation.opts.progress ) .done( animation.opts.done, animation.opts.complete ) .fail( animation.opts.fail ) .always( animation.opts.always ); } function propFilter( props, specialEasing ) { var index, name, easing, value, hooks; // camelCase, specialEasing and expand cssHook pass for ( index in props ) { name = jQuery.camelCase( index ); easing = specialEasing[ name ]; value = props[ index ]; if ( jQuery.isArray( value ) ) { easing = value[ 1 ]; value = props[ index ] = value[ 0 ]; } if ( index !== name ) { props[ name ] = value; delete props[ index ]; } hooks = jQuery.cssHooks[ name ]; if ( hooks && "expand" in hooks ) { value = hooks.expand( value ); delete props[ name ]; // not quite $.extend, this wont overwrite keys already present. // also - reusing 'index' from above because we have the correct "name" for ( index in value ) { if ( !( index in props ) ) { props[ index ] = value[ index ]; specialEasing[ index ] = easing; } } } else { specialEasing[ name ] = easing; } } } jQuery.Animation = jQuery.extend( Animation, { tweener: function( props, callback ) { if ( jQuery.isFunction( props ) ) { callback = props; props = [ "*" ]; } else { props = props.split(" "); } var prop, index = 0, length = props.length; for ( ; index < length ; index++ ) { prop = props[ index ]; tweeners[ prop ] = tweeners[ prop ] || []; tweeners[ prop ].unshift( callback ); } }, prefilter: function( callback, prepend ) { if ( prepend ) { animationPrefilters.unshift( callback ); } else { animationPrefilters.push( callback ); } } }); function defaultPrefilter( elem, props, opts ) { /* jshint validthis: true */ var prop, value, toggle, tween, hooks, oldfire, anim = this, orig = {}, style = elem.style, hidden = elem.nodeType && isHidden( elem ), dataShow = data_priv.get( elem, "fxshow" ); // handle queue: false promises if ( !opts.queue ) { hooks = jQuery._queueHooks( elem, "fx" ); if ( hooks.unqueued == null ) { hooks.unqueued = 0; oldfire = hooks.empty.fire; hooks.empty.fire = function() { if ( !hooks.unqueued ) { oldfire(); } }; } hooks.unqueued++; anim.always(function() { // doing this makes sure that the complete handler will be called // before this completes anim.always(function() { hooks.unqueued--; if ( !jQuery.queue( elem, "fx" ).length ) { hooks.empty.fire(); } }); }); } // height/width overflow pass if ( elem.nodeType === 1 && ( "height" in props || "width" in props ) ) { // Make sure that nothing sneaks out // Record all 3 overflow attributes because IE9-10 do not // change the overflow attribute when overflowX and // overflowY are set to the same value opts.overflow = [ style.overflow, style.overflowX, style.overflowY ]; // Set display property to inline-block for height/width // animations on inline elements that are having width/height animated if ( jQuery.css( elem, "display" ) === "inline" && jQuery.css( elem, "float" ) === "none" ) { style.display = "inline-block"; } } if ( opts.overflow ) { style.overflow = "hidden"; anim.always(function() { style.overflow = opts.overflow[ 0 ]; style.overflowX = opts.overflow[ 1 ]; style.overflowY = opts.overflow[ 2 ]; }); } // show/hide pass for ( prop in props ) { value = props[ prop ]; if ( rfxtypes.exec( value ) ) { delete props[ prop ]; toggle = toggle || value === "toggle"; if ( value === ( hidden ? "hide" : "show" ) ) { // If there is dataShow left over from a stopped hide or show and we are going to proceed with show, we should pretend to be hidden if ( value === "show" && dataShow && dataShow[ prop ] !== undefined ) { hidden = true; } else { continue; } } orig[ prop ] = dataShow && dataShow[ prop ] || jQuery.style( elem, prop ); } } if ( !jQuery.isEmptyObject( orig ) ) { if ( dataShow ) { if ( "hidden" in dataShow ) { hidden = dataShow.hidden; } } else { dataShow = data_priv.access( elem, "fxshow", {} ); } // store state if its toggle - enables .stop().toggle() to "reverse" if ( toggle ) { dataShow.hidden = !hidden; } if ( hidden ) { jQuery( elem ).show(); } else { anim.done(function() { jQuery( elem ).hide(); }); } anim.done(function() { var prop; data_priv.remove( elem, "fxshow" ); for ( prop in orig ) { jQuery.style( elem, prop, orig[ prop ] ); } }); for ( prop in orig ) { tween = createTween( hidden ? dataShow[ prop ] : 0, prop, anim ); if ( !( prop in dataShow ) ) { dataShow[ prop ] = tween.start; if ( hidden ) { tween.end = tween.start; tween.start = prop === "width" || prop === "height" ? 1 : 0; } } } } } function Tween( elem, options, prop, end, easing ) { return new Tween.prototype.init( elem, options, prop, end, easing ); } jQuery.Tween = Tween; Tween.prototype = { constructor: Tween, init: function( elem, options, prop, end, easing, unit ) { this.elem = elem; this.prop = prop; this.easing = easing || "swing"; this.options = options; this.start = this.now = this.cur(); this.end = end; this.unit = unit || ( jQuery.cssNumber[ prop ] ? "" : "px" ); }, cur: function() { var hooks = Tween.propHooks[ this.prop ]; return hooks && hooks.get ? hooks.get( this ) : Tween.propHooks._default.get( this ); }, run: function( percent ) { var eased, hooks = Tween.propHooks[ this.prop ]; if ( this.options.duration ) { this.pos = eased = jQuery.easing[ this.easing ]( percent, this.options.duration * percent, 0, 1, this.options.duration ); } else { this.pos = eased = percent; } this.now = ( this.end - this.start ) * eased + this.start; if ( this.options.step ) { this.options.step.call( this.elem, this.now, this ); } if ( hooks && hooks.set ) { hooks.set( this ); } else { Tween.propHooks._default.set( this ); } return this; } }; Tween.prototype.init.prototype = Tween.prototype; Tween.propHooks = { _default: { get: function( tween ) { var result; if ( tween.elem[ tween.prop ] != null && (!tween.elem.style || tween.elem.style[ tween.prop ] == null) ) { return tween.elem[ tween.prop ]; } // passing an empty string as a 3rd parameter to .css will automatically // attempt a parseFloat and fallback to a string if the parse fails // so, simple values such as "10px" are parsed to Float. // complex values such as "rotate(1rad)" are returned as is. result = jQuery.css( tween.elem, tween.prop, "" ); // Empty strings, null, undefined and "auto" are converted to 0. return !result || result === "auto" ? 0 : result; }, set: function( tween ) { // use step hook for back compat - use cssHook if its there - use .style if its // available and use plain properties where available if ( jQuery.fx.step[ tween.prop ] ) { jQuery.fx.step[ tween.prop ]( tween ); } else if ( tween.elem.style && ( tween.elem.style[ jQuery.cssProps[ tween.prop ] ] != null || jQuery.cssHooks[ tween.prop ] ) ) { jQuery.style( tween.elem, tween.prop, tween.now + tween.unit ); } else { tween.elem[ tween.prop ] = tween.now; } } } }; // Support: IE9 // Panic based approach to setting things on disconnected nodes Tween.propHooks.scrollTop = Tween.propHooks.scrollLeft = { set: function( tween ) { if ( tween.elem.nodeType && tween.elem.parentNode ) { tween.elem[ tween.prop ] = tween.now; } } }; jQuery.each([ "toggle", "show", "hide" ], function( i, name ) { var cssFn = jQuery.fn[ name ]; jQuery.fn[ name ] = function( speed, easing, callback ) { return speed == null || typeof speed === "boolean" ? cssFn.apply( this, arguments ) : this.animate( genFx( name, true ), speed, easing, callback ); }; }); jQuery.fn.extend({ fadeTo: function( speed, to, easing, callback ) { // show any hidden elements after setting opacity to 0 return this.filter( isHidden ).css( "opacity", 0 ).show() // animate to the value specified .end().animate({ opacity: to }, speed, easing, callback ); }, animate: function( prop, speed, easing, callback ) { var empty = jQuery.isEmptyObject( prop ), optall = jQuery.speed( speed, easing, callback ), doAnimation = function() { // Operate on a copy of prop so per-property easing won't be lost var anim = Animation( this, jQuery.extend( {}, prop ), optall ); // Empty animations, or finishing resolves immediately if ( empty || data_priv.get( this, "finish" ) ) { anim.stop( true ); } }; doAnimation.finish = doAnimation; return empty || optall.queue === false ? this.each( doAnimation ) : this.queue( optall.queue, doAnimation ); }, stop: function( type, clearQueue, gotoEnd ) { var stopQueue = function( hooks ) { var stop = hooks.stop; delete hooks.stop; stop( gotoEnd ); }; if ( typeof type !== "string" ) { gotoEnd = clearQueue; clearQueue = type; type = undefined; } if ( clearQueue && type !== false ) { this.queue( type || "fx", [] ); } return this.each(function() { var dequeue = true, index = type != null && type + "queueHooks", timers = jQuery.timers, data = data_priv.get( this ); if ( index ) { if ( data[ index ] && data[ index ].stop ) { stopQueue( data[ index ] ); } } else { for ( index in data ) { if ( data[ index ] && data[ index ].stop && rrun.test( index ) ) { stopQueue( data[ index ] ); } } } for ( index = timers.length; index--; ) { if ( timers[ index ].elem === this && (type == null || timers[ index ].queue === type) ) { timers[ index ].anim.stop( gotoEnd ); dequeue = false; timers.splice( index, 1 ); } } // start the next in the queue if the last step wasn't forced // timers currently will call their complete callbacks, which will dequeue // but only if they were gotoEnd if ( dequeue || !gotoEnd ) { jQuery.dequeue( this, type ); } }); }, finish: function( type ) { if ( type !== false ) { type = type || "fx"; } return this.each(function() { var index, data = data_priv.get( this ), queue = data[ type + "queue" ], hooks = data[ type + "queueHooks" ], timers = jQuery.timers, length = queue ? queue.length : 0; // enable finishing flag on private data data.finish = true; // empty the queue first jQuery.queue( this, type, [] ); if ( hooks && hooks.stop ) { hooks.stop.call( this, true ); } // look for any active animations, and finish them for ( index = timers.length; index--; ) { if ( timers[ index ].elem === this && timers[ index ].queue === type ) { timers[ index ].anim.stop( true ); timers.splice( index, 1 ); } } // look for any animations in the old queue and finish them for ( index = 0; index < length; index++ ) { if ( queue[ index ] && queue[ index ].finish ) { queue[ index ].finish.call( this ); } } // turn off finishing flag delete data.finish; }); } }); // Generate parameters to create a standard animation function genFx( type, includeWidth ) { var which, attrs = { height: type }, i = 0; // if we include width, step value is 1 to do all cssExpand values, // if we don't include width, step value is 2 to skip over Left and Right includeWidth = includeWidth? 1 : 0; for( ; i < 4 ; i += 2 - includeWidth ) { which = cssExpand[ i ]; attrs[ "margin" + which ] = attrs[ "padding" + which ] = type; } if ( includeWidth ) { attrs.opacity = attrs.width = type; } return attrs; } // Generate shortcuts for custom animations jQuery.each({ slideDown: genFx("show"), slideUp: genFx("hide"), slideToggle: genFx("toggle"), fadeIn: { opacity: "show" }, fadeOut: { opacity: "hide" }, fadeToggle: { opacity: "toggle" } }, function( name, props ) { jQuery.fn[ name ] = function( speed, easing, callback ) { return this.animate( props, speed, easing, callback ); }; }); jQuery.speed = function( speed, easing, fn ) { var opt = speed && typeof speed === "object" ? jQuery.extend( {}, speed ) : { complete: fn || !fn && easing || jQuery.isFunction( speed ) && speed, duration: speed, easing: fn && easing || easing && !jQuery.isFunction( easing ) && easing }; opt.duration = jQuery.fx.off ? 0 : typeof opt.duration === "number" ? opt.duration : opt.duration in jQuery.fx.speeds ? jQuery.fx.speeds[ opt.duration ] : jQuery.fx.speeds._default; // normalize opt.queue - true/undefined/null -> "fx" if ( opt.queue == null || opt.queue === true ) { opt.queue = "fx"; } // Queueing opt.old = opt.complete; opt.complete = function() { if ( jQuery.isFunction( opt.old ) ) { opt.old.call( this ); } if ( opt.queue ) { jQuery.dequeue( this, opt.queue ); } }; return opt; }; jQuery.easing = { linear: function( p ) { return p; }, swing: function( p ) { return 0.5 - Math.cos( p*Math.PI ) / 2; } }; jQuery.timers = []; jQuery.fx = Tween.prototype.init; jQuery.fx.tick = function() { var timer, timers = jQuery.timers, i = 0; fxNow = jQuery.now(); for ( ; i < timers.length; i++ ) { timer = timers[ i ]; // Checks the timer has not already been removed if ( !timer() && timers[ i ] === timer ) { timers.splice( i--, 1 ); } } if ( !timers.length ) { jQuery.fx.stop(); } fxNow = undefined; }; jQuery.fx.timer = function( timer ) { if ( timer() && jQuery.timers.push( timer ) ) { jQuery.fx.start(); } }; jQuery.fx.interval = 13; jQuery.fx.start = function() { if ( !timerId ) { timerId = setInterval( jQuery.fx.tick, jQuery.fx.interval ); } }; jQuery.fx.stop = function() { clearInterval( timerId ); timerId = null; }; jQuery.fx.speeds = { slow: 600, fast: 200, // Default speed _default: 400 }; // Back Compat <1.8 extension point jQuery.fx.step = {}; if ( jQuery.expr && jQuery.expr.filters ) { jQuery.expr.filters.animated = function( elem ) { return jQuery.grep(jQuery.timers, function( fn ) { return elem === fn.elem; }).length; }; } jQuery.fn.offset = function( options ) { if ( arguments.length ) { return options === undefined ? this : this.each(function( i ) { jQuery.offset.setOffset( this, options, i ); }); } var docElem, win, elem = this[ 0 ], box = { top: 0, left: 0 }, doc = elem && elem.ownerDocument; if ( !doc ) { return; } docElem = doc.documentElement; // Make sure it's not a disconnected DOM node if ( !jQuery.contains( docElem, elem ) ) { return box; } // If we don't have gBCR, just use 0,0 rather than error // BlackBerry 5, iOS 3 (original iPhone) if ( typeof elem.getBoundingClientRect !== core_strundefined ) { box = elem.getBoundingClientRect(); } win = getWindow( doc ); return { top: box.top + win.pageYOffset - docElem.clientTop, left: box.left + win.pageXOffset - docElem.clientLeft }; }; jQuery.offset = { setOffset: function( elem, options, i ) { var curPosition, curLeft, curCSSTop, curTop, curOffset, curCSSLeft, calculatePosition, position = jQuery.css( elem, "position" ), curElem = jQuery( elem ), props = {}; // Set position first, in-case top/left are set even on static elem if ( position === "static" ) { elem.style.position = "relative"; } curOffset = curElem.offset(); curCSSTop = jQuery.css( elem, "top" ); curCSSLeft = jQuery.css( elem, "left" ); calculatePosition = ( position === "absolute" || position === "fixed" ) && ( curCSSTop + curCSSLeft ).indexOf("auto") > -1; // Need to be able to calculate position if either top or left is auto and position is either absolute or fixed if ( calculatePosition ) { curPosition = curElem.position(); curTop = curPosition.top; curLeft = curPosition.left; } else { curTop = parseFloat( curCSSTop ) || 0; curLeft = parseFloat( curCSSLeft ) || 0; } if ( jQuery.isFunction( options ) ) { options = options.call( elem, i, curOffset ); } if ( options.top != null ) { props.top = ( options.top - curOffset.top ) + curTop; } if ( options.left != null ) { props.left = ( options.left - curOffset.left ) + curLeft; } if ( "using" in options ) { options.using.call( elem, props ); } else { curElem.css( props ); } } }; jQuery.fn.extend({ position: function() { if ( !this[ 0 ] ) { return; } var offsetParent, offset, elem = this[ 0 ], parentOffset = { top: 0, left: 0 }; // Fixed elements are offset from window (parentOffset = {top:0, left: 0}, because it is it's only offset parent if ( jQuery.css( elem, "position" ) === "fixed" ) { // We assume that getBoundingClientRect is available when computed position is fixed offset = elem.getBoundingClientRect(); } else { // Get *real* offsetParent offsetParent = this.offsetParent(); // Get correct offsets offset = this.offset(); if ( !jQuery.nodeName( offsetParent[ 0 ], "html" ) ) { parentOffset = offsetParent.offset(); } // Add offsetParent borders parentOffset.top += jQuery.css( offsetParent[ 0 ], "borderTopWidth", true ); parentOffset.left += jQuery.css( offsetParent[ 0 ], "borderLeftWidth", true ); } // Subtract parent offsets and element margins return { top: offset.top - parentOffset.top - jQuery.css( elem, "marginTop", true ), left: offset.left - parentOffset.left - jQuery.css( elem, "marginLeft", true ) }; }, offsetParent: function() { return this.map(function() { var offsetParent = this.offsetParent || docElem; while ( offsetParent && ( !jQuery.nodeName( offsetParent, "html" ) && jQuery.css( offsetParent, "position") === "static" ) ) { offsetParent = offsetParent.offsetParent; } return offsetParent || docElem; }); } }); // Create scrollLeft and scrollTop methods jQuery.each( {scrollLeft: "pageXOffset", scrollTop: "pageYOffset"}, function( method, prop ) { var top = "pageYOffset" === prop; jQuery.fn[ method ] = function( val ) { return jQuery.access( this, function( elem, method, val ) { var win = getWindow( elem ); if ( val === undefined ) { return win ? win[ prop ] : elem[ method ]; } if ( win ) { win.scrollTo( !top ? val : window.pageXOffset, top ? val : window.pageYOffset ); } else { elem[ method ] = val; } }, method, val, arguments.length, null ); }; }); function getWindow( elem ) { return jQuery.isWindow( elem ) ? elem : elem.nodeType === 9 && elem.defaultView; } // Create innerHeight, innerWidth, height, width, outerHeight and outerWidth methods jQuery.each( { Height: "height", Width: "width" }, function( name, type ) { jQuery.each( { padding: "inner" + name, content: type, "": "outer" + name }, function( defaultExtra, funcName ) { // margin is only for outerHeight, outerWidth jQuery.fn[ funcName ] = function( margin, value ) { var chainable = arguments.length && ( defaultExtra || typeof margin !== "boolean" ), extra = defaultExtra || ( margin === true || value === true ? "margin" : "border" ); return jQuery.access( this, function( elem, type, value ) { var doc; if ( jQuery.isWindow( elem ) ) { // As of 5/8/2012 this will yield incorrect results for Mobile Safari, but there // isn't a whole lot we can do. See pull request at this URL for discussion: // https://github.com/jquery/jquery/pull/764 return elem.document.documentElement[ "client" + name ]; } // Get document width or height if ( elem.nodeType === 9 ) { doc = elem.documentElement; // Either scroll[Width/Height] or offset[Width/Height] or client[Width/Height], // whichever is greatest return Math.max( elem.body[ "scroll" + name ], doc[ "scroll" + name ], elem.body[ "offset" + name ], doc[ "offset" + name ], doc[ "client" + name ] ); } return value === undefined ? // Get width or height on the element, requesting but not forcing parseFloat jQuery.css( elem, type, extra ) : // Set width or height on the element jQuery.style( elem, type, value, extra ); }, type, chainable ? margin : undefined, chainable, null ); }; }); }); // Limit scope pollution from any deprecated API // (function() { // The number of elements contained in the matched element set jQuery.fn.size = function() { return this.length; }; jQuery.fn.andSelf = jQuery.fn.addBack; // })(); if ( typeof module === "object" && module && typeof module.exports === "object" ) { // Expose jQuery as module.exports in loaders that implement the Node // module pattern (including browserify). Do not create the global, since // the user will be storing it themselves locally, and globals are frowned // upon in the Node module world. module.exports = jQuery; } else { // Register as a named AMD module, since jQuery can be concatenated with other // files that may use define, but not via a proper concatenation script that // understands anonymous AMD modules. A named AMD is safest and most robust // way to register. Lowercase jquery is used because AMD module names are // derived from file names, and jQuery is normally delivered in a lowercase // file name. Do this after creating the global so that if an AMD module wants // to call noConflict to hide this version of jQuery, it will work. if ( typeof define === "function" && define.amd ) { define( "jquery", [], function () { return jQuery; } ); } } // If there is a window object, that at least has a document property, // define jQuery and $ identifiers if ( typeof window === "object" && typeof window.document === "object" ) { window.jQuery = window.$ = jQuery; } })( window ); /** * @license * Lo-Dash 2.2.1 (Custom Build) <http://lodash.com/> * Build: `lodash modern -o ./dist/lodash.js` * Copyright 2012-2013 The Dojo Foundation <http://dojofoundation.org/> * Based on Underscore.js 1.5.2 <http://underscorejs.org/LICENSE> * Copyright 2009-2013 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors * Available under MIT license <http://lodash.com/license> */ ;(function() { /** Used as a safe reference for `undefined` in pre ES5 environments */ var undefined; /** Used to pool arrays and objects used internally */ var arrayPool = [], objectPool = []; /** Used to generate unique IDs */ var idCounter = 0; /** Used to prefix keys to avoid issues with `__proto__` and properties on `Object.prototype` */ var keyPrefix = +new Date + ''; /** Used as the size when optimizations are enabled for large arrays */ var largeArraySize = 75; /** Used as the max size of the `arrayPool` and `objectPool` */ var maxPoolSize = 40; /** Used to detect and test whitespace */ var whitespace = ( // whitespace ' \t\x0B\f\xA0\ufeff' + // line terminators '\n\r\u2028\u2029' + // unicode category "Zs" space separators '\u1680\u180e\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u202f\u205f\u3000' ); /** Used to match empty string literals in compiled template source */ var reEmptyStringLeading = /\b__p \+= '';/g, reEmptyStringMiddle = /\b(__p \+=) '' \+/g, reEmptyStringTrailing = /(__e\(.*?\)|\b__t\)) \+\n'';/g; /** * Used to match ES6 template delimiters * http://people.mozilla.org/~jorendorff/es6-draft.html#sec-7.8.6 */ var reEsTemplate = /\$\{([^\\}]*(?:\\.[^\\}]*)*)\}/g; /** Used to match regexp flags from their coerced string values */ var reFlags = /\w*$/; /** Used to detected named functions */ var reFuncName = /^function[ \n\r\t]+\w/; /** Used to match "interpolate" template delimiters */ var reInterpolate = /<%=([\s\S]+?)%>/g; /** Used to match leading whitespace and zeros to be removed */ var reLeadingSpacesAndZeros = RegExp('^[' + whitespace + ']*0+(?=.$)'); /** Used to ensure capturing order of template delimiters */ var reNoMatch = /($^)/; /** Used to detect functions containing a `this` reference */ var reThis = /\bthis\b/; /** Used to match unescaped characters in compiled string literals */ var reUnescapedString = /['\n\r\t\u2028\u2029\\]/g; /** Used to assign default `context` object properties */ var contextProps = [ 'Array', 'Boolean', 'Date', 'Function', 'Math', 'Number', 'Object', 'RegExp', 'String', '_', 'attachEvent', 'clearTimeout', 'isFinite', 'isNaN', 'parseInt', 'setImmediate', 'setTimeout' ]; /** Used to make template sourceURLs easier to identify */ var templateCounter = 0; /** `Object#toString` result shortcuts */ var argsClass = '[object Arguments]', arrayClass = '[object Array]', boolClass = '[object Boolean]', dateClass = '[object Date]', funcClass = '[object Function]', numberClass = '[object Number]', objectClass = '[object Object]', regexpClass = '[object RegExp]', stringClass = '[object String]'; /** Used to identify object classifications that `_.clone` supports */ var cloneableClasses = {}; cloneableClasses[funcClass] = false; cloneableClasses[argsClass] = cloneableClasses[arrayClass] = cloneableClasses[boolClass] = cloneableClasses[dateClass] = cloneableClasses[numberClass] = cloneableClasses[objectClass] = cloneableClasses[regexpClass] = cloneableClasses[stringClass] = true; /** Used as an internal `_.debounce` options object */ var debounceOptions = { 'leading': false, 'maxWait': 0, 'trailing': false }; /** Used as the property descriptor for `__bindData__` */ var descriptor = { 'configurable': false, 'enumerable': false, 'value': null, 'writable': false }; /** Used to determine if values are of the language type Object */ var objectTypes = { 'boolean': false, 'function': true, 'object': true, 'number': false, 'string': false, 'undefined': false }; /** Used to escape characters for inclusion in compiled string literals */ var stringEscapes = { '\\': '\\', "'": "'", '\n': 'n', '\r': 'r', '\t': 't', '\u2028': 'u2028', '\u2029': 'u2029' }; /** Used as a reference to the global object */ var root = (objectTypes[typeof window] && window) || this; /** Detect free variable `exports` */ var freeExports = objectTypes[typeof exports] && exports && !exports.nodeType && exports; /** Detect free variable `module` */ var freeModule = objectTypes[typeof module] && module && !module.nodeType && module; /** Detect the popular CommonJS extension `module.exports` */ var moduleExports = freeModule && freeModule.exports === freeExports && freeExports; /** Detect free variable `global` from Node.js or Browserified code and use it as `root` */ var freeGlobal = objectTypes[typeof global] && global; if (freeGlobal && (freeGlobal.global === freeGlobal || freeGlobal.window === freeGlobal)) { root = freeGlobal; } /*--------------------------------------------------------------------------*/ /** * The base implementation of `_.indexOf` without support for binary searches * or `fromIndex` constraints. * * @private * @param {Array} array The array to search. * @param {*} value The value to search for. * @param {number} [fromIndex=0] The index to search from. * @returns {number} Returns the index of the matched value or `-1`. */ function baseIndexOf(array, value, fromIndex) { var index = (fromIndex || 0) - 1, length = array ? array.length : 0; while (++index < length) { if (array[index] === value) { return index; } } return -1; } /** * An implementation of `_.contains` for cache objects that mimics the return * signature of `_.indexOf` by returning `0` if the value is found, else `-1`. * * @private * @param {Object} cache The cache object to inspect. * @param {*} value The value to search for. * @returns {number} Returns `0` if `value` is found, else `-1`. */ function cacheIndexOf(cache, value) { var type = typeof value; cache = cache.cache; if (type == 'boolean' || value == null) { return cache[value] ? 0 : -1; } if (type != 'number' && type != 'string') { type = 'object'; } var key = type == 'number' ? value : keyPrefix + value; cache = (cache = cache[type]) && cache[key]; return type == 'object' ? (cache && baseIndexOf(cache, value) > -1 ? 0 : -1) : (cache ? 0 : -1); } /** * Adds a given value to the corresponding cache object. * * @private * @param {*} value The value to add to the cache. */ function cachePush(value) { var cache = this.cache, type = typeof value; if (type == 'boolean' || value == null) { cache[value] = true; } else { if (type != 'number' && type != 'string') { type = 'object'; } var key = type == 'number' ? value : keyPrefix + value, typeCache = cache[type] || (cache[type] = {}); if (type == 'object') { (typeCache[key] || (typeCache[key] = [])).push(value); } else { typeCache[key] = true; } } } /** * Used by `_.max` and `_.min` as the default callback when a given * collection is a string value. * * @private * @param {string} value The character to inspect. * @returns {number} Returns the code unit of given character. */ function charAtCallback(value) { return value.charCodeAt(0); } /** * Used by `sortBy` to compare transformed `collection` elements, stable sorting * them in ascending order. * * @private * @param {Object} a The object to compare to `b`. * @param {Object} b The object to compare to `a`. * @returns {number} Returns the sort order indicator of `1` or `-1`. */ function compareAscending(a, b) { var ac = a.criteria, bc = b.criteria; // ensure a stable sort in V8 and other engines // http://code.google.com/p/v8/issues/detail?id=90 if (ac !== bc) { if (ac > bc || typeof ac == 'undefined') { return 1; } if (ac < bc || typeof bc == 'undefined') { return -1; } } // The JS engine embedded in Adobe applications like InDesign has a buggy // `Array#sort` implementation that causes it, under certain circumstances, // to return the same value for `a` and `b`. // See https://github.com/jashkenas/underscore/pull/1247 return a.index - b.index; } /** * Creates a cache object to optimize linear searches of large arrays. * * @private * @param {Array} [array=[]] The array to search. * @returns {null|Object} Returns the cache object or `null` if caching should not be used. */ function createCache(array) { var index = -1, length = array.length, first = array[0], mid = array[(length / 2) | 0], last = array[length - 1]; if (first && typeof first == 'object' && mid && typeof mid == 'object' && last && typeof last == 'object') { return false; } var cache = getObject(); cache['false'] = cache['null'] = cache['true'] = cache['undefined'] = false; var result = getObject(); result.array = array; result.cache = cache; result.push = cachePush; while (++index < length) { result.push(array[index]); } return result; } /** * Used by `template` to escape characters for inclusion in compiled * string literals. * * @private * @param {string} match The matched character to escape. * @returns {string} Returns the escaped character. */ function escapeStringChar(match) { return '\\' + stringEscapes[match]; } /** * Gets an array from the array pool or creates a new one if the pool is empty. * * @private * @returns {Array} The array from the pool. */ function getArray() { return arrayPool.pop() || []; } /** * Gets an object from the object pool or creates a new one if the pool is empty. * * @private * @returns {Object} The object from the pool. */ function getObject() { return objectPool.pop() || { 'array': null, 'cache': null, 'criteria': null, 'false': false, 'index': 0, 'null': false, 'number': null, 'object': null, 'push': null, 'string': null, 'true': false, 'undefined': false, 'value': null }; } /** * A no-operation function. * * @private */ function noop() { // no operation performed } /** * Releases the given array back to the array pool. * * @private * @param {Array} [array] The array to release. */ function releaseArray(array) { array.length = 0; if (arrayPool.length < maxPoolSize) { arrayPool.push(array); } } /** * Releases the given object back to the object pool. * * @private * @param {Object} [object] The object to release. */ function releaseObject(object) { var cache = object.cache; if (cache) { releaseObject(cache); } object.array = object.cache = object.criteria = object.object = object.number = object.string = object.value = null; if (objectPool.length < maxPoolSize) { objectPool.push(object); } } /** * Slices the `collection` from the `start` index up to, but not including, * the `end` index. * * Note: This function is used instead of `Array#slice` to support node lists * in IE < 9 and to ensure dense arrays are returned. * * @private * @param {Array|Object|string} collection The collection to slice. * @param {number} start The start index. * @param {number} end The end index. * @returns {Array} Returns the new array. */ function slice(array, start, end) { start || (start = 0); if (typeof end == 'undefined') { end = array ? array.length : 0; } var index = -1, length = end - start || 0, result = Array(length < 0 ? 0 : length); while (++index < length) { result[index] = array[start + index]; } return result; } /*--------------------------------------------------------------------------*/ /** * Create a new `lodash` function using the given context object. * * @static * @memberOf _ * @category Utilities * @param {Object} [context=root] The context object. * @returns {Function} Returns the `lodash` function. */ function runInContext(context) { // Avoid issues with some ES3 environments that attempt to use values, named // after built-in constructors like `Object`, for the creation of literals. // ES5 clears this up by stating that literals must use built-in constructors. // See http://es5.github.io/#x11.1.5. context = context ? _.defaults(root.Object(), context, _.pick(root, contextProps)) : root; /** Native constructor references */ var Array = context.Array, Boolean = context.Boolean, Date = context.Date, Function = context.Function, Math = context.Math, Number = context.Number, Object = context.Object, RegExp = context.RegExp, String = context.String, TypeError = context.TypeError; /** * Used for `Array` method references. * * Normally `Array.prototype` would suffice, however, using an array literal * avoids issues in Narwhal. */ var arrayRef = []; /** Used for native method references */ var objectProto = Object.prototype; /** Used to restore the original `_` reference in `noConflict` */ var oldDash = context._; /** Used to detect if a method is native */ var reNative = RegExp('^' + String(objectProto.valueOf) .replace(/[.*+?^${}()|[\]\\]/g, '\\$&') .replace(/valueOf|for [^\]]+/g, '.+?') + '$' ); /** Native method shortcuts */ var ceil = Math.ceil, clearTimeout = context.clearTimeout, floor = Math.floor, fnToString = Function.prototype.toString, getPrototypeOf = reNative.test(getPrototypeOf = Object.getPrototypeOf) && getPrototypeOf, hasOwnProperty = objectProto.hasOwnProperty, now = reNative.test(now = Date.now) && now || function() { return +new Date; }, push = arrayRef.push, setImmediate = context.setImmediate, setTimeout = context.setTimeout, splice = arrayRef.splice, toString = objectProto.toString, unshift = arrayRef.unshift; var defineProperty = (function() { try { var o = {}, func = reNative.test(func = Object.defineProperty) && func, result = func(o, o, o) && func; } catch(e) { } return result; }()); /* Native method shortcuts for methods with the same name as other `lodash` methods */ var nativeBind = reNative.test(nativeBind = toString.bind) && nativeBind, nativeCreate = reNative.test(nativeCreate = Object.create) && nativeCreate, nativeIsArray = reNative.test(nativeIsArray = Array.isArray) && nativeIsArray, nativeIsFinite = context.isFinite, nativeIsNaN = context.isNaN, nativeKeys = reNative.test(nativeKeys = Object.keys) && nativeKeys, nativeMax = Math.max, nativeMin = Math.min, nativeParseInt = context.parseInt, nativeRandom = Math.random, nativeSlice = arrayRef.slice; /** Detect various environments */ var isIeOpera = reNative.test(context.attachEvent), isV8 = nativeBind && !/\n|true/.test(nativeBind + isIeOpera); /** Used to lookup a built-in constructor by [[Class]] */ var ctorByClass = {}; ctorByClass[arrayClass] = Array; ctorByClass[boolClass] = Boolean; ctorByClass[dateClass] = Date; ctorByClass[funcClass] = Function; ctorByClass[objectClass] = Object; ctorByClass[numberClass] = Number; ctorByClass[regexpClass] = RegExp; ctorByClass[stringClass] = String; /*--------------------------------------------------------------------------*/ /** * Creates a `lodash` object which wraps the given value to enable intuitive * method chaining. * * In addition to Lo-Dash methods, wrappers also have the following `Array` methods: * `concat`, `join`, `pop`, `push`, `reverse`, `shift`, `slice`, `sort`, `splice`, * and `unshift` * * Chaining is supported in custom builds as long as the `value` method is * implicitly or explicitly included in the build. * * The chainable wrapper functions are: * `after`, `assign`, `bind`, `bindAll`, `bindKey`, `chain`, `compact`, * `compose`, `concat`, `countBy`, `createCallback`, `curry`, `debounce`, * `defaults`, `defer`, `delay`, `difference`, `filter`, `flatten`, `forEach`, * `forEachRight`, `forIn`, `forInRight`, `forOwn`, `forOwnRight`, `functions`, * `groupBy`, `indexBy`, `initial`, `intersection`, `invert`, `invoke`, `keys`, * `map`, `max`, `memoize`, `merge`, `min`, `object`, `omit`, `once`, `pairs`, * `partial`, `partialRight`, `pick`, `pluck`, `pull`, `push`, `range`, `reject`, * `remove`, `rest`, `reverse`, `shuffle`, `slice`, `sort`, `sortBy`, `splice`, * `tap`, `throttle`, `times`, `toArray`, `transform`, `union`, `uniq`, `unshift`, * `unzip`, `values`, `where`, `without`, `wrap`, and `zip` * * The non-chainable wrapper functions are: * `clone`, `cloneDeep`, `contains`, `escape`, `every`, `find`, `findIndex`, * `findKey`, `findLast`, `findLastIndex`, `findLastKey`, `has`, `identity`, * `indexOf`, `isArguments`, `isArray`, `isBoolean`, `isDate`, `isElement`, * `isEmpty`, `isEqual`, `isFinite`, `isFunction`, `isNaN`, `isNull`, `isNumber`, * `isObject`, `isPlainObject`, `isRegExp`, `isString`, `isUndefined`, `join`, * `lastIndexOf`, `mixin`, `noConflict`, `parseInt`, `pop`, `random`, `reduce`, * `reduceRight`, `result`, `shift`, `size`, `some`, `sortedIndex`, `runInContext`, * `template`, `unescape`, `uniqueId`, and `value` * * The wrapper functions `first` and `last` return wrapped values when `n` is * provided, otherwise they return unwrapped values. * * Explicit chaining can be enabled by using the `_.chain` method. * * @name _ * @constructor * @category Chaining * @param {*} value The value to wrap in a `lodash` instance. * @returns {Object} Returns a `lodash` instance. * @example * * var wrapped = _([1, 2, 3]); * * // returns an unwrapped value * wrapped.reduce(function(sum, num) { * return sum + num; * }); * // => 6 * * // returns a wrapped value * var squares = wrapped.map(function(num) { * return num * num; * }); * * _.isArray(squares); * // => false * * _.isArray(squares.value()); * // => true */ function lodash(value) { // don't wrap if already wrapped, even if wrapped by a different `lodash` constructor return (value && typeof value == 'object' && !isArray(value) && hasOwnProperty.call(value, '__wrapped__')) ? value : new lodashWrapper(value); } /** * A fast path for creating `lodash` wrapper objects. * * @private * @param {*} value The value to wrap in a `lodash` instance. * @param {boolean} chainAll A flag to enable chaining for all methods * @returns {Object} Returns a `lodash` instance. */ function lodashWrapper(value, chainAll) { this.__chain__ = !!chainAll; this.__wrapped__ = value; } // ensure `new lodashWrapper` is an instance of `lodash` lodashWrapper.prototype = lodash.prototype; /** * An object used to flag environments features. * * @static * @memberOf _ * @type Object */ var support = lodash.support = {}; /** * Detect if `Function#bind` exists and is inferred to be fast (all but V8). * * @memberOf _.support * @type boolean */ support.fastBind = nativeBind && !isV8; /** * Detect if functions can be decompiled by `Function#toString` * (all but PS3 and older Opera mobile browsers & avoided in Windows 8 apps). * * @memberOf _.support * @type boolean */ support.funcDecomp = !reNative.test(context.WinRTError) && reThis.test(runInContext); /** * Detect if `Function#name` is supported (all but IE). * * @memberOf _.support * @type boolean */ support.funcNames = typeof Function.name == 'string'; /** * By default, the template delimiters used by Lo-Dash are similar to those in * embedded Ruby (ERB). Change the following template settings to use alternative * delimiters. * * @static * @memberOf _ * @type Object */ lodash.templateSettings = { /** * Used to detect `data` property values to be HTML-escaped. * * @memberOf _.templateSettings * @type RegExp */ 'escape': /<%-([\s\S]+?)%>/g, /** * Used to detect code to be evaluated. * * @memberOf _.templateSettings * @type RegExp */ 'evaluate': /<%([\s\S]+?)%>/g, /** * Used to detect `data` property values to inject. * * @memberOf _.templateSettings * @type RegExp */ 'interpolate': reInterpolate, /** * Used to reference the data object in the template text. * * @memberOf _.templateSettings * @type string */ 'variable': '', /** * Used to import variables into the compiled template. * * @memberOf _.templateSettings * @type Object */ 'imports': { /** * A reference to the `lodash` function. * * @memberOf _.templateSettings.imports * @type Function */ '_': lodash } }; /*--------------------------------------------------------------------------*/ /** * The base implementation of `_.clone` without argument juggling or support * for `thisArg` binding. * * @private * @param {*} value The value to clone. * @param {boolean} [deep=false] Specify a deep clone. * @param {Function} [callback] The function to customize cloning values. * @param {Array} [stackA=[]] Tracks traversed source objects. * @param {Array} [stackB=[]] Associates clones with source counterparts. * @returns {*} Returns the cloned value. */ function baseClone(value, deep, callback, stackA, stackB) { if (callback) { var result = callback(value); if (typeof result != 'undefined') { return result; } } // inspect [[Class]] var isObj = isObject(value); if (isObj) { var className = toString.call(value); if (!cloneableClasses[className]) { return value; } var ctor = ctorByClass[className]; switch (className) { case boolClass: case dateClass: return new ctor(+value); case numberClass: case stringClass: return new ctor(value); case regexpClass: result = ctor(value.source, reFlags.exec(value)); result.lastIndex = value.lastIndex; return result; } } else { return value; } var isArr = isArray(value); if (deep) { // check for circular references and return corresponding clone var initedStack = !stackA; stackA || (stackA = getArray()); stackB || (stackB = getArray()); var length = stackA.length; while (length--) { if (stackA[length] == value) { return stackB[length]; } } result = isArr ? ctor(value.length) : {}; } else { result = isArr ? slice(value) : assign({}, value); } // add array properties assigned by `RegExp#exec` if (isArr) { if (hasOwnProperty.call(value, 'index')) { result.index = value.index; } if (hasOwnProperty.call(value, 'input')) { result.input = value.input; } } // exit for shallow clone if (!deep) { return result; } // add the source value to the stack of traversed objects // and associate it with its clone stackA.push(value); stackB.push(result); // recursively populate clone (susceptible to call stack limits) (isArr ? forEach : forOwn)(value, function(objValue, key) { result[key] = baseClone(objValue, deep, callback, stackA, stackB); }); if (initedStack) { releaseArray(stackA); releaseArray(stackB); } return result; } /** * The base implementation of `_.createCallback` without support for creating * "_.pluck" or "_.where" style callbacks. * * @private * @param {*} [func=identity] The value to convert to a callback. * @param {*} [thisArg] The `this` binding of the created callback. * @param {number} [argCount] The number of arguments the callback accepts. * @returns {Function} Returns a callback function. */ function baseCreateCallback(func, thisArg, argCount) { if (typeof func != 'function') { return identity; } // exit early if there is no `thisArg` if (typeof thisArg == 'undefined') { return func; } var bindData = func.__bindData__ || (support.funcNames && !func.name); if (typeof bindData == 'undefined') { var source = reThis && fnToString.call(func); if (!support.funcNames && source && !reFuncName.test(source)) { bindData = true; } if (support.funcNames || !bindData) { // checks if `func` references the `this` keyword and stores the result bindData = !support.funcDecomp || reThis.test(source); setBindData(func, bindData); } } // exit early if there are no `this` references or `func` is bound if (bindData !== true && (bindData && bindData[1] & 1)) { return func; } switch (argCount) { case 1: return function(value) { return func.call(thisArg, value); }; case 2: return function(a, b) { return func.call(thisArg, a, b); }; case 3: return function(value, index, collection) { return func.call(thisArg, value, index, collection); }; case 4: return function(accumulator, value, index, collection) { return func.call(thisArg, accumulator, value, index, collection); }; } return bind(func, thisArg); } /** * The base implementation of `_.flatten` without support for callback * shorthands or `thisArg` binding. * * @private * @param {Array} array The array to flatten. * @param {boolean} [isShallow=false] A flag to restrict flattening to a single level. * @param {boolean} [isArgArrays=false] A flag to restrict flattening to arrays and `arguments` objects. * @param {number} [fromIndex=0] The index to start from. * @returns {Array} Returns a new flattened array. */ function baseFlatten(array, isShallow, isArgArrays, fromIndex) { var index = (fromIndex || 0) - 1, length = array ? array.length : 0, result = []; while (++index < length) { var value = array[index]; if (value && typeof value == 'object' && typeof value.length == 'number' && (isArray(value) || isArguments(value))) { // recursively flatten arrays (susceptible to call stack limits) if (!isShallow) { value = baseFlatten(value, isShallow, isArgArrays); } var valIndex = -1, valLength = value.length, resIndex = result.length; result.length += valLength; while (++valIndex < valLength) { result[resIndex++] = value[valIndex]; } } else if (!isArgArrays) { result.push(value); } } return result; } /** * The base implementation of `_.isEqual`, without support for `thisArg` binding, * that allows partial "_.where" style comparisons. * * @private * @param {*} a The value to compare. * @param {*} b The other value to compare. * @param {Function} [callback] The function to customize comparing values. * @param {Function} [isWhere=false] A flag to indicate performing partial comparisons. * @param {Array} [stackA=[]] Tracks traversed `a` objects. * @param {Array} [stackB=[]] Tracks traversed `b` objects. * @returns {boolean} Returns `true` if the values are equivalent, else `false`. */ function baseIsEqual(a, b, callback, isWhere, stackA, stackB) { // used to indicate that when comparing objects, `a` has at least the properties of `b` if (callback) { var result = callback(a, b); if (typeof result != 'undefined') { return !!result; } } // 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 && objectTypes[type]) && !(b && objectTypes[otherType])) { return false; } // exit early for `null` and `undefined` avoiding ES3's Function#call behavior // http://es5.github.io/#x15.3.4.4 if (a == null || b == null) { return a === b; } // 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) { // unwrap any `lodash` wrapped values if (hasOwnProperty.call(a, '__wrapped__ ') || hasOwnProperty.call(b, '__wrapped__')) { return baseIsEqual(a.__wrapped__ || a, b.__wrapped__ || b, callback, isWhere, stackA, stackB); } // exit for functions and DOM nodes if (className != objectClass) { return false; } // in older versions of Opera, `arguments` objects have `Array` constructors var ctorA = a.constructor, ctorB = b.constructor; // non `Object` object instances with different constructors are not equal if (ctorA != ctorB && !( isFunction(ctorA) && ctorA instanceof ctorA && isFunction(ctorB) && ctorB instanceof ctorB )) { 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 = getArray()); stackB || (stackB = getArray()); var length = stackA.length; while (length--) { if (stackA[length] == a) { return stackB[length] == b; } } var size = 0; 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) { length = a.length; size = b.length; // compare lengths to determine if a deep comparison is necessary result = size == a.length; if (!result && !isWhere) { return result; } // deep compare the contents, ignoring non-numeric properties while (size--) { var index = length, value = b[size]; if (isWhere) { while (index--) { if ((result = baseIsEqual(a[index], value, callback, isWhere, stackA, stackB))) { break; } } } else if (!(result = baseIsEqual(a[size], value, callback, isWhere, stackA, stackB))) { break; } } return result; } // deep compare objects using `forIn`, instead of `forOwn`, to avoid `Object.keys` // which, in this case, is more costly forIn(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) && baseIsEqual(a[key], value, callback, isWhere, stackA, stackB)); } }); if (result && !isWhere) { // ensure both objects have the same number of properties forIn(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); } }); } if (initedStack) { releaseArray(stackA); releaseArray(stackB); } return result; } /** * The base implementation of `_.merge` without argument juggling or support * for `thisArg` binding. * * @private * @param {Object} object The destination object. * @param {Object} source The source object. * @param {Function} [callback] The function to customize merging properties. * @param {Array} [stackA=[]] Tracks traversed source objects. * @param {Array} [stackB=[]] Associates values with source counterparts. */ function baseMerge(object, source, callback, stackA, stackB) { (isArray(source) ? forEach : forOwn)(source, function(source, key) { var found, isArr, result = source, value = object[key]; if (source && ((isArr = isArray(source)) || isPlainObject(source))) { // avoid merging previously merged cyclic sources var stackLength = stackA.length; while (stackLength--) { if ((found = stackA[stackLength] == source)) { value = stackB[stackLength]; break; } } if (!found) { var isShallow; if (callback) { result = callback(value, source); if ((isShallow = typeof result != 'undefined')) { value = result; } } if (!isShallow) { value = isArr ? (isArray(value) ? value : []) : (isPlainObject(value) ? value : {}); } // add `source` and associated `value` to the stack of traversed objects stackA.push(source); stackB.push(value); // recursively merge objects and arrays (susceptible to call stack limits) if (!isShallow) { baseMerge(value, source, callback, stackA, stackB); } } } else { if (callback) { result = callback(value, source); if (typeof result == 'undefined') { result = source; } } if (typeof result != 'undefined') { value = result; } } object[key] = value; }); } /** * The base implementation of `_.uniq` without support for callback shorthands * or `thisArg` binding. * * @private * @param {Array} array The array to process. * @param {boolean} [isSorted=false] A flag to indicate that `array` is sorted. * @param {Function} [callback] The function called per iteration. * @returns {Array} Returns a duplicate-value-free array. */ function baseUniq(array, isSorted, callback) { var index = -1, indexOf = getIndexOf(), length = array ? array.length : 0, result = []; var isLarge = !isSorted && length >= largeArraySize && indexOf === baseIndexOf, seen = (callback || isLarge) ? getArray() : result; if (isLarge) { var cache = createCache(seen); if (cache) { indexOf = cacheIndexOf; seen = cache; } else { isLarge = false; seen = callback ? seen : (releaseArray(seen), result); } } while (++index < length) { var value = array[index], computed = callback ? callback(value, index, array) : value; if (isSorted ? !index || seen[seen.length - 1] !== computed : indexOf(seen, computed) < 0 ) { if (callback || isLarge) { seen.push(computed); } result.push(value); } } if (isLarge) { releaseArray(seen.array); releaseObject(seen); } else if (callback) { releaseArray(seen); } return result; } /** * Creates a function that aggregates a collection, creating an object composed * of keys generated from the results of running each element of the collection * through a callback. The given `setter` function sets the keys and values * of the composed object. * * @private * @param {Function} setter The setter function. * @returns {Function} Returns the new aggregator function. */ function createAggregator(setter) { return function(collection, callback, thisArg) { var result = {}; callback = lodash.createCallback(callback, thisArg, 3); var index = -1, length = collection ? collection.length : 0; if (typeof length == 'number') { while (++index < length) { var value = collection[index]; setter(result, value, callback(value, index, collection), collection); } } else { forOwn(collection, function(value, key, collection) { setter(result, value, callback(value, key, collection), collection); }); } return result; }; } /** * Creates a function that, when called, either curries or invokes `func` * with an optional `this` binding and partially applied arguments. * * @private * @param {Function|string} func The function or method name to reference. * @param {number} bitmask The bitmask of method flags to compose. * The bitmask may be composed of the following flags: * 1 - `_.bind` * 2 - `_.bindKey` * 4 - `_.curry` * 8 - `_.curry` (bound) * 16 - `_.partial` * 32 - `_.partialRight` * @param {Array} [partialArgs] An array of arguments to prepend to those * provided to the new function. * @param {Array} [partialRightArgs] An array of arguments to append to those * provided to the new function. * @param {*} [thisArg] The `this` binding of `func`. * @param {number} [arity] The arity of `func`. * @returns {Function} Returns the new bound function. */ function createBound(func, bitmask, partialArgs, partialRightArgs, thisArg, arity) { var isBind = bitmask & 1, isBindKey = bitmask & 2, isCurry = bitmask & 4, isCurryBound = bitmask & 8, isPartial = bitmask & 16, isPartialRight = bitmask & 32, key = func; if (!isBindKey && !isFunction(func)) { throw new TypeError; } if (isPartial && !partialArgs.length) { bitmask &= ~16; isPartial = partialArgs = false; } if (isPartialRight && !partialRightArgs.length) { bitmask &= ~32; isPartialRight = partialRightArgs = false; } var bindData = func && func.__bindData__; if (bindData) { if (isBind && !(bindData[1] & 1)) { bindData[4] = thisArg; } if (!isBind && bindData[1] & 1) { bitmask |= 8; } if (isCurry && !(bindData[1] & 4)) { bindData[5] = arity; } if (isPartial) { push.apply(bindData[2] || (bindData[2] = []), partialArgs); } if (isPartialRight) { push.apply(bindData[3] || (bindData[3] = []), partialRightArgs); } bindData[1] |= bitmask; return createBound.apply(null, bindData); } // use `Function#bind` if it exists and is fast // (in V8 `Function#bind` is slower except when partially applied) if (isBind && !(isBindKey || isCurry || isPartialRight) && (support.fastBind || (nativeBind && isPartial))) { if (isPartial) { var args = [thisArg]; push.apply(args, partialArgs); } var bound = isPartial ? nativeBind.apply(func, args) : nativeBind.call(func, thisArg); } else { bound = function() { // `Function#bind` spec // http://es5.github.io/#x15.3.4.5 var args = arguments, thisBinding = isBind ? thisArg : this; if (isCurry || isPartial || isPartialRight) { args = nativeSlice.call(args); if (isPartial) { unshift.apply(args, partialArgs); } if (isPartialRight) { push.apply(args, partialRightArgs); } if (isCurry && args.length < arity) { bitmask |= 16 & ~32; return createBound(func, (isCurryBound ? bitmask : bitmask & ~3), args, null, thisArg, arity); } } if (isBindKey) { func = thisBinding[key]; } if (this instanceof bound) { // ensure `new bound` is an instance of `func` thisBinding = createObject(func.prototype); // mimic the constructor's `return` behavior // http://es5.github.io/#x13.2.2 var result = func.apply(thisBinding, args); return isObject(result) ? result : thisBinding; } return func.apply(thisBinding, args); }; } setBindData(bound, nativeSlice.call(arguments)); return bound; } /** * Creates a new object with the specified `prototype`. * * @private * @param {Object} prototype The prototype object. * @returns {Object} Returns the new object. */ function createObject(prototype) { return isObject(prototype) ? nativeCreate(prototype) : {}; } // fallback for browsers without `Object.create` if (!nativeCreate) { createObject = function(prototype) { if (isObject(prototype)) { noop.prototype = prototype; var result = new noop; noop.prototype = null; } return result || {}; }; } /** * Used by `escape` to convert characters to HTML entities. * * @private * @param {string} match The matched character to escape. * @returns {string} Returns the escaped character. */ function escapeHtmlChar(match) { return htmlEscapes[match]; } /** * Gets the appropriate "indexOf" function. If the `_.indexOf` method is * customized, this method returns the custom method, otherwise it returns * the `baseIndexOf` function. * * @private * @returns {Function} Returns the "indexOf" function. */ function getIndexOf() { var result = (result = lodash.indexOf) === indexOf ? baseIndexOf : result; return result; } /** * Sets `this` binding data on a given function. * * @private * @param {Function} func The function to set data on. * @param {*} value The value to set. */ var setBindData = !defineProperty ? noop : function(func, value) { descriptor.value = value; defineProperty(func, '__bindData__', descriptor); }; /** * A fallback implementation of `isPlainObject` which checks if a given value * is an object created by the `Object` constructor, assuming objects created * by the `Object` constructor have no inherited enumerable properties and that * there are no `Object.prototype` extensions. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a plain object, else `false`. */ function shimIsPlainObject(value) { var ctor, result; // avoid non Object objects, `arguments` objects, and DOM elements if (!(value && toString.call(value) == objectClass) || (ctor = value.constructor, isFunction(ctor) && !(ctor instanceof ctor))) { return false; } // In most environments an object's own properties are iterated before // its inherited properties. If the last iterated property is an object's // own property then there are no inherited enumerable properties. forIn(value, function(value, key) { result = key; }); return typeof result == 'undefined' || hasOwnProperty.call(value, result); } /** * Used by `unescape` to convert HTML entities to characters. * * @private * @param {string} match The matched character to unescape. * @returns {string} Returns the unescaped character. */ function unescapeHtmlChar(match) { return htmlUnescapes[match]; } /*--------------------------------------------------------------------------*/ /** * Checks if `value` is an `arguments` object. * * @static * @memberOf _ * @category Objects * @param {*} value The value to check. * @returns {boolean} Returns `true` if the `value` is an `arguments` object, else `false`. * @example * * (function() { return _.isArguments(arguments); })(1, 2, 3); * // => true * * _.isArguments([1, 2, 3]); * // => false */ function isArguments(value) { return value && typeof value == 'object' && typeof value.length == 'number' && toString.call(value) == argsClass || false; } /** * Checks if `value` is an array. * * @static * @memberOf _ * @type Function * @category Objects * @param {*} value The value to check. * @returns {boolean} Returns `true` if the `value` is an array, else `false`. * @example * * (function() { return _.isArray(arguments); })(); * // => false * * _.isArray([1, 2, 3]); * // => true */ var isArray = nativeIsArray || function(value) { return value && typeof value == 'object' && typeof value.length == 'number' && toString.call(value) == arrayClass || false; }; /** * A fallback implementation of `Object.keys` which produces an array of the * given object's own enumerable property names. * * @private * @type Function * @param {Object} object The object to inspect. * @returns {Array} Returns an array of property names. */ var shimKeys = function(object) { var index, iterable = object, result = []; if (!iterable) return result; if (!(objectTypes[typeof object])) return result; for (index in iterable) { if (hasOwnProperty.call(iterable, index)) { result.push(index); } } return result }; /** * Creates an array composed of the own enumerable property names of an object. * * @static * @memberOf _ * @category Objects * @param {Object} object The object to inspect. * @returns {Array} Returns an array of property names. * @example * * _.keys({ 'one': 1, 'two': 2, 'three': 3 }); * // => ['one', 'two', 'three'] (property order is not guaranteed across environments) */ var keys = !nativeKeys ? shimKeys : function(object) { if (!isObject(object)) { return []; } return nativeKeys(object); }; /** * Used to convert characters to HTML entities: * * Though the `>` character is escaped for symmetry, characters like `>` and `/` * don't require escaping in HTML and have no special meaning unless they're part * of a tag or an unquoted attribute value. * http://mathiasbynens.be/notes/ambiguous-ampersands (under "semi-related fun fact") */ var htmlEscapes = { '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' }; /** Used to convert HTML entities to characters */ var htmlUnescapes = invert(htmlEscapes); /** Used to match HTML entities and HTML characters */ var reEscapedHtml = RegExp('(' + keys(htmlUnescapes).join('|') + ')', 'g'), reUnescapedHtml = RegExp('[' + keys(htmlEscapes).join('') + ']', 'g'); /*--------------------------------------------------------------------------*/ /** * Assigns own enumerable properties of source object(s) to the destination * object. Subsequent sources will overwrite property assignments of previous * sources. If a callback is provided it will be executed to produce the * assigned values. The callback is bound to `thisArg` and invoked with two * arguments; (objectValue, sourceValue). * * @static * @memberOf _ * @type Function * @alias extend * @category Objects * @param {Object} object The destination object. * @param {...Object} [source] The source objects. * @param {Function} [callback] The function to customize assigning values. * @param {*} [thisArg] The `this` binding of `callback`. * @returns {Object} Returns the destination object. * @example * * _.assign({ 'name': 'moe' }, { 'age': 40 }); * // => { 'name': 'moe', 'age': 40 } * * var defaults = _.partialRight(_.assign, function(a, b) { * return typeof a == 'undefined' ? b : a; * }); * * var food = { 'name': 'apple' }; * defaults(food, { 'name': 'banana', 'type': 'fruit' }); * // => { 'name': 'apple', 'type': 'fruit' } */ var assign = function(object, source, guard) { var index, iterable = object, result = iterable; if (!iterable) return result; var args = arguments, argsIndex = 0, argsLength = typeof guard == 'number' ? 2 : args.length; if (argsLength > 3 && typeof args[argsLength - 2] == 'function') { var callback = baseCreateCallback(args[--argsLength - 1], args[argsLength--], 2); } else if (argsLength > 2 && typeof args[argsLength - 1] == 'function') { callback = args[--argsLength]; } while (++argsIndex < argsLength) { iterable = args[argsIndex]; if (iterable && objectTypes[typeof iterable]) { var ownIndex = -1, ownProps = objectTypes[typeof iterable] && keys(iterable), length = ownProps ? ownProps.length : 0; while (++ownIndex < length) { index = ownProps[ownIndex]; result[index] = callback ? callback(result[index], iterable[index]) : iterable[index]; } } } return result }; /** * Creates a clone of `value`. If `deep` is `true` nested objects will also * be cloned, otherwise they will be assigned by reference. If a callback * is provided it will be executed to produce the cloned values. If the * callback returns `undefined` cloning will be handled by the method instead. * The callback is bound to `thisArg` and invoked with one argument; (value). * * @static * @memberOf _ * @category Objects * @param {*} value The value to clone. * @param {boolean} [deep=false] Specify a deep clone. * @param {Function} [callback] The function to customize cloning values. * @param {*} [thisArg] The `this` binding of `callback`. * @returns {*} Returns the cloned value. * @example * * var stooges = [ * { 'name': 'moe', 'age': 40 }, * { 'name': 'larry', 'age': 50 } * ]; * * var shallow = _.clone(stooges); * shallow[0] === stooges[0]; * // => true * * var deep = _.clone(stooges, true); * deep[0] === stooges[0]; * // => false * * _.mixin({ * 'clone': _.partialRight(_.clone, function(value) { * return _.isElement(value) ? value.cloneNode(false) : undefined; * }) * }); * * var clone = _.clone(document.body); * clone.childNodes.length; * // => 0 */ function clone(value, deep, callback, thisArg) { // allows working with "Collections" methods without using their `index` // and `collection` arguments for `deep` and `callback` if (typeof deep != 'boolean' && deep != null) { thisArg = callback; callback = deep; deep = false; } return baseClone(value, deep, typeof callback == 'function' && baseCreateCallback(callback, thisArg, 1)); } /** * Creates a deep clone of `value`. If a callback is provided it will be * executed to produce the cloned values. If the callback returns `undefined` * cloning will be handled by the method instead. The callback is bound to * `thisArg` and invoked with one argument; (value). * * Note: This method is loosely based on the structured clone algorithm. Functions * and DOM nodes are **not** cloned. The enumerable properties of `arguments` objects and * objects created by constructors other than `Object` are cloned to plain `Object` objects. * See http://www.w3.org/TR/html5/infrastructure.html#internal-structured-cloning-algorithm. * * @static * @memberOf _ * @category Objects * @param {*} value The value to deep clone. * @param {Function} [callback] The function to customize cloning values. * @param {*} [thisArg] The `this` binding of `callback`. * @returns {*} Returns the deep cloned value. * @example * * var stooges = [ * { 'name': 'moe', 'age': 40 }, * { 'name': 'larry', 'age': 50 } * ]; * * var deep = _.cloneDeep(stooges); * deep[0] === stooges[0]; * // => false * * var view = { * 'label': 'docs', * 'node': element * }; * * var clone = _.cloneDeep(view, function(value) { * return _.isElement(value) ? value.cloneNode(true) : undefined; * }); * * clone.node == view.node; * // => false */ function cloneDeep(value, callback, thisArg) { return baseClone(value, true, typeof callback == 'function' && baseCreateCallback(callback, thisArg, 1)); } /** * Assigns own enumerable properties of source object(s) to the destination * object for all destination properties that resolve to `undefined`. Once a * property is set, additional defaults of the same property will be ignored. * * @static * @memberOf _ * @type Function * @category Objects * @param {Object} object The destination object. * @param {...Object} [source] The source objects. * @param- {Object} [guard] Allows working with `_.reduce` without using its * `key` and `object` arguments as sources. * @returns {Object} Returns the destination object. * @example * * var food = { 'name': 'apple' }; * _.defaults(food, { 'name': 'banana', 'type': 'fruit' }); * // => { 'name': 'apple', 'type': 'fruit' } */ var defaults = function(object, source, guard) { var index, iterable = object, result = iterable; if (!iterable) return result; var args = arguments, argsIndex = 0, argsLength = typeof guard == 'number' ? 2 : args.length; while (++argsIndex < argsLength) { iterable = args[argsIndex]; if (iterable && objectTypes[typeof iterable]) { var ownIndex = -1, ownProps = objectTypes[typeof iterable] && keys(iterable), length = ownProps ? ownProps.length : 0; while (++ownIndex < length) { index = ownProps[ownIndex]; if (typeof result[index] == 'undefined') result[index] = iterable[index]; } } } return result }; /** * This method is like `_.findIndex` except that it returns the key of the * first element that passes the callback check, instead of the element itself. * * @static * @memberOf _ * @category Objects * @param {Object} object The object to search. * @param {Function|Object|string} [callback=identity] The function called per * iteration. If a property name or object is provided it will be used to * create a "_.pluck" or "_.where" style callback, respectively. * @param {*} [thisArg] The `this` binding of `callback`. * @returns {string|undefined} Returns the key of the found element, else `undefined`. * @example * * _.findKey({ 'a': 1, 'b': 2, 'c': 3, 'd': 4 }, function(num) { * return num % 2 == 0; * }); * // => 'b' (property order is not guaranteed across environments) */ function findKey(object, callback, thisArg) { var result; callback = lodash.createCallback(callback, thisArg, 3); forOwn(object, function(value, key, object) { if (callback(value, key, object)) { result = key; return false; } }); return result; } /** * This method is like `_.findKey` except that it iterates over elements * of a `collection` in the opposite order. * * @static * @memberOf _ * @category Objects * @param {Object} object The object to search. * @param {Function|Object|string} [callback=identity] The function called per * iteration. If a property name or object is provided it will be used to * create a "_.pluck" or "_.where" style callback, respectively. * @param {*} [thisArg] The `this` binding of `callback`. * @returns {string|undefined} Returns the key of the found element, else `undefined`. * @example * * _.findLastKey({ 'a': 1, 'b': 2, 'c': 3, 'd': 4 }, function(num) { * return num % 2 == 1; * }); * // => returns `c`, assuming `_.findKey` returns `a` */ function findLastKey(object, callback, thisArg) { var result; callback = lodash.createCallback(callback, thisArg, 3); forOwnRight(object, function(value, key, object) { if (callback(value, key, object)) { result = key; return false; } }); return result; } /** * Iterates over own and inherited enumerable properties of an object, * executing the callback for each property. The callback is bound to `thisArg` * and invoked with three arguments; (value, key, object). Callbacks may exit * iteration early by explicitly returning `false`. * * @static * @memberOf _ * @type Function * @category Objects * @param {Object} object The object to iterate over. * @param {Function} [callback=identity] The function called per iteration. * @param {*} [thisArg] The `this` binding of `callback`. * @returns {Object} Returns `object`. * @example * * function Dog(name) { * this.name = name; * } * * Dog.prototype.bark = function() { * console.log('Woof, woof!'); * }; * * _.forIn(new Dog('Dagny'), function(value, key) { * console.log(key); * }); * // => logs 'bark' and 'name' (property order is not guaranteed across environments) */ var forIn = function(collection, callback, thisArg) { var index, iterable = collection, result = iterable; if (!iterable) return result; if (!objectTypes[typeof iterable]) return result; callback = callback && typeof thisArg == 'undefined' ? callback : baseCreateCallback(callback, thisArg, 3); for (index in iterable) { if (callback(iterable[index], index, collection) === false) return result; } return result }; /** * This method is like `_.forIn` except that it iterates over elements * of a `collection` in the opposite order. * * @static * @memberOf _ * @category Objects * @param {Object} object The object to iterate over. * @param {Function} [callback=identity] The function called per iteration. * @param {*} [thisArg] The `this` binding of `callback`. * @returns {Object} Returns `object`. * @example * * function Dog(name) { * this.name = name; * } * * Dog.prototype.bark = function() { * console.log('Woof, woof!'); * }; * * _.forInRight(new Dog('Dagny'), function(value, key) { * console.log(key); * }); * // => logs 'name' and 'bark' assuming `_.forIn ` logs 'bark' and 'name' */ function forInRight(object, callback, thisArg) { var pairs = []; forIn(object, function(value, key) { pairs.push(key, value); }); var length = pairs.length; callback = baseCreateCallback(callback, thisArg, 3); while (length--) { if (callback(pairs[length--], pairs[length], object) === false) { break; } } return object; } /** * Iterates over own enumerable properties of an object, executing the callback * for each property. The callback is bound to `thisArg` and invoked with three * arguments; (value, key, object). Callbacks may exit iteration early by * explicitly returning `false`. * * @static * @memberOf _ * @type Function * @category Objects * @param {Object} object The object to iterate over. * @param {Function} [callback=identity] The function called per iteration. * @param {*} [thisArg] The `this` binding of `callback`. * @returns {Object} Returns `object`. * @example * * _.forOwn({ '0': 'zero', '1': 'one', 'length': 2 }, function(num, key) { * console.log(key); * }); * // => logs '0', '1', and 'length' (property order is not guaranteed across environments) */ var forOwn = function(collection, callback, thisArg) { var index, iterable = collection, result = iterable; if (!iterable) return result; if (!objectTypes[typeof iterable]) return result; callback = callback && typeof thisArg == 'undefined' ? callback : baseCreateCallback(callback, thisArg, 3); var ownIndex = -1, ownProps = objectTypes[typeof iterable] && keys(iterable), length = ownProps ? ownProps.length : 0; while (++ownIndex < length) { index = ownProps[ownIndex]; if (callback(iterable[index], index, collection) === false) return result; } return result }; /** * This method is like `_.forOwn` except that it iterates over elements * of a `collection` in the opposite order. * * @static * @memberOf _ * @category Objects * @param {Object} object The object to iterate over. * @param {Function} [callback=identity] The function called per iteration. * @param {*} [thisArg] The `this` binding of `callback`. * @returns {Object} Returns `object`. * @example * * _.forOwnRight({ '0': 'zero', '1': 'one', 'length': 2 }, function(num, key) { * console.log(key); * }); * // => logs 'length', '1', and '0' assuming `_.forOwn` logs '0', '1', and 'length' */ function forOwnRight(object, callback, thisArg) { var props = keys(object), length = props.length; callback = baseCreateCallback(callback, thisArg, 3); while (length--) { var key = props[length]; if (callback(object[key], key, object) === false) { break; } } return object; } /** * Creates a sorted array of property names of all enumerable properties, * own and inherited, of `object` that have function values. * * @static * @memberOf _ * @alias methods * @category Objects * @param {Object} object The object to inspect. * @returns {Array} Returns an array of property names that have function values. * @example * * _.functions(_); * // => ['all', 'any', 'bind', 'bindAll', 'clone', 'compact', 'compose', ...] */ function functions(object) { var result = []; forIn(object, function(value, key) { if (isFunction(value)) { result.push(key); } }); return result.sort(); } /** * Checks if the specified object `property` exists and is a direct property, * instead of an inherited property. * * @static * @memberOf _ * @category Objects * @param {Object} object The object to check. * @param {string} property The property to check for. * @returns {boolean} Returns `true` if key is a direct property, else `false`. * @example * * _.has({ 'a': 1, 'b': 2, 'c': 3 }, 'b'); * // => true */ function has(object, property) { return object ? hasOwnProperty.call(object, property) : false; } /** * Creates an object composed of the inverted keys and values of the given object. * * @static * @memberOf _ * @category Objects * @param {Object} object The object to invert. * @returns {Object} Returns the created inverted object. * @example * * _.invert({ 'first': 'moe', 'second': 'larry' }); * // => { 'moe': 'first', 'larry': 'second' } */ function invert(object) { var index = -1, props = keys(object), length = props.length, result = {}; while (++index < length) { var key = props[index]; result[object[key]] = key; } return result; } /** * Checks if `value` is a boolean value. * * @static * @memberOf _ * @category Objects * @param {*} value The value to check. * @returns {boolean} Returns `true` if the `value` is a boolean value, else `false`. * @example * * _.isBoolean(null); * // => false */ function isBoolean(value) { return value === true || value === false || toString.call(value) == boolClass; } /** * Checks if `value` is a date. * * @static * @memberOf _ * @category Objects * @param {*} value The value to check. * @returns {boolean} Returns `true` if the `value` is a date, else `false`. * @example * * _.isDate(new Date); * // => true */ function isDate(value) { return value ? (typeof value == 'object' && toString.call(value) == dateClass) : false; } /** * Checks if `value` is a DOM element. * * @static * @memberOf _ * @category Objects * @param {*} value The value to check. * @returns {boolean} Returns `true` if the `value` is a DOM element, else `false`. * @example * * _.isElement(document.body); * // => true */ function isElement(value) { return value ? value.nodeType === 1 : false; } /** * Checks if `value` is empty. Arrays, strings, or `arguments` objects with a * length of `0` and objects with no own enumerable properties are considered * "empty". * * @static * @memberOf _ * @category Objects * @param {Array|Object|string} value The value to inspect. * @returns {boolean} Returns `true` if the `value` is empty, else `false`. * @example * * _.isEmpty([1, 2, 3]); * // => false * * _.isEmpty({}); * // => true * * _.isEmpty(''); * // => true */ function isEmpty(value) { var result = true; if (!value) { return result; } var className = toString.call(value), length = value.length; if ((className == arrayClass || className == stringClass || className == argsClass ) || (className == objectClass && typeof length == 'number' && isFunction(value.splice))) { return !length; } forOwn(value, function() { return (result = false); }); return result; } /** * Performs a deep comparison between two values to determine if they are * equivalent to each other. If a callback is provided it will be executed * to compare values. If the callback returns `undefined` comparisons will * be handled by the method instead. The callback is bound to `thisArg` and * invoked with two arguments; (a, b). * * @static * @memberOf _ * @category Objects * @param {*} a The value to compare. * @param {*} b The other value to compare. * @param {Function} [callback] The function to customize comparing values. * @param {*} [thisArg] The `this` binding of `callback`. * @returns {boolean} Returns `true` if the values are equivalent, else `false`. * @example * * var moe = { 'name': 'moe', 'age': 40 }; * var copy = { 'name': 'moe', 'age': 40 }; * * moe == copy; * // => false * * _.isEqual(moe, copy); * // => true * * var words = ['hello', 'goodbye']; * var otherWords = ['hi', 'goodbye']; * * _.isEqual(words, otherWords, function(a, b) { * var reGreet = /^(?:hello|hi)$/i, * aGreet = _.isString(a) && reGreet.test(a), * bGreet = _.isString(b) && reGreet.test(b); * * return (aGreet || bGreet) ? (aGreet == bGreet) : undefined; * }); * // => true */ function isEqual(a, b, callback, thisArg) { return baseIsEqual(a, b, typeof callback == 'function' && baseCreateCallback(callback, thisArg, 2)); } /** * Checks if `value` is, or can be coerced to, a finite number. * * Note: This is not the same as native `isFinite` which will return true for * booleans and empty strings. See http://es5.github.io/#x15.1.2.5. * * @static * @memberOf _ * @category Objects * @param {*} value The value to check. * @returns {boolean} Returns `true` if the `value` is finite, else `false`. * @example * * _.isFinite(-101); * // => true * * _.isFinite('10'); * // => true * * _.isFinite(true); * // => false * * _.isFinite(''); * // => false * * _.isFinite(Infinity); * // => false */ function isFinite(value) { return nativeIsFinite(value) && !nativeIsNaN(parseFloat(value)); } /** * Checks if `value` is a function. * * @static * @memberOf _ * @category Objects * @param {*} value The value to check. * @returns {boolean} Returns `true` if the `value` is a function, else `false`. * @example * * _.isFunction(_); * // => true */ function isFunction(value) { return typeof value == 'function'; } /** * Checks if `value` is the language type of Object. * (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`) * * @static * @memberOf _ * @category Objects * @param {*} value The value to check. * @returns {boolean} Returns `true` if the `value` is an object, else `false`. * @example * * _.isObject({}); * // => true * * _.isObject([1, 2, 3]); * // => true * * _.isObject(1); * // => false */ function isObject(value) { // check if the value is the ECMAScript language type of Object // http://es5.github.io/#x8 // and avoid a V8 bug // http://code.google.com/p/v8/issues/detail?id=2291 return !!(value && objectTypes[typeof value]); } /** * Checks if `value` is `NaN`. * * Note: This is not the same as native `isNaN` which will return `true` for * `undefined` and other non-numeric values. See http://es5.github.io/#x15.1.2.4. * * @static * @memberOf _ * @category Objects * @param {*} value The value to check. * @returns {boolean} Returns `true` if the `value` is `NaN`, else `false`. * @example * * _.isNaN(NaN); * // => true * * _.isNaN(new Number(NaN)); * // => true * * isNaN(undefined); * // => true * * _.isNaN(undefined); * // => false */ function isNaN(value) { // `NaN` as a primitive is the only value that is not equal to itself // (perform the [[Class]] check first to avoid errors with some host objects in IE) return isNumber(value) && value != +value; } /** * Checks if `value` is `null`. * * @static * @memberOf _ * @category Objects * @param {*} value The value to check. * @returns {boolean} Returns `true` if the `value` is `null`, else `false`. * @example * * _.isNull(null); * // => true * * _.isNull(undefined); * // => false */ function isNull(value) { return value === null; } /** * Checks if `value` is a number. * * Note: `NaN` is considered a number. See http://es5.github.io/#x8.5. * * @static * @memberOf _ * @category Objects * @param {*} value The value to check. * @returns {boolean} Returns `true` if the `value` is a number, else `false`. * @example * * _.isNumber(8.4 * 5); * // => true */ function isNumber(value) { return typeof value == 'number' || toString.call(value) == numberClass; } /** * Checks if `value` is an object created by the `Object` constructor. * * @static * @memberOf _ * @category Objects * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a plain object, else `false`. * @example * * function Stooge(name, age) { * this.name = name; * this.age = age; * } * * _.isPlainObject(new Stooge('moe', 40)); * // => false * * _.isPlainObject([1, 2, 3]); * // => false * * _.isPlainObject({ 'name': 'moe', 'age': 40 }); * // => true */ var isPlainObject = function(value) { if (!(value && toString.call(value) == objectClass)) { return false; } var valueOf = value.valueOf, objProto = typeof valueOf == 'function' && (objProto = getPrototypeOf(valueOf)) && getPrototypeOf(objProto); return objProto ? (value == objProto || getPrototypeOf(value) == objProto) : shimIsPlainObject(value); }; /** * Checks if `value` is a regular expression. * * @static * @memberOf _ * @category Objects * @param {*} value The value to check. * @returns {boolean} Returns `true` if the `value` is a regular expression, else `false`. * @example * * _.isRegExp(/moe/); * // => true */ function isRegExp(value) { return value ? (typeof value == 'object' && toString.call(value) == regexpClass) : false; } /** * Checks if `value` is a string. * * @static * @memberOf _ * @category Objects * @param {*} value The value to check. * @returns {boolean} Returns `true` if the `value` is a string, else `false`. * @example * * _.isString('moe'); * // => true */ function isString(value) { return typeof value == 'string' || toString.call(value) == stringClass; } /** * Checks if `value` is `undefined`. * * @static * @memberOf _ * @category Objects * @param {*} value The value to check. * @returns {boolean} Returns `true` if the `value` is `undefined`, else `false`. * @example * * _.isUndefined(void 0); * // => true */ function isUndefined(value) { return typeof value == 'undefined'; } /** * Recursively merges own enumerable properties of the source object(s), that * don't resolve to `undefined` into the destination object. Subsequent sources * will overwrite property assignments of previous sources. If a callback is * provided it will be executed to produce the merged values of the destination * and source properties. If the callback returns `undefined` merging will * be handled by the method instead. The callback is bound to `thisArg` and * invoked with two arguments; (objectValue, sourceValue). * * @static * @memberOf _ * @category Objects * @param {Object} object The destination object. * @param {...Object} [source] The source objects. * @param {Function} [callback] The function to customize merging properties. * @param {*} [thisArg] The `this` binding of `callback`. * @returns {Object} Returns the destination object. * @example * * var names = { * 'stooges': [ * { 'name': 'moe' }, * { 'name': 'larry' } * ] * }; * * var ages = { * 'stooges': [ * { 'age': 40 }, * { 'age': 50 } * ] * }; * * _.merge(names, ages); * // => { 'stooges': [{ 'name': 'moe', 'age': 40 }, { 'name': 'larry', 'age': 50 }] } * * var food = { * 'fruits': ['apple'], * 'vegetables': ['beet'] * }; * * var otherFood = { * 'fruits': ['banana'], * 'vegetables': ['carrot'] * }; * * _.merge(food, otherFood, function(a, b) { * return _.isArray(a) ? a.concat(b) : undefined; * }); * // => { 'fruits': ['apple', 'banana'], 'vegetables': ['beet', 'carrot] } */ function merge(object) { var args = arguments, length = 2; if (!isObject(object)) { return object; } // allows working with `_.reduce` and `_.reduceRight` without using // their `index` and `collection` arguments if (typeof args[2] != 'number') { length = args.length; } if (length > 3 && typeof args[length - 2] == 'function') { var callback = baseCreateCallback(args[--length - 1], args[length--], 2); } else if (length > 2 && typeof args[length - 1] == 'function') { callback = args[--length]; } var sources = nativeSlice.call(arguments, 1, length), index = -1, stackA = getArray(), stackB = getArray(); while (++index < length) { baseMerge(object, sources[index], callback, stackA, stackB); } releaseArray(stackA); releaseArray(stackB); return object; } /** * Creates a shallow clone of `object` excluding the specified properties. * Property names may be specified as individual arguments or as arrays of * property names. If a callback is provided it will be executed for each * property of `object` omitting the properties the callback returns truey * for. The callback is bound to `thisArg` and invoked with three arguments; * (value, key, object). * * @static * @memberOf _ * @category Objects * @param {Object} object The source object. * @param {Function|...string|string[]} [callback] The properties to omit or the * function called per iteration. * @param {*} [thisArg] The `this` binding of `callback`. * @returns {Object} Returns an object without the omitted properties. * @example * * _.omit({ 'name': 'moe', 'age': 40 }, 'age'); * // => { 'name': 'moe' } * * _.omit({ 'name': 'moe', 'age': 40 }, function(value) { * return typeof value == 'number'; * }); * // => { 'name': 'moe' } */ function omit(object, callback, thisArg) { var indexOf = getIndexOf(), isFunc = typeof callback == 'function', result = {}; if (isFunc) { callback = lodash.createCallback(callback, thisArg, 3); } else { var props = baseFlatten(arguments, true, false, 1); } forIn(object, function(value, key, object) { if (isFunc ? !callback(value, key, object) : indexOf(props, key) < 0 ) { result[key] = value; } }); return result; } /** * Creates a two dimensional array of an object's key-value pairs, * i.e. `[[key1, value1], [key2, value2]]`. * * @static * @memberOf _ * @category Objects * @param {Object} object The object to inspect. * @returns {Array} Returns new array of key-value pairs. * @example * * _.pairs({ 'moe': 30, 'larry': 40 }); * // => [['moe', 30], ['larry', 40]] (property order is not guaranteed across environments) */ function pairs(object) { var index = -1, props = keys(object), length = props.length, result = Array(length); while (++index < length) { var key = props[index]; result[index] = [key, object[key]]; } return result; } /** * Creates a shallow clone of `object` composed of the specified properties. * Property names may be specified as individual arguments or as arrays of * property names. If a callback is provided it will be executed for each * property of `object` picking the properties the callback returns truey * for. The callback is bound to `thisArg` and invoked with three arguments; * (value, key, object). * * @static * @memberOf _ * @category Objects * @param {Object} object The source object. * @param {Function|...string|string[]} [callback] The function called per * iteration or property names to pick, specified as individual property * names or arrays of property names. * @param {*} [thisArg] The `this` binding of `callback`. * @returns {Object} Returns an object composed of the picked properties. * @example * * _.pick({ 'name': 'moe', '_userid': 'moe1' }, 'name'); * // => { 'name': 'moe' } * * _.pick({ 'name': 'moe', '_userid': 'moe1' }, function(value, key) { * return key.charAt(0) != '_'; * }); * // => { 'name': 'moe' } */ function pick(object, callback, thisArg) { var result = {}; if (typeof callback != 'function') { var index = -1, props = baseFlatten(arguments, true, false, 1), length = isObject(object) ? props.length : 0; while (++index < length) { var key = props[index]; if (key in object) { result[key] = object[key]; } } } else { callback = lodash.createCallback(callback, thisArg, 3); forIn(object, function(value, key, object) { if (callback(value, key, object)) { result[key] = value; } }); } return result; } /** * An alternative to `_.reduce` this method transforms `object` to a new * `accumulator` object which is the result of running each of its elements * through a callback, with each callback execution potentially mutating * the `accumulator` object. The callback is bound to `thisArg` and invoked * with four arguments; (accumulator, value, key, object). Callbacks may exit * iteration early by explicitly returning `false`. * * @static * @memberOf _ * @category Objects * @param {Array|Object} collection The collection to iterate over. * @param {Function} [callback=identity] The function called per iteration. * @param {*} [accumulator] The custom accumulator value. * @param {*} [thisArg] The `this` binding of `callback`. * @returns {*} Returns the accumulated value. * @example * * var squares = _.transform([1, 2, 3, 4, 5, 6, 7, 8, 9, 10], function(result, num) { * num *= num; * if (num % 2) { * return result.push(num) < 3; * } * }); * // => [1, 9, 25] * * var mapped = _.transform({ 'a': 1, 'b': 2, 'c': 3 }, function(result, num, key) { * result[key] = num * 3; * }); * // => { 'a': 3, 'b': 6, 'c': 9 } */ function transform(object, callback, accumulator, thisArg) { var isArr = isArray(object); callback = baseCreateCallback(callback, thisArg, 4); if (accumulator == null) { if (isArr) { accumulator = []; } else { var ctor = object && object.constructor, proto = ctor && ctor.prototype; accumulator = createObject(proto); } } (isArr ? forEach : forOwn)(object, function(value, index, object) { return callback(accumulator, value, index, object); }); return accumulator; } /** * Creates an array composed of the own enumerable property values of `object`. * * @static * @memberOf _ * @category Objects * @param {Object} object The object to inspect. * @returns {Array} Returns an array of property values. * @example * * _.values({ 'one': 1, 'two': 2, 'three': 3 }); * // => [1, 2, 3] (property order is not guaranteed across environments) */ function values(object) { var index = -1, props = keys(object), length = props.length, result = Array(length); while (++index < length) { result[index] = object[props[index]]; } return result; } /*--------------------------------------------------------------------------*/ /** * Creates an array of elements from the specified indexes, or keys, of the * `collection`. Indexes may be specified as individual arguments or as arrays * of indexes. * * @static * @memberOf _ * @category Collections * @param {Array|Object|string} collection The collection to iterate over. * @param {...(number|number[]|string|string[])} [index] The indexes of `collection` * to retrieve, specified as individual indexes or arrays of indexes. * @returns {Array} Returns a new array of elements corresponding to the * provided indexes. * @example * * _.at(['a', 'b', 'c', 'd', 'e'], [0, 2, 4]); * // => ['a', 'c', 'e'] * * _.at(['moe', 'larry', 'curly'], 0, 2); * // => ['moe', 'curly'] */ function at(collection) { var args = arguments, index = -1, props = baseFlatten(args, true, false, 1), length = (args[2] && args[2][args[1]] === collection) ? 1 : props.length, result = Array(length); while(++index < length) { result[index] = collection[props[index]]; } return result; } /** * Checks if a given value is present in a collection using strict equality * for comparisons, i.e. `===`. If `fromIndex` is negative, it is used as the * offset from the end of the collection. * * @static * @memberOf _ * @alias include * @category Collections * @param {Array|Object|string} collection The collection to iterate over. * @param {*} target The value to check for. * @param {number} [fromIndex=0] The index to search from. * @returns {boolean} Returns `true` if the `target` element is found, else `false`. * @example * * _.contains([1, 2, 3], 1); * // => true * * _.contains([1, 2, 3], 1, 2); * // => false * * _.contains({ 'name': 'moe', 'age': 40 }, 'moe'); * // => true * * _.contains('curly', 'ur'); * // => true */ function contains(collection, target, fromIndex) { var index = -1, indexOf = getIndexOf(), length = collection ? collection.length : 0, result = false; fromIndex = (fromIndex < 0 ? nativeMax(0, length + fromIndex) : fromIndex) || 0; if (isArray(collection)) { result = indexOf(collection, target, fromIndex) > -1; } else if (typeof length == 'number') { result = (isString(collection) ? collection.indexOf(target, fromIndex) : indexOf(collection, target, fromIndex)) > -1; } else { forOwn(collection, function(value) { if (++index >= fromIndex) { return !(result = value === target); } }); } return result; } /** * Creates an object composed of keys generated from the results of running * each element of `collection` through the callback. The corresponding value * of each key is the number of times the key was returned by the callback. * The callback is bound to `thisArg` and invoked with three arguments; * (value, index|key, collection). * * If a property name is provided for `callback` the created "_.pluck" style * callback will return the property value of the given element. * * If an object is provided for `callback` the created "_.where" style callback * will return `true` for elements that have the properties of the given object, * else `false`. * * @static * @memberOf _ * @category Collections * @param {Array|Object|string} collection The collection to iterate over. * @param {Function|Object|string} [callback=identity] The function called * per iteration. If a property name or object is provided it will be used * to create a "_.pluck" or "_.where" style callback, respectively. * @param {*} [thisArg] The `this` binding of `callback`. * @returns {Object} Returns the composed aggregate object. * @example * * _.countBy([4.3, 6.1, 6.4], function(num) { return Math.floor(num); }); * // => { '4': 1, '6': 2 } * * _.countBy([4.3, 6.1, 6.4], function(num) { return this.floor(num); }, Math); * // => { '4': 1, '6': 2 } * * _.countBy(['one', 'two', 'three'], 'length'); * // => { '3': 2, '5': 1 } */ var countBy = createAggregator(function(result, value, key) { (hasOwnProperty.call(result, key) ? result[key]++ : result[key] = 1); }); /** * Checks if the given callback returns truey value for **all** elements of * a collection. The callback is bound to `thisArg` and invoked with three * arguments; (value, index|key, collection). * * If a property name is provided for `callback` the created "_.pluck" style * callback will return the property value of the given element. * * If an object is provided for `callback` the created "_.where" style callback * will return `true` for elements that have the properties of the given object, * else `false`. * * @static * @memberOf _ * @alias all * @category Collections * @param {Array|Object|string} collection The collection to iterate over. * @param {Function|Object|string} [callback=identity] The function called * per iteration. If a property name or object is provided it will be used * to create a "_.pluck" or "_.where" style callback, respectively. * @param {*} [thisArg] The `this` binding of `callback`. * @returns {boolean} Returns `true` if all elements passed the callback check, * else `false`. * @example * * _.every([true, 1, null, 'yes'], Boolean); * // => false * * var stooges = [ * { 'name': 'moe', 'age': 40 }, * { 'name': 'larry', 'age': 50 } * ]; * * // using "_.pluck" callback shorthand * _.every(stooges, 'age'); * // => true * * // using "_.where" callback shorthand * _.every(stooges, { 'age': 50 }); * // => false */ function every(collection, callback, thisArg) { var result = true; callback = lodash.createCallback(callback, thisArg, 3); var index = -1, length = collection ? collection.length : 0; if (typeof length == 'number') { while (++index < length) { if (!(result = !!callback(collection[index], index, collection))) { break; } } } else { forOwn(collection, function(value, index, collection) { return (result = !!callback(value, index, collection)); }); } return result; } /** * Iterates over elements of a collection, returning an array of all elements * the callback returns truey for. The callback is bound to `thisArg` and * invoked with three arguments; (value, index|key, collection). * * If a property name is provided for `callback` the created "_.pluck" style * callback will return the property value of the given element. * * If an object is provided for `callback` the created "_.where" style callback * will return `true` for elements that have the properties of the given object, * else `false`. * * @static * @memberOf _ * @alias select * @category Collections * @param {Array|Object|string} collection The collection to iterate over. * @param {Function|Object|string} [callback=identity] The function called * per iteration. If a property name or object is provided it will be used * to create a "_.pluck" or "_.where" style callback, respectively. * @param {*} [thisArg] The `this` binding of `callback`. * @returns {Array} Returns a new array of elements that passed the callback check. * @example * * var evens = _.filter([1, 2, 3, 4, 5, 6], function(num) { return num % 2 == 0; }); * // => [2, 4, 6] * * var food = [ * { 'name': 'apple', 'organic': false, 'type': 'fruit' }, * { 'name': 'carrot', 'organic': true, 'type': 'vegetable' } * ]; * * // using "_.pluck" callback shorthand * _.filter(food, 'organic'); * // => [{ 'name': 'carrot', 'organic': true, 'type': 'vegetable' }] * * // using "_.where" callback shorthand * _.filter(food, { 'type': 'fruit' }); * // => [{ 'name': 'apple', 'organic': false, 'type': 'fruit' }] */ function filter(collection, callback, thisArg) { var result = []; callback = lodash.createCallback(callback, thisArg, 3); var index = -1, length = collection ? collection.length : 0; if (typeof length == 'number') { while (++index < length) { var value = collection[index]; if (callback(value, index, collection)) { result.push(value); } } } else { forOwn(collection, function(value, index, collection) { if (callback(value, index, collection)) { result.push(value); } }); } return result; } /** * Iterates over elements of a collection, returning the first element that * the callback returns truey for. The callback is bound to `thisArg` and * invoked with three arguments; (value, index|key, collection). * * If a property name is provided for `callback` the created "_.pluck" style * callback will return the property value of the given element. * * If an object is provided for `callback` the created "_.where" style callback * will return `true` for elements that have the properties of the given object, * else `false`. * * @static * @memberOf _ * @alias detect, findWhere * @category Collections * @param {Array|Object|string} collection The collection to iterate over. * @param {Function|Object|string} [callback=identity] The function called * per iteration. If a property name or object is provided it will be used * to create a "_.pluck" or "_.where" style callback, respectively. * @param {*} [thisArg] The `this` binding of `callback`. * @returns {*} Returns the found element, else `undefined`. * @example * * _.find([1, 2, 3, 4], function(num) { * return num % 2 == 0; * }); * // => 2 * * var food = [ * { 'name': 'apple', 'organic': false, 'type': 'fruit' }, * { 'name': 'banana', 'organic': true, 'type': 'fruit' }, * { 'name': 'beet', 'organic': false, 'type': 'vegetable' } * ]; * * // using "_.where" callback shorthand * _.find(food, { 'type': 'vegetable' }); * // => { 'name': 'beet', 'organic': false, 'type': 'vegetable' } * * // using "_.pluck" callback shorthand * _.find(food, 'organic'); * // => { 'name': 'banana', 'organic': true, 'type': 'fruit' } */ function find(collection, callback, thisArg) { callback = lodash.createCallback(callback, thisArg, 3); var index = -1, length = collection ? collection.length : 0; if (typeof length == 'number') { while (++index < length) { var value = collection[index]; if (callback(value, index, collection)) { return value; } } } else { var result; forOwn(collection, function(value, index, collection) { if (callback(value, index, collection)) { result = value; return false; } }); return result; } } /** * This method is like `_.find` except that it iterates over elements * of a `collection` from right to left. * * @static * @memberOf _ * @category Collections * @param {Array|Object|string} collection The collection to iterate over. * @param {Function|Object|string} [callback=identity] The function called * per iteration. If a property name or object is provided it will be used * to create a "_.pluck" or "_.where" style callback, respectively. * @param {*} [thisArg] The `this` binding of `callback`. * @returns {*} Returns the found element, else `undefined`. * @example * * _.findLast([1, 2, 3, 4], function(num) { * return num % 2 == 1; * }); * // => 3 */ function findLast(collection, callback, thisArg) { var result; callback = lodash.createCallback(callback, thisArg, 3); forEachRight(collection, function(value, index, collection) { if (callback(value, index, collection)) { result = value; return false; } }); return result; } /** * Iterates over elements of a collection, executing the callback for each * element. The callback is bound to `thisArg` and invoked with three arguments; * (value, index|key, collection). Callbacks may exit iteration early by * explicitly returning `false`. * * @static * @memberOf _ * @alias each * @category Collections * @param {Array|Object|string} collection The collection to iterate over. * @param {Function} [callback=identity] The function called per iteration. * @param {*} [thisArg] The `this` binding of `callback`. * @returns {Array|Object|string} Returns `collection`. * @example * * _([1, 2, 3]).forEach(function(num) { console.log(num); }).join(','); * // => logs each number and returns '1,2,3' * * _.forEach({ 'one': 1, 'two': 2, 'three': 3 }, function(num) { console.log(num); }); * // => logs each number and returns the object (property order is not guaranteed across environments) */ function forEach(collection, callback, thisArg) { var index = -1, length = collection ? collection.length : 0; callback = callback && typeof thisArg == 'undefined' ? callback : baseCreateCallback(callback, thisArg, 3); if (typeof length == 'number') { while (++index < length) { if (callback(collection[index], index, collection) === false) { break; } } } else { forOwn(collection, callback); } return collection; } /** * This method is like `_.forEach` except that it iterates over elements * of a `collection` from right to left. * * @static * @memberOf _ * @alias eachRight * @category Collections * @param {Array|Object|string} collection The collection to iterate over. * @param {Function} [callback=identity] The function called per iteration. * @param {*} [thisArg] The `this` binding of `callback`. * @returns {Array|Object|string} Returns `collection`. * @example * * _([1, 2, 3]).forEachRight(function(num) { console.log(num); }).join(','); * // => logs each number from right to left and returns '3,2,1' */ function forEachRight(collection, callback, thisArg) { var length = collection ? collection.length : 0; callback = callback && typeof thisArg == 'undefined' ? callback : baseCreateCallback(callback, thisArg, 3); if (typeof length == 'number') { while (length--) { if (callback(collection[length], length, collection) === false) { break; } } } else { var props = keys(collection); length = props.length; forOwn(collection, function(value, key, collection) { key = props ? props[--length] : --length; return callback(collection[key], key, collection); }); } return collection; } /** * Creates an object composed of keys generated from the results of running * each element of a collection through the callback. The corresponding value * of each key is an array of the elements responsible for generating the key. * The callback is bound to `thisArg` and invoked with three arguments; * (value, index|key, collection). * * If a property name is provided for `callback` the created "_.pluck" style * callback will return the property value of the given element. * * If an object is provided for `callback` the created "_.where" style callback * will return `true` for elements that have the properties of the given object, * else `false` * * @static * @memberOf _ * @category Collections * @param {Array|Object|string} collection The collection to iterate over. * @param {Function|Object|string} [callback=identity] The function called * per iteration. If a property name or object is provided it will be used * to create a "_.pluck" or "_.where" style callback, respectively. * @param {*} [thisArg] The `this` binding of `callback`. * @returns {Object} Returns the composed aggregate object. * @example * * _.groupBy([4.2, 6.1, 6.4], function(num) { return Math.floor(num); }); * // => { '4': [4.2], '6': [6.1, 6.4] } * * _.groupBy([4.2, 6.1, 6.4], function(num) { return this.floor(num); }, Math); * // => { '4': [4.2], '6': [6.1, 6.4] } * * // using "_.pluck" callback shorthand * _.groupBy(['one', 'two', 'three'], 'length'); * // => { '3': ['one', 'two'], '5': ['three'] } */ var groupBy = createAggregator(function(result, value, key) { (hasOwnProperty.call(result, key) ? result[key] : result[key] = []).push(value); }); /** * Creates an object composed of keys generated from the results of running * each element of the collection through the given callback. The corresponding * value of each key is the last element responsible for generating the key. * The callback is bound to `thisArg` and invoked with three arguments; * (value, index|key, collection). * * If a property name is provided for `callback` the created "_.pluck" style * callback will return the property value of the given element. * * If an object is provided for `callback` the created "_.where" style callback * will return `true` for elements that have the properties of the given object, * else `false`. * * @static * @memberOf _ * @category Collections * @param {Array|Object|string} collection The collection to iterate over. * @param {Function|Object|string} [callback=identity] The function called * per iteration. If a property name or object is provided it will be used * to create a "_.pluck" or "_.where" style callback, respectively. * @param {*} [thisArg] The `this` binding of `callback`. * @returns {Object} Returns the composed aggregate object. * @example * * var keys = [ * { 'dir': 'left', 'code': 97 }, * { 'dir': 'right', 'code': 100 } * ]; * * _.indexBy(keys, 'dir'); * // => { 'left': { 'dir': 'left', 'code': 97 }, 'right': { 'dir': 'right', 'code': 100 } } * * _.indexBy(keys, function(key) { return String.fromCharCode(key.code); }); * // => { 'a': { 'dir': 'left', 'code': 97 }, 'd': { 'dir': 'right', 'code': 100 } } * * _.indexBy(stooges, function(key) { this.fromCharCode(key.code); }, String); * // => { 'a': { 'dir': 'left', 'code': 97 }, 'd': { 'dir': 'right', 'code': 100 } } */ var indexBy = createAggregator(function(result, value, key) { result[key] = value; }); /** * Invokes the method named by `methodName` on each element in the `collection` * returning an array of the results of each invoked method. Additional arguments * will be provided to each invoked method. If `methodName` is a function it * will be invoked for, and `this` bound to, each element in the `collection`. * * @static * @memberOf _ * @category Collections * @param {Array|Object|string} collection The collection to iterate over. * @param {Function|string} methodName The name of the method to invoke or * the function invoked per iteration. * @param {...*} [arg] Arguments to invoke the method with. * @returns {Array} Returns a new array of the results of each invoked method. * @example * * _.invoke([[5, 1, 7], [3, 2, 1]], 'sort'); * // => [[1, 5, 7], [1, 2, 3]] * * _.invoke([123, 456], String.prototype.split, ''); * // => [['1', '2', '3'], ['4', '5', '6']] */ function invoke(collection, methodName) { var args = nativeSlice.call(arguments, 2), index = -1, isFunc = typeof methodName == 'function', length = collection ? collection.length : 0, result = Array(typeof length == 'number' ? length : 0); forEach(collection, function(value) { result[++index] = (isFunc ? methodName : value[methodName]).apply(value, args); }); return result; } /** * Creates an array of values by running each element in the collection * through the callback. The callback is bound to `thisArg` and invoked with * three arguments; (value, index|key, collection). * * If a property name is provided for `callback` the created "_.pluck" style * callback will return the property value of the given element. * * If an object is provided for `callback` the created "_.where" style callback * will return `true` for elements that have the properties of the given object, * else `false`. * * @static * @memberOf _ * @alias collect * @category Collections * @param {Array|Object|string} collection The collection to iterate over. * @param {Function|Object|string} [callback=identity] The function called * per iteration. If a property name or object is provided it will be used * to create a "_.pluck" or "_.where" style callback, respectively. * @param {*} [thisArg] The `this` binding of `callback`. * @returns {Array} Returns a new array of the results of each `callback` execution. * @example * * _.map([1, 2, 3], function(num) { return num * 3; }); * // => [3, 6, 9] * * _.map({ 'one': 1, 'two': 2, 'three': 3 }, function(num) { return num * 3; }); * // => [3, 6, 9] (property order is not guaranteed across environments) * * var stooges = [ * { 'name': 'moe', 'age': 40 }, * { 'name': 'larry', 'age': 50 } * ]; * * // using "_.pluck" callback shorthand * _.map(stooges, 'name'); * // => ['moe', 'larry'] */ function map(collection, callback, thisArg) { var index = -1, length = collection ? collection.length : 0; callback = lodash.createCallback(callback, thisArg, 3); if (typeof length == 'number') { var result = Array(length); while (++index < length) { result[index] = callback(collection[index], index, collection); } } else { result = []; forOwn(collection, function(value, key, collection) { result[++index] = callback(value, key, collection); }); } return result; } /** * Retrieves the maximum value of a collection. If the collection is empty or * falsey `-Infinity` is returned. If a callback is provided it will be executed * for each value in the collection to generate the criterion by which the value * is ranked. The callback is bound to `thisArg` and invoked with three * arguments; (value, index, collection). * * If a property name is provided for `callback` the created "_.pluck" style * callback will return the property value of the given element. * * If an object is provided for `callback` the created "_.where" style callback * will return `true` for elements that have the properties of the given object, * else `false`. * * @static * @memberOf _ * @category Collections * @param {Array|Object|string} collection The collection to iterate over. * @param {Function|Object|string} [callback=identity] The function called * per iteration. If a property name or object is provided it will be used * to create a "_.pluck" or "_.where" style callback, respectively. * @param {*} [thisArg] The `this` binding of `callback`. * @returns {*} Returns the maximum value. * @example * * _.max([4, 2, 8, 6]); * // => 8 * * var stooges = [ * { 'name': 'moe', 'age': 40 }, * { 'name': 'larry', 'age': 50 } * ]; * * _.max(stooges, function(stooge) { return stooge.age; }); * // => { 'name': 'larry', 'age': 50 }; * * // using "_.pluck" callback shorthand * _.max(stooges, 'age'); * // => { 'name': 'larry', 'age': 50 }; */ function max(collection, callback, thisArg) { var computed = -Infinity, result = computed; if (!callback && isArray(collection)) { var index = -1, length = collection.length; while (++index < length) { var value = collection[index]; if (value > result) { result = value; } } } else { callback = (!callback && isString(collection)) ? charAtCallback : lodash.createCallback(callback, thisArg, 3); forEach(collection, function(value, index, collection) { var current = callback(value, index, collection); if (current > computed) { computed = current; result = value; } }); } return result; } /** * Retrieves the minimum value of a collection. If the collection is empty or * falsey `Infinity` is returned. If a callback is provided it will be executed * for each value in the collection to generate the criterion by which the value * is ranked. The callback is bound to `thisArg` and invoked with three * arguments; (value, index, collection). * * If a property name is provided for `callback` the created "_.pluck" style * callback will return the property value of the given element. * * If an object is provided for `callback` the created "_.where" style callback * will return `true` for elements that have the properties of the given object, * else `false`. * * @static * @memberOf _ * @category Collections * @param {Array|Object|string} collection The collection to iterate over. * @param {Function|Object|string} [callback=identity] The function called * per iteration. If a property name or object is provided it will be used * to create a "_.pluck" or "_.where" style callback, respectively. * @param {*} [thisArg] The `this` binding of `callback`. * @returns {*} Returns the minimum value. * @example * * _.min([4, 2, 8, 6]); * // => 2 * * var stooges = [ * { 'name': 'moe', 'age': 40 }, * { 'name': 'larry', 'age': 50 } * ]; * * _.min(stooges, function(stooge) { return stooge.age; }); * // => { 'name': 'moe', 'age': 40 }; * * // using "_.pluck" callback shorthand * _.min(stooges, 'age'); * // => { 'name': 'moe', 'age': 40 }; */ function min(collection, callback, thisArg) { var computed = Infinity, result = computed; if (!callback && isArray(collection)) { var index = -1, length = collection.length; while (++index < length) { var value = collection[index]; if (value < result) { result = value; } } } else { callback = (!callback && isString(collection)) ? charAtCallback : lodash.createCallback(callback, thisArg, 3); forEach(collection, function(value, index, collection) { var current = callback(value, index, collection); if (current < computed) { computed = current; result = value; } }); } return result; } /** * Retrieves the value of a specified property from all elements in the `collection`. * * @static * @memberOf _ * @type Function * @category Collections * @param {Array|Object|string} collection The collection to iterate over. * @param {string} property The property to pluck. * @returns {Array} Returns a new array of property values. * @example * * var stooges = [ * { 'name': 'moe', 'age': 40 }, * { 'name': 'larry', 'age': 50 } * ]; * * _.pluck(stooges, 'name'); * // => ['moe', 'larry'] */ function pluck(collection, property) { var index = -1, length = collection ? collection.length : 0; if (typeof length == 'number') { var result = Array(length); while (++index < length) { result[index] = collection[index][property]; } } return result || map(collection, property); } /** * Reduces a collection to a value which is the accumulated result of running * each element in the collection through the callback, where each successive * callback execution consumes the return value of the previous execution. If * `accumulator` is not provided the first element of the collection will be * used as the initial `accumulator` value. The callback is bound to `thisArg` * and invoked with four arguments; (accumulator, value, index|key, collection). * * @static * @memberOf _ * @alias foldl, inject * @category Collections * @param {Array|Object|string} collection The collection to iterate over. * @param {Function} [callback=identity] The function called per iteration. * @param {*} [accumulator] Initial value of the accumulator. * @param {*} [thisArg] The `this` binding of `callback`. * @returns {*} Returns the accumulated value. * @example * * var sum = _.reduce([1, 2, 3], function(sum, num) { * return sum + num; * }); * // => 6 * * var mapped = _.reduce({ 'a': 1, 'b': 2, 'c': 3 }, function(result, num, key) { * result[key] = num * 3; * return result; * }, {}); * // => { 'a': 3, 'b': 6, 'c': 9 } */ function reduce(collection, callback, accumulator, thisArg) { if (!collection) return accumulator; var noaccum = arguments.length < 3; callback = baseCreateCallback(callback, thisArg, 4); var index = -1, length = collection.length; if (typeof length == 'number') { if (noaccum) { accumulator = collection[++index]; } while (++index < length) { accumulator = callback(accumulator, collection[index], index, collection); } } else { forOwn(collection, function(value, index, collection) { accumulator = noaccum ? (noaccum = false, value) : callback(accumulator, value, index, collection) }); } return accumulator; } /** * This method is like `_.reduce` except that it iterates over elements * of a `collection` from right to left. * * @static * @memberOf _ * @alias foldr * @category Collections * @param {Array|Object|string} collection The collection to iterate over. * @param {Function} [callback=identity] The function called per iteration. * @param {*} [accumulator] Initial value of the accumulator. * @param {*} [thisArg] The `this` binding of `callback`. * @returns {*} Returns the accumulated value. * @example * * var list = [[0, 1], [2, 3], [4, 5]]; * var flat = _.reduceRight(list, function(a, b) { return a.concat(b); }, []); * // => [4, 5, 2, 3, 0, 1] */ function reduceRight(collection, callback, accumulator, thisArg) { var noaccum = arguments.length < 3; callback = baseCreateCallback(callback, thisArg, 4); forEachRight(collection, function(value, index, collection) { accumulator = noaccum ? (noaccum = false, value) : callback(accumulator, value, index, collection); }); return accumulator; } /** * The opposite of `_.filter` this method returns the elements of a * collection that the callback does **not** return truey for. * * If a property name is provided for `callback` the created "_.pluck" style * callback will return the property value of the given element. * * If an object is provided for `callback` the created "_.where" style callback * will return `true` for elements that have the properties of the given object, * else `false`. * * @static * @memberOf _ * @category Collections * @param {Array|Object|string} collection The collection to iterate over. * @param {Function|Object|string} [callback=identity] The function called * per iteration. If a property name or object is provided it will be used * to create a "_.pluck" or "_.where" style callback, respectively. * @param {*} [thisArg] The `this` binding of `callback`. * @returns {Array} Returns a new array of elements that failed the callback check. * @example * * var odds = _.reject([1, 2, 3, 4, 5, 6], function(num) { return num % 2 == 0; }); * // => [1, 3, 5] * * var food = [ * { 'name': 'apple', 'organic': false, 'type': 'fruit' }, * { 'name': 'carrot', 'organic': true, 'type': 'vegetable' } * ]; * * // using "_.pluck" callback shorthand * _.reject(food, 'organic'); * // => [{ 'name': 'apple', 'organic': false, 'type': 'fruit' }] * * // using "_.where" callback shorthand * _.reject(food, { 'type': 'fruit' }); * // => [{ 'name': 'carrot', 'organic': true, 'type': 'vegetable' }] */ function reject(collection, callback, thisArg) { callback = lodash.createCallback(callback, thisArg, 3); return filter(collection, function(value, index, collection) { return !callback(value, index, collection); }); } /** * Retrieves a random element or `n` random elements from a collection. * * @static * @memberOf _ * @category Collections * @param {Array|Object|string} collection The collection to sample. * @param {number} [n] The number of elements to sample. * @param- {Object} [guard] Allows working with functions, like `_.map`, * without using their `key` and `object` arguments as sources. * @returns {Array} Returns the random sample(s) of `collection`. * @example * * _.sample([1, 2, 3, 4]); * // => 2 * * _.sample([1, 2, 3, 4], 2); * // => [3, 1] */ function sample(collection, n, guard) { var length = collection ? collection.length : 0; if (typeof length != 'number') { collection = values(collection); } if (n == null || guard) { return collection ? collection[random(length - 1)] : undefined; } var result = shuffle(collection); result.length = nativeMin(nativeMax(0, n), result.length); return result; } /** * Creates an array of shuffled values, using a version of the Fisher-Yates * shuffle. See http://en.wikipedia.org/wiki/Fisher-Yates_shuffle. * * @static * @memberOf _ * @category Collections * @param {Array|Object|string} collection The collection to shuffle. * @returns {Array} Returns a new shuffled collection. * @example * * _.shuffle([1, 2, 3, 4, 5, 6]); * // => [4, 1, 6, 3, 5, 2] */ function shuffle(collection) { var index = -1, length = collection ? collection.length : 0, result = Array(typeof length == 'number' ? length : 0); forEach(collection, function(value) { var rand = random(++index); result[index] = result[rand]; result[rand] = value; }); return result; } /** * Gets the size of the `collection` by returning `collection.length` for arrays * and array-like objects or the number of own enumerable properties for objects. * * @static * @memberOf _ * @category Collections * @param {Array|Object|string} collection The collection to inspect. * @returns {number} Returns `collection.length` or number of own enumerable properties. * @example * * _.size([1, 2]); * // => 2 * * _.size({ 'one': 1, 'two': 2, 'three': 3 }); * // => 3 * * _.size('curly'); * // => 5 */ function size(collection) { var length = collection ? collection.length : 0; return typeof length == 'number' ? length : keys(collection).length; } /** * Checks if the callback returns a truey value for **any** element of a * collection. The function returns as soon as it finds a passing value and * does not iterate over the entire collection. The callback is bound to * `thisArg` and invoked with three arguments; (value, index|key, collection). * * If a property name is provided for `callback` the created "_.pluck" style * callback will return the property value of the given element. * * If an object is provided for `callback` the created "_.where" style callback * will return `true` for elements that have the properties of the given object, * else `false`. * * @static * @memberOf _ * @alias any * @category Collections * @param {Array|Object|string} collection The collection to iterate over. * @param {Function|Object|string} [callback=identity] The function called * per iteration. If a property name or object is provided it will be used * to create a "_.pluck" or "_.where" style callback, respectively. * @param {*} [thisArg] The `this` binding of `callback`. * @returns {boolean} Returns `true` if any element passed the callback check, * else `false`. * @example * * _.some([null, 0, 'yes', false], Boolean); * // => true * * var food = [ * { 'name': 'apple', 'organic': false, 'type': 'fruit' }, * { 'name': 'carrot', 'organic': true, 'type': 'vegetable' } * ]; * * // using "_.pluck" callback shorthand * _.some(food, 'organic'); * // => true * * // using "_.where" callback shorthand * _.some(food, { 'type': 'meat' }); * // => false */ function some(collection, callback, thisArg) { var result; callback = lodash.createCallback(callback, thisArg, 3); var index = -1, length = collection ? collection.length : 0; if (typeof length == 'number') { while (++index < length) { if ((result = callback(collection[index], index, collection))) { break; } } } else { forOwn(collection, function(value, index, collection) { return !(result = callback(value, index, collection)); }); } return !!result; } /** * Creates an array of elements, sorted in ascending order by the results of * running each element in a collection through the callback. This method * performs a stable sort, that is, it will preserve the original sort order * of equal elements. The callback is bound to `thisArg` and invoked with * three arguments; (value, index|key, collection). * * If a property name is provided for `callback` the created "_.pluck" style * callback will return the property value of the given element. * * If an object is provided for `callback` the created "_.where" style callback * will return `true` for elements that have the properties of the given object, * else `false`. * * @static * @memberOf _ * @category Collections * @param {Array|Object|string} collection The collection to iterate over. * @param {Function|Object|string} [callback=identity] The function called * per iteration. If a property name or object is provided it will be used * to create a "_.pluck" or "_.where" style callback, respectively. * @param {*} [thisArg] The `this` binding of `callback`. * @returns {Array} Returns a new array of sorted elements. * @example * * _.sortBy([1, 2, 3], function(num) { return Math.sin(num); }); * // => [3, 1, 2] * * _.sortBy([1, 2, 3], function(num) { return this.sin(num); }, Math); * // => [3, 1, 2] * * // using "_.pluck" callback shorthand * _.sortBy(['banana', 'strawberry', 'apple'], 'length'); * // => ['apple', 'banana', 'strawberry'] */ function sortBy(collection, callback, thisArg) { var index = -1, length = collection ? collection.length : 0, result = Array(typeof length == 'number' ? length : 0); callback = lodash.createCallback(callback, thisArg, 3); forEach(collection, function(value, key, collection) { var object = result[++index] = getObject(); object.criteria = callback(value, key, collection); object.index = index; object.value = value; }); length = result.length; result.sort(compareAscending); while (length--) { var object = result[length]; result[length] = object.value; releaseObject(object); } return result; } /** * Converts the `collection` to an array. * * @static * @memberOf _ * @category Collections * @param {Array|Object|string} collection The collection to convert. * @returns {Array} Returns the new converted array. * @example * * (function() { return _.toArray(arguments).slice(1); })(1, 2, 3, 4); * // => [2, 3, 4] */ function toArray(collection) { if (collection && typeof collection.length == 'number') { return slice(collection); } return values(collection); } /** * Performs a deep comparison of each element in a `collection` to the given * `properties` object, returning an array of all elements that have equivalent * property values. * * @static * @memberOf _ * @type Function * @category Collections * @param {Array|Object|string} collection The collection to iterate over. * @param {Object} properties The object of property values to filter by. * @returns {Array} Returns a new array of elements that have the given properties. * @example * * var stooges = [ * { 'name': 'curly', 'age': 30, 'quotes': ['Oh, a wise guy, eh?', 'Poifect!'] }, * { 'name': 'moe', 'age': 40, 'quotes': ['Spread out!', 'You knucklehead!'] } * ]; * * _.where(stooges, { 'age': 40 }); * // => [{ 'name': 'moe', 'age': 40, 'quotes': ['Spread out!', 'You knucklehead!'] }] * * _.where(stooges, { 'quotes': ['Poifect!'] }); * // => [{ 'name': 'curly', 'age': 30, 'quotes': ['Oh, a wise guy, eh?', 'Poifect!'] }] */ var where = filter; /*--------------------------------------------------------------------------*/ /** * Creates an array with all falsey values removed. The values `false`, `null`, * `0`, `""`, `undefined`, and `NaN` are all falsey. * * @static * @memberOf _ * @category Arrays * @param {Array} array The array to compact. * @returns {Array} Returns a new array of filtered values. * @example * * _.compact([0, 1, false, 2, '', 3]); * // => [1, 2, 3] */ function compact(array) { var index = -1, length = array ? array.length : 0, result = []; while (++index < length) { var value = array[index]; if (value) { result.push(value); } } return result; } /** * Creates an array excluding all values of the provided arrays using strict * equality for comparisons, i.e. `===`. * * @static * @memberOf _ * @category Arrays * @param {Array} array The array to process. * @param {...Array} [array] The arrays of values to exclude. * @returns {Array} Returns a new array of filtered values. * @example * * _.difference([1, 2, 3, 4, 5], [5, 2, 10]); * // => [1, 3, 4] */ function difference(array) { var index = -1, indexOf = getIndexOf(), length = array ? array.length : 0, seen = baseFlatten(arguments, true, true, 1), result = []; var isLarge = length >= largeArraySize && indexOf === baseIndexOf; if (isLarge) { var cache = createCache(seen); if (cache) { indexOf = cacheIndexOf; seen = cache; } else { isLarge = false; } } while (++index < length) { var value = array[index]; if (indexOf(seen, value) < 0) { result.push(value); } } if (isLarge) { releaseObject(seen); } return result; } /** * This method is like `_.find` except that it returns the index of the first * element that passes the callback check, instead of the element itself. * * @static * @memberOf _ * @category Arrays * @param {Array} array The array to search. * @param {Function|Object|string} [callback=identity] The function called * per iteration. If a property name or object is provided it will be used * to create a "_.pluck" or "_.where" style callback, respectively. * @param {*} [thisArg] The `this` binding of `callback`. * @returns {number} Returns the index of the found element, else `-1`. * @example * * _.findIndex(['apple', 'banana', 'beet'], function(food) { * return /^b/.test(food); * }); * // => 1 */ function findIndex(array, callback, thisArg) { var index = -1, length = array ? array.length : 0; callback = lodash.createCallback(callback, thisArg, 3); while (++index < length) { if (callback(array[index], index, array)) { return index; } } return -1; } /** * This method is like `_.findIndex` except that it iterates over elements * of a `collection` from right to left. * * @static * @memberOf _ * @category Arrays * @param {Array} array The array to search. * @param {Function|Object|string} [callback=identity] The function called * per iteration. If a property name or object is provided it will be used * to create a "_.pluck" or "_.where" style callback, respectively. * @param {*} [thisArg] The `this` binding of `callback`. * @returns {number} Returns the index of the found element, else `-1`. * @example * * _.findLastIndex(['apple', 'banana', 'beet'], function(food) { * return /^b/.test(food); * }); * // => 2 */ function findLastIndex(array, callback, thisArg) { var length = array ? array.length : 0; callback = lodash.createCallback(callback, thisArg, 3); while (length--) { if (callback(array[length], length, array)) { return length; } } return -1; } /** * Gets the first element or first `n` elements of an array. If a callback * is provided elements at the beginning of the array are returned as long * as the callback returns truey. The callback is bound to `thisArg` and * invoked with three arguments; (value, index, array). * * If a property name is provided for `callback` the created "_.pluck" style * callback will return the property value of the given element. * * If an object is provided for `callback` the created "_.where" style callback * will return `true` for elements that have the properties of the given object, * else `false`. * * @static * @memberOf _ * @alias head, take * @category Arrays * @param {Array} array The array to query. * @param {Function|Object|number|string} [callback] The function called * per element or the number of elements to return. If a property name or * object is provided it will be used to create a "_.pluck" or "_.where" * style callback, respectively. * @param {*} [thisArg] The `this` binding of `callback`. * @returns {*} Returns the first element(s) of `array`. * @example * * _.first([1, 2, 3]); * // => 1 * * _.first([1, 2, 3], 2); * // => [1, 2] * * _.first([1, 2, 3], function(num) { * return num < 3; * }); * // => [1, 2] * * var food = [ * { 'name': 'banana', 'organic': true }, * { 'name': 'beet', 'organic': false }, * ]; * * // using "_.pluck" callback shorthand * _.first(food, 'organic'); * // => [{ 'name': 'banana', 'organic': true }] * * var food = [ * { 'name': 'apple', 'type': 'fruit' }, * { 'name': 'banana', 'type': 'fruit' }, * { 'name': 'beet', 'type': 'vegetable' } * ]; * * // using "_.where" callback shorthand * _.first(food, { 'type': 'fruit' }); * // => [{ 'name': 'apple', 'type': 'fruit' }, { 'name': 'banana', 'type': 'fruit' }] */ function first(array, callback, thisArg) { var n = 0, length = array ? array.length : 0; if (typeof callback != 'number' && callback != null) { var index = -1; callback = lodash.createCallback(callback, thisArg, 3); while (++index < length && callback(array[index], index, array)) { n++; } } else { n = callback; if (n == null || thisArg) { return array ? array[0] : undefined; } } return slice(array, 0, nativeMin(nativeMax(0, n), length)); } /** * Flattens a nested array (the nesting can be to any depth). If `isShallow` * is truey, the array will only be flattened a single level. If a callback * is provided each element of the array is passed through the callback before * flattening. The callback is bound to `thisArg` and invoked with three * arguments; (value, index, array). * * If a property name is provided for `callback` the created "_.pluck" style * callback will return the property value of the given element. * * If an object is provided for `callback` the created "_.where" style callback * will return `true` for elements that have the properties of the given object, * else `false`. * * @static * @memberOf _ * @category Arrays * @param {Array} array The array to flatten. * @param {boolean} [isShallow=false] A flag to restrict flattening to a single level. * @param {Function|Object|string} [callback=identity] The function called * per iteration. If a property name or object is provided it will be used * to create a "_.pluck" or "_.where" style callback, respectively. * @param {*} [thisArg] The `this` binding of `callback`. * @returns {Array} Returns a new flattened array. * @example * * _.flatten([1, [2], [3, [[4]]]]); * // => [1, 2, 3, 4]; * * _.flatten([1, [2], [3, [[4]]]], true); * // => [1, 2, 3, [[4]]]; * * var stooges = [ * { 'name': 'curly', 'quotes': ['Oh, a wise guy, eh?', 'Poifect!'] }, * { 'name': 'moe', 'quotes': ['Spread out!', 'You knucklehead!'] } * ]; * * // using "_.pluck" callback shorthand * _.flatten(stooges, 'quotes'); * // => ['Oh, a wise guy, eh?', 'Poifect!', 'Spread out!', 'You knucklehead!'] */ function flatten(array, isShallow, callback, thisArg) { // juggle arguments if (typeof isShallow != 'boolean' && isShallow != null) { thisArg = callback; callback = !(thisArg && thisArg[isShallow] === array) ? isShallow : null; isShallow = false; } if (callback != null) { array = map(array, callback, thisArg); } return baseFlatten(array, isShallow); } /** * Gets the index at which the first occurrence of `value` is found using * strict equality for comparisons, i.e. `===`. If the array is already sorted * providing `true` for `fromIndex` will run a faster binary search. * * @static * @memberOf _ * @category Arrays * @param {Array} array The array to search. * @param {*} value The value to search for. * @param {boolean|number} [fromIndex=0] The index to search from or `true` * to perform a binary search on a sorted array. * @returns {number} Returns the index of the matched value or `-1`. * @example * * _.indexOf([1, 2, 3, 1, 2, 3], 2); * // => 1 * * _.indexOf([1, 2, 3, 1, 2, 3], 2, 3); * // => 4 * * _.indexOf([1, 1, 2, 2, 3, 3], 2, true); * // => 2 */ function indexOf(array, value, fromIndex) { if (typeof fromIndex == 'number') { var length = array ? array.length : 0; fromIndex = (fromIndex < 0 ? nativeMax(0, length + fromIndex) : fromIndex || 0); } else if (fromIndex) { var index = sortedIndex(array, value); return array[index] === value ? index : -1; } return baseIndexOf(array, value, fromIndex); } /** * Gets all but the last element or last `n` elements of an array. If a * callback is provided elements at the end of the array are excluded from * the result as long as the callback returns truey. The callback is bound * to `thisArg` and invoked with three arguments; (value, index, array). * * If a property name is provided for `callback` the created "_.pluck" style * callback will return the property value of the given element. * * If an object is provided for `callback` the created "_.where" style callback * will return `true` for elements that have the properties of the given object, * else `false`. * * @static * @memberOf _ * @category Arrays * @param {Array} array The array to query. * @param {Function|Object|number|string} [callback=1] The function called * per element or the number of elements to exclude. If a property name or * object is provided it will be used to create a "_.pluck" or "_.where" * style callback, respectively. * @param {*} [thisArg] The `this` binding of `callback`. * @returns {Array} Returns a slice of `array`. * @example * * _.initial([1, 2, 3]); * // => [1, 2] * * _.initial([1, 2, 3], 2); * // => [1] * * _.initial([1, 2, 3], function(num) { * return num > 1; * }); * // => [1] * * var food = [ * { 'name': 'beet', 'organic': false }, * { 'name': 'carrot', 'organic': true } * ]; * * // using "_.pluck" callback shorthand * _.initial(food, 'organic'); * // => [{ 'name': 'beet', 'organic': false }] * * var food = [ * { 'name': 'banana', 'type': 'fruit' }, * { 'name': 'beet', 'type': 'vegetable' }, * { 'name': 'carrot', 'type': 'vegetable' } * ]; * * // using "_.where" callback shorthand * _.initial(food, { 'type': 'vegetable' }); * // => [{ 'name': 'banana', 'type': 'fruit' }] */ function initial(array, callback, thisArg) { var n = 0, length = array ? array.length : 0; if (typeof callback != 'number' && callback != null) { var index = length; callback = lodash.createCallback(callback, thisArg, 3); while (index-- && callback(array[index], index, array)) { n++; } } else { n = (callback == null || thisArg) ? 1 : callback || n; } return slice(array, 0, nativeMin(nativeMax(0, length - n), length)); } /** * Creates an array of unique values present in all provided arrays using * strict equality for comparisons, i.e. `===`. * * @static * @memberOf _ * @category Arrays * @param {...Array} [array] The arrays to inspect. * @returns {Array} Returns an array of composite values. * @example * * _.intersection([1, 2, 3], [101, 2, 1, 10], [2, 1]); * // => [1, 2] */ function intersection(array) { var args = arguments, argsLength = args.length, argsIndex = -1, caches = getArray(), index = -1, indexOf = getIndexOf(), length = array ? array.length : 0, result = [], seen = getArray(); while (++argsIndex < argsLength) { var value = args[argsIndex]; caches[argsIndex] = indexOf === baseIndexOf && (value ? value.length : 0) >= largeArraySize && createCache(argsIndex ? args[argsIndex] : seen); } outer: while (++index < length) { var cache = caches[0]; value = array[index]; if ((cache ? cacheIndexOf(cache, value) : indexOf(seen, value)) < 0) { argsIndex = argsLength; (cache || seen).push(value); while (--argsIndex) { cache = caches[argsIndex]; if ((cache ? cacheIndexOf(cache, value) : indexOf(args[argsIndex], value)) < 0) { continue outer; } } result.push(value); } } while (argsLength--) { cache = caches[argsLength]; if (cache) { releaseObject(cache); } } releaseArray(caches); releaseArray(seen); return result; } /** * Gets the last element or last `n` elements of an array. If a callback is * provided elements at the end of the array are returned as long as the * callback returns truey. The callback is bound to `thisArg` and invoked * with three arguments; (value, index, array). * * If a property name is provided for `callback` the created "_.pluck" style * callback will return the property value of the given element. * * If an object is provided for `callback` the created "_.where" style callback * will return `true` for elements that have the properties of the given object, * else `false`. * * @static * @memberOf _ * @category Arrays * @param {Array} array The array to query. * @param {Function|Object|number|string} [callback] The function called * per element or the number of elements to return. If a property name or * object is provided it will be used to create a "_.pluck" or "_.where" * style callback, respectively. * @param {*} [thisArg] The `this` binding of `callback`. * @returns {*} Returns the last element(s) of `array`. * @example * * _.last([1, 2, 3]); * // => 3 * * _.last([1, 2, 3], 2); * // => [2, 3] * * _.last([1, 2, 3], function(num) { * return num > 1; * }); * // => [2, 3] * * var food = [ * { 'name': 'beet', 'organic': false }, * { 'name': 'carrot', 'organic': true } * ]; * * // using "_.pluck" callback shorthand * _.last(food, 'organic'); * // => [{ 'name': 'carrot', 'organic': true }] * * var food = [ * { 'name': 'banana', 'type': 'fruit' }, * { 'name': 'beet', 'type': 'vegetable' }, * { 'name': 'carrot', 'type': 'vegetable' } * ]; * * // using "_.where" callback shorthand * _.last(food, { 'type': 'vegetable' }); * // => [{ 'name': 'beet', 'type': 'vegetable' }, { 'name': 'carrot', 'type': 'vegetable' }] */ function last(array, callback, thisArg) { var n = 0, length = array ? array.length : 0; if (typeof callback != 'number' && callback != null) { var index = length; callback = lodash.createCallback(callback, thisArg, 3); while (index-- && callback(array[index], index, array)) { n++; } } else { n = callback; if (n == null || thisArg) { return array ? array[length - 1] : undefined; } } return slice(array, nativeMax(0, length - n)); } /** * Gets the index at which the last occurrence of `value` is found using strict * equality for comparisons, i.e. `===`. If `fromIndex` is negative, it is used * as the offset from the end of the collection. * * @static * @memberOf _ * @category Arrays * @param {Array} array The array to search. * @param {*} value The value to search for. * @param {number} [fromIndex=array.length-1] The index to search from. * @returns {number} Returns the index of the matched value or `-1`. * @example * * _.lastIndexOf([1, 2, 3, 1, 2, 3], 2); * // => 4 * * _.lastIndexOf([1, 2, 3, 1, 2, 3], 2, 3); * // => 1 */ function lastIndexOf(array, value, fromIndex) { var index = array ? array.length : 0; if (typeof fromIndex == 'number') { index = (fromIndex < 0 ? nativeMax(0, index + fromIndex) : nativeMin(fromIndex, index - 1)) + 1; } while (index--) { if (array[index] === value) { return index; } } return -1; } /** * Removes all provided values from the given array using strict equality for * comparisons, i.e. `===`. * * @static * @memberOf _ * @category Arrays * @param {Array} array The array to modify. * @param {...*} [value] The values to remove. * @returns {Array} Returns `array`. * @example * * var array = [1, 2, 3, 1, 2, 3]; * _.pull(array, 2, 3); * console.log(array); * // => [1, 1] */ function pull(array) { var args = arguments, argsIndex = 0, argsLength = args.length, length = array ? array.length : 0; while (++argsIndex < argsLength) { var index = -1, value = args[argsIndex]; while (++index < length) { if (array[index] === value) { splice.call(array, index--, 1); length--; } } } return array; } /** * Creates an array of numbers (positive and/or negative) progressing from * `start` up to but not including `end`. If `start` is less than `stop` a * zero-length range is created unless a negative `step` is specified. * * @static * @memberOf _ * @category Arrays * @param {number} [start=0] The start of the range. * @param {number} end The end of the range. * @param {number} [step=1] The value to increment or decrement by. * @returns {Array} Returns a new range array. * @example * * _.range(10); * // => [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] * * _.range(1, 11); * // => [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] * * _.range(0, 30, 5); * // => [0, 5, 10, 15, 20, 25] * * _.range(0, -10, -1); * // => [0, -1, -2, -3, -4, -5, -6, -7, -8, -9] * * _.range(1, 4, 0); * // => [1, 1, 1] * * _.range(0); * // => [] */ function range(start, end, step) { start = +start || 0; step = typeof step == 'number' ? step : (+step || 1); if (end == null) { end = start; start = 0; } // use `Array(length)` so engines, like Chakra and V8, avoid slower modes // http://youtu.be/XAqIpGU8ZZk#t=17m25s var index = -1, length = nativeMax(0, ceil((end - start) / (step || 1))), result = Array(length); while (++index < length) { result[index] = start; start += step; } return result; } /** * Removes all elements from an array that the callback returns truey for * and returns an array of removed elements. The callback is bound to `thisArg` * and invoked with three arguments; (value, index, array). * * If a property name is provided for `callback` the created "_.pluck" style * callback will return the property value of the given element. * * If an object is provided for `callback` the created "_.where" style callback * will return `true` for elements that have the properties of the given object, * else `false`. * * @static * @memberOf _ * @category Arrays * @param {Array} array The array to modify. * @param {Function|Object|string} [callback=identity] The function called * per iteration. If a property name or object is provided it will be used * to create a "_.pluck" or "_.where" style callback, respectively. * @param {*} [thisArg] The `this` binding of `callback`. * @returns {Array} Returns a new array of removed elements. * @example * * var array = [1, 2, 3, 4, 5, 6]; * var evens = _.remove(array, function(num) { return num % 2 == 0; }); * * console.log(array); * // => [1, 3, 5] * * console.log(evens); * // => [2, 4, 6] */ function remove(array, callback, thisArg) { var index = -1, length = array ? array.length : 0, result = []; callback = lodash.createCallback(callback, thisArg, 3); while (++index < length) { var value = array[index]; if (callback(value, index, array)) { result.push(value); splice.call(array, index--, 1); length--; } } return result; } /** * The opposite of `_.initial` this method gets all but the first element or * first `n` elements of an array. If a callback function is provided elements * at the beginning of the array are excluded from the result as long as the * callback returns truey. The callback is bound to `thisArg` and invoked * with three arguments; (value, index, array). * * If a property name is provided for `callback` the created "_.pluck" style * callback will return the property value of the given element. * * If an object is provided for `callback` the created "_.where" style callback * will return `true` for elements that have the properties of the given object, * else `false`. * * @static * @memberOf _ * @alias drop, tail * @category Arrays * @param {Array} array The array to query. * @param {Function|Object|number|string} [callback=1] The function called * per element or the number of elements to exclude. If a property name or * object is provided it will be used to create a "_.pluck" or "_.where" * style callback, respectively. * @param {*} [thisArg] The `this` binding of `callback`. * @returns {Array} Returns a slice of `array`. * @example * * _.rest([1, 2, 3]); * // => [2, 3] * * _.rest([1, 2, 3], 2); * // => [3] * * _.rest([1, 2, 3], function(num) { * return num < 3; * }); * // => [3] * * var food = [ * { 'name': 'banana', 'organic': true }, * { 'name': 'beet', 'organic': false }, * ]; * * // using "_.pluck" callback shorthand * _.rest(food, 'organic'); * // => [{ 'name': 'beet', 'organic': false }] * * var food = [ * { 'name': 'apple', 'type': 'fruit' }, * { 'name': 'banana', 'type': 'fruit' }, * { 'name': 'beet', 'type': 'vegetable' } * ]; * * // using "_.where" callback shorthand * _.rest(food, { 'type': 'fruit' }); * // => [{ 'name': 'beet', 'type': 'vegetable' }] */ function rest(array, callback, thisArg) { if (typeof callback != 'number' && callback != null) { var n = 0, index = -1, length = array ? array.length : 0; callback = lodash.createCallback(callback, thisArg, 3); while (++index < length && callback(array[index], index, array)) { n++; } } else { n = (callback == null || thisArg) ? 1 : nativeMax(0, callback); } return slice(array, n); } /** * Uses a binary search to determine the smallest index at which a value * should be inserted into a given sorted array in order to maintain the sort * order of the array. If a callback is provided it will be executed for * `value` and each element of `array` to compute their sort ranking. The * callback is bound to `thisArg` and invoked with one argument; (value). * * If a property name is provided for `callback` the created "_.pluck" style * callback will return the property value of the given element. * * If an object is provided for `callback` the created "_.where" style callback * will return `true` for elements that have the properties of the given object, * else `false`. * * @static * @memberOf _ * @category Arrays * @param {Array} array The array to inspect. * @param {*} value The value to evaluate. * @param {Function|Object|string} [callback=identity] The function called * per iteration. If a property name or object is provided it will be used * to create a "_.pluck" or "_.where" style callback, respectively. * @param {*} [thisArg] The `this` binding of `callback`. * @returns {number} Returns the index at which `value` should be inserted * into `array`. * @example * * _.sortedIndex([20, 30, 50], 40); * // => 2 * * // using "_.pluck" callback shorthand * _.sortedIndex([{ 'x': 20 }, { 'x': 30 }, { 'x': 50 }], { 'x': 40 }, 'x'); * // => 2 * * var dict = { * 'wordToNumber': { 'twenty': 20, 'thirty': 30, 'fourty': 40, 'fifty': 50 } * }; * * _.sortedIndex(['twenty', 'thirty', 'fifty'], 'fourty', function(word) { * return dict.wordToNumber[word]; * }); * // => 2 * * _.sortedIndex(['twenty', 'thirty', 'fifty'], 'fourty', function(word) { * return this.wordToNumber[word]; * }, dict); * // => 2 */ function sortedIndex(array, value, callback, thisArg) { var low = 0, high = array ? array.length : low; // explicitly reference `identity` for better inlining in Firefox callback = callback ? lodash.createCallback(callback, thisArg, 1) : identity; value = callback(value); while (low < high) { var mid = (low + high) >>> 1; (callback(array[mid]) < value) ? low = mid + 1 : high = mid; } return low; } /** * Creates an array of unique values, in order, of the provided arrays using * strict equality for comparisons, i.e. `===`. * * @static * @memberOf _ * @category Arrays * @param {...Array} [array] The arrays to inspect. * @returns {Array} Returns an array of composite values. * @example * * _.union([1, 2, 3], [101, 2, 1, 10], [2, 1]); * // => [1, 2, 3, 101, 10] */ function union(array) { return baseUniq(baseFlatten(arguments, true, true)); } /** * Creates a duplicate-value-free version of an array using strict equality * for comparisons, i.e. `===`. If the array is sorted, providing * `true` for `isSorted` will use a faster algorithm. If a callback is provided * each element of `array` is passed through the callback before uniqueness * is computed. The callback is bound to `thisArg` and invoked with three * arguments; (value, index, array). * * If a property name is provided for `callback` the created "_.pluck" style * callback will return the property value of the given element. * * If an object is provided for `callback` the created "_.where" style callback * will return `true` for elements that have the properties of the given object, * else `false`. * * @static * @memberOf _ * @alias unique * @category Arrays * @param {Array} array The array to process. * @param {boolean} [isSorted=false] A flag to indicate that `array` is sorted. * @param {Function|Object|string} [callback=identity] The function called * per iteration. If a property name or object is provided it will be used * to create a "_.pluck" or "_.where" style callback, respectively. * @param {*} [thisArg] The `this` binding of `callback`. * @returns {Array} Returns a duplicate-value-free array. * @example * * _.uniq([1, 2, 1, 3, 1]); * // => [1, 2, 3] * * _.uniq([1, 1, 2, 2, 3], true); * // => [1, 2, 3] * * _.uniq(['A', 'b', 'C', 'a', 'B', 'c'], function(letter) { return letter.toLowerCase(); }); * // => ['A', 'b', 'C'] * * _.uniq([1, 2.5, 3, 1.5, 2, 3.5], function(num) { return this.floor(num); }, Math); * // => [1, 2.5, 3] * * // using "_.pluck" callback shorthand * _.uniq([{ 'x': 1 }, { 'x': 2 }, { 'x': 1 }], 'x'); * // => [{ 'x': 1 }, { 'x': 2 }] */ function uniq(array, isSorted, callback, thisArg) { // juggle arguments if (typeof isSorted != 'boolean' && isSorted != null) { thisArg = callback; callback = !(thisArg && thisArg[isSorted] === array) ? isSorted : null; isSorted = false; } if (callback != null) { callback = lodash.createCallback(callback, thisArg, 3); } return baseUniq(array, isSorted, callback); } /** * Creates an array excluding all provided values using strict equality for * comparisons, i.e. `===`. * * @static * @memberOf _ * @category Arrays * @param {Array} array The array to filter. * @param {...*} [value] The values to exclude. * @returns {Array} Returns a new array of filtered values. * @example * * _.without([1, 2, 1, 0, 3, 1, 4], 0, 1); * // => [2, 3, 4] */ function without(array) { return difference(array, nativeSlice.call(arguments, 1)); } /** * Creates an array of grouped elements, the first of which contains the first * elements of the given arrays, the second of which contains the second * elements of the given arrays, and so on. * * @static * @memberOf _ * @alias unzip * @category Arrays * @param {...Array} [array] Arrays to process. * @returns {Array} Returns a new array of grouped elements. * @example * * _.zip(['moe', 'larry'], [30, 40], [true, false]); * // => [['moe', 30, true], ['larry', 40, false]] */ function zip() { var array = arguments.length > 1 ? arguments : arguments[0], index = -1, length = array ? max(pluck(array, 'length')) : 0, result = Array(length < 0 ? 0 : length); while (++index < length) { result[index] = pluck(array, index); } return result; } /** * Creates an object composed from arrays of `keys` and `values`. Provide * either a single two dimensional array, i.e. `[[key1, value1], [key2, value2]]` * or two arrays, one of `keys` and one of corresponding `values`. * * @static * @memberOf _ * @alias object * @category Arrays * @param {Array} keys The array of keys. * @param {Array} [values=[]] The array of values. * @returns {Object} Returns an object composed of the given keys and * corresponding values. * @example * * _.zipObject(['moe', 'larry'], [30, 40]); * // => { 'moe': 30, 'larry': 40 } */ function zipObject(keys, values) { var index = -1, length = keys ? keys.length : 0, result = {}; while (++index < length) { var key = keys[index]; if (values) { result[key] = values[index]; } else if (key) { result[key[0]] = key[1]; } } return result; } /*--------------------------------------------------------------------------*/ /** * Creates a function that executes `func`, with the `this` binding and * arguments of the created function, only after being called `n` times. * * @static * @memberOf _ * @category Functions * @param {number} n The number of times the function must be called before * `func` is executed. * @param {Function} func The function to restrict. * @returns {Function} Returns the new restricted function. * @example * * var saves = ['profile', 'settings']; * * var done = _.after(saves.length, function() { * console.log('Done saving!'); * }); * * _.forEach(saves, function(type) { * asyncSave({ 'type': type, 'complete': done }); * }); * // => logs 'Done saving!', after all saves have completed */ function after(n, func) { if (!isFunction(func)) { throw new TypeError; } return function() { if (--n < 1) { return func.apply(this, arguments); } }; } /** * Creates a function that, when called, invokes `func` with the `this` * binding of `thisArg` and prepends any additional `bind` arguments to those * provided to the bound function. * * @static * @memberOf _ * @category Functions * @param {Function} func The function to bind. * @param {*} [thisArg] The `this` binding of `func`. * @param {...*} [arg] Arguments to be partially applied. * @returns {Function} Returns the new bound function. * @example * * var func = function(greeting) { * return greeting + ' ' + this.name; * }; * * func = _.bind(func, { 'name': 'moe' }, 'hi'); * func(); * // => 'hi moe' */ function bind(func, thisArg) { return arguments.length > 2 ? createBound(func, 17, nativeSlice.call(arguments, 2), null, thisArg) : createBound(func, 1, null, null, thisArg); } /** * Binds methods of an object to the object itself, overwriting the existing * method. Method names may be specified as individual arguments or as arrays * of method names. If no method names are provided all the function properties * of `object` will be bound. * * @static * @memberOf _ * @category Functions * @param {Object} object The object to bind and assign the bound methods to. * @param {...string} [methodName] The object method names to * bind, specified as individual method names or arrays of method names. * @returns {Object} Returns `object`. * @example * * var view = { * 'label': 'docs', * 'onClick': function() { console.log('clicked ' + this.label); } * }; * * _.bindAll(view); * jQuery('#docs').on('click', view.onClick); * // => logs 'clicked docs', when the button is clicked */ function bindAll(object) { var funcs = arguments.length > 1 ? baseFlatten(arguments, true, false, 1) : functions(object), index = -1, length = funcs.length; while (++index < length) { var key = funcs[index]; object[key] = createBound(object[key], 1, null, null, object); } return object; } /** * Creates a function that, when called, invokes the method at `object[key]` * and prepends any additional `bindKey` arguments to those provided to the bound * function. This method differs from `_.bind` by allowing bound functions to * reference methods that will be redefined or don't yet exist. * See http://michaux.ca/articles/lazy-function-definition-pattern. * * @static * @memberOf _ * @category Functions * @param {Object} object The object the method belongs to. * @param {string} key The key of the method. * @param {...*} [arg] Arguments to be partially applied. * @returns {Function} Returns the new bound function. * @example * * var object = { * 'name': 'moe', * 'greet': function(greeting) { * return greeting + ' ' + this.name; * } * }; * * var func = _.bindKey(object, 'greet', 'hi'); * func(); * // => 'hi moe' * * object.greet = function(greeting) { * return greeting + ', ' + this.name + '!'; * }; * * func(); * // => 'hi, moe!' */ function bindKey(object, key) { return arguments.length > 2 ? createBound(key, 19, nativeSlice.call(arguments, 2), null, object) : createBound(key, 3, null, null, object); } /** * Creates a function that is the composition of the provided functions, * where each function consumes the return value of the function that follows. * For example, composing the functions `f()`, `g()`, and `h()` produces `f(g(h()))`. * Each function is executed with the `this` binding of the composed function. * * @static * @memberOf _ * @category Functions * @param {...Function} [func] Functions to compose. * @returns {Function} Returns the new composed function. * @example * * var realNameMap = { * 'curly': 'jerome' * }; * * var format = function(name) { * name = realNameMap[name.toLowerCase()] || name; * return name.charAt(0).toUpperCase() + name.slice(1).toLowerCase(); * }; * * var greet = function(formatted) { * return 'Hiya ' + formatted + '!'; * }; * * var welcome = _.compose(greet, format); * welcome('curly'); * // => 'Hiya Jerome!' */ function compose() { var funcs = arguments, length = funcs.length; while (length--) { if (!isFunction(funcs[length])) { throw new TypeError; } } return function() { var args = arguments, length = funcs.length; while (length--) { args = [funcs[length].apply(this, args)]; } return args[0]; }; } /** * Produces a callback bound to an optional `thisArg`. If `func` is a property * name the created callback will return the property value for a given element. * If `func` is an object the created callback will return `true` for elements * that contain the equivalent object properties, otherwise it will return `false`. * * @static * @memberOf _ * @category Functions * @param {*} [func=identity] The value to convert to a callback. * @param {*} [thisArg] The `this` binding of the created callback. * @param {number} [argCount] The number of arguments the callback accepts. * @returns {Function} Returns a callback function. * @example * * var stooges = [ * { 'name': 'moe', 'age': 40 }, * { 'name': 'larry', 'age': 50 } * ]; * * // wrap to create custom callback shorthands * _.createCallback = _.wrap(_.createCallback, function(func, callback, thisArg) { * var match = /^(.+?)__([gl]t)(.+)$/.exec(callback); * return !match ? func(callback, thisArg) : function(object) { * return match[2] == 'gt' ? object[match[1]] > match[3] : object[match[1]] < match[3]; * }; * }); * * _.filter(stooges, 'age__gt45'); * // => [{ 'name': 'larry', 'age': 50 }] */ function createCallback(func, thisArg, argCount) { var type = typeof func; if (func == null || type == 'function') { return baseCreateCallback(func, thisArg, argCount); } // handle "_.pluck" style callback shorthands if (type != 'object') { return function(object) { return object[func]; }; } var props = keys(func), key = props[0], a = func[key]; // handle "_.where" style callback shorthands if (props.length == 1 && a === a && !isObject(a)) { // fast path the common case of providing an object with a single // property containing a primitive value return function(object) { var b = object[key]; return a === b && (a !== 0 || (1 / a == 1 / b)); }; } return function(object) { var length = props.length, result = false; while (length--) { if (!(result = baseIsEqual(object[props[length]], func[props[length]], null, true))) { break; } } return result; }; } /** * Creates a function which accepts one or more arguments of `func` that when * invoked either executes `func` returning its result, if all `func` arguments * have been provided, or returns a function that accepts one or more of the * remaining `func` arguments, and so on. The arity of `func` can be specified * if `func.length` is not sufficient. * * @static * @memberOf _ * @category Functions * @param {Function} func The function to curry. * @param {number} [arity=func.length] The arity of `func`. * @returns {Function} Returns the new curried function. * @example * * var curried = _.curry(function(a, b, c) { * console.log(a + b + c); * }); * * curried(1)(2)(3); * // => 6 * * curried(1, 2)(3); * // => 6 * * curried(1, 2, 3); * // => 6 */ function curry(func, arity) { arity = typeof arity == 'number' ? arity : (+arity || func.length); return createBound(func, 4, null, null, null, arity); } /** * Creates a function that will delay the execution of `func` until after * `wait` milliseconds have elapsed since the last time it was invoked. * Provide an options object to indicate that `func` should be invoked on * the leading and/or trailing edge of the `wait` timeout. Subsequent calls * to the debounced function will return the result of the last `func` call. * * Note: If `leading` and `trailing` options are `true` `func` will be called * on the trailing edge of the timeout only if the the debounced function is * invoked more than once during the `wait` timeout. * * @static * @memberOf _ * @category Functions * @param {Function} func The function to debounce. * @param {number} wait The number of milliseconds to delay. * @param {Object} [options] The options object. * @param {boolean} [options.leading=false] Specify execution on the leading edge of the timeout. * @param {number} [options.maxWait] The maximum time `func` is allowed to be delayed before it's called. * @param {boolean} [options.trailing=true] Specify execution on the trailing edge of the timeout. * @returns {Function} Returns the new debounced function. * @example * * // avoid costly calculations while the window size is in flux * var lazyLayout = _.debounce(calculateLayout, 150); * jQuery(window).on('resize', lazyLayout); * * // execute `sendMail` when the click event is fired, debouncing subsequent calls * jQuery('#postbox').on('click', _.debounce(sendMail, 300, { * 'leading': true, * 'trailing': false * }); * * // ensure `batchLog` is executed once after 1 second of debounced calls * var source = new EventSource('/stream'); * source.addEventListener('message', _.debounce(batchLog, 250, { * 'maxWait': 1000 * }, false); */ function debounce(func, wait, options) { var args, maxTimeoutId, result, stamp, thisArg, timeoutId, trailingCall, lastCalled = 0, maxWait = false, trailing = true; if (!isFunction(func)) { throw new TypeError; } wait = nativeMax(0, wait) || 0; if (options === true) { var leading = true; trailing = false; } else if (isObject(options)) { leading = options.leading; maxWait = 'maxWait' in options && (nativeMax(wait, options.maxWait) || 0); trailing = 'trailing' in options ? options.trailing : trailing; } var delayed = function() { var remaining = wait - (now() - stamp); if (remaining <= 0) { if (maxTimeoutId) { clearTimeout(maxTimeoutId); } var isCalled = trailingCall; maxTimeoutId = timeoutId = trailingCall = undefined; if (isCalled) { lastCalled = now(); result = func.apply(thisArg, args); } } else { timeoutId = setTimeout(delayed, remaining); } }; var maxDelayed = function() { if (timeoutId) { clearTimeout(timeoutId); } maxTimeoutId = timeoutId = trailingCall = undefined; if (trailing || (maxWait !== wait)) { lastCalled = now(); result = func.apply(thisArg, args); } }; return function() { args = arguments; stamp = now(); thisArg = this; trailingCall = trailing && (timeoutId || !leading); if (maxWait === false) { var leadingCall = leading && !timeoutId; } else { if (!maxTimeoutId && !leading) { lastCalled = stamp; } var remaining = maxWait - (stamp - lastCalled); if (remaining <= 0) { if (maxTimeoutId) { maxTimeoutId = clearTimeout(maxTimeoutId); } lastCalled = stamp; result = func.apply(thisArg, args); } else if (!maxTimeoutId) { maxTimeoutId = setTimeout(maxDelayed, remaining); } } if (!timeoutId && wait !== maxWait) { timeoutId = setTimeout(delayed, wait); } if (leadingCall) { result = func.apply(thisArg, args); } return result; }; } /** * Defers executing the `func` function until the current call stack has cleared. * Additional arguments will be provided to `func` when it is invoked. * * @static * @memberOf _ * @category Functions * @param {Function} func The function to defer. * @param {...*} [arg] Arguments to invoke the function with. * @returns {number} Returns the timer id. * @example * * _.defer(function() { console.log('deferred'); }); * // returns from the function before 'deferred' is logged */ function defer(func) { if (!isFunction(func)) { throw new TypeError; } var args = nativeSlice.call(arguments, 1); return setTimeout(function() { func.apply(undefined, args); }, 1); } // use `setImmediate` if available in Node.js if (isV8 && moduleExports && typeof setImmediate == 'function') { defer = function(func) { if (!isFunction(func)) { throw new TypeError; } return setImmediate.apply(context, arguments); }; } /** * Executes the `func` function after `wait` milliseconds. Additional arguments * will be provided to `func` when it is invoked. * * @static * @memberOf _ * @category Functions * @param {Function} func The function to delay. * @param {number} wait The number of milliseconds to delay execution. * @param {...*} [arg] Arguments to invoke the function with. * @returns {number} Returns the timer id. * @example * * var log = _.bind(console.log, console); * _.delay(log, 1000, 'logged later'); * // => 'logged later' (Appears after one second.) */ function delay(func, wait) { if (!isFunction(func)) { throw new TypeError; } var args = nativeSlice.call(arguments, 2); return setTimeout(function() { func.apply(undefined, args); }, wait); } /** * Creates a function that memoizes the result of `func`. If `resolver` is * provided it will be used to determine 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 cache key. * The `func` is executed with the `this` binding of the memoized function. * The result cache is exposed as the `cache` property on the memoized function. * * @static * @memberOf _ * @category Functions * @param {Function} func The function to have its output memoized. * @param {Function} [resolver] A function used to resolve the cache key. * @returns {Function} Returns the new memoizing function. * @example * * var fibonacci = _.memoize(function(n) { * return n < 2 ? n : fibonacci(n - 1) + fibonacci(n - 2); * }); * * var data = { * 'moe': { 'name': 'moe', 'age': 40 }, * 'curly': { 'name': 'curly', 'age': 60 } * }; * * // modifying the result cache * var stooge = _.memoize(function(name) { return data[name]; }, _.identity); * stooge('curly'); * // => { 'name': 'curly', 'age': 60 } * * stooge.cache.curly.name = 'jerome'; * stooge('curly'); * // => { 'name': 'jerome', 'age': 60 } */ function memoize(func, resolver) { if (!isFunction(func)) { throw new TypeError; } var memoized = function() { var cache = memoized.cache, key = resolver ? resolver.apply(this, arguments) : keyPrefix + arguments[0]; return hasOwnProperty.call(cache, key) ? cache[key] : (cache[key] = func.apply(this, arguments)); } memoized.cache = {}; return memoized; } /** * Creates a function that is restricted to execute `func` once. Repeat calls to * the function will return the value of the first call. The `func` is executed * with the `this` binding of the created function. * * @static * @memberOf _ * @category Functions * @param {Function} func The function to restrict. * @returns {Function} Returns the new restricted function. * @example * * var initialize = _.once(createApplication); * initialize(); * initialize(); * // `initialize` executes `createApplication` once */ function once(func) { var ran, result; if (!isFunction(func)) { throw new TypeError; } return function() { if (ran) { return result; } ran = true; result = func.apply(this, arguments); // clear the `func` variable so the function may be garbage collected func = null; return result; }; } /** * Creates a function that, when called, invokes `func` with any additional * `partial` arguments prepended to those provided to the new function. This * method is similar to `_.bind` except it does **not** alter the `this` binding. * * @static * @memberOf _ * @category Functions * @param {Function} func The function to partially apply arguments to. * @param {...*} [arg] Arguments to be partially applied. * @returns {Function} Returns the new partially applied function. * @example * * var greet = function(greeting, name) { return greeting + ' ' + name; }; * var hi = _.partial(greet, 'hi'); * hi('moe'); * // => 'hi moe' */ function partial(func) { return createBound(func, 16, nativeSlice.call(arguments, 1)); } /** * This method is like `_.partial` except that `partial` arguments are * appended to those provided to the new function. * * @static * @memberOf _ * @category Functions * @param {Function} func The function to partially apply arguments to. * @param {...*} [arg] Arguments to be partially applied. * @returns {Function} Returns the new partially applied function. * @example * * var defaultsDeep = _.partialRight(_.merge, _.defaults); * * var options = { * 'variable': 'data', * 'imports': { 'jq': $ } * }; * * defaultsDeep(options, _.templateSettings); * * options.variable * // => 'data' * * options.imports * // => { '_': _, 'jq': $ } */ function partialRight(func) { return createBound(func, 32, null, nativeSlice.call(arguments, 1)); } /** * Creates a function that, when executed, will only call the `func` function * at most once per every `wait` milliseconds. Provide an options object to * indicate that `func` should be invoked on the leading and/or trailing edge * of the `wait` timeout. Subsequent calls to the throttled function will * return the result of the last `func` call. * * Note: If `leading` and `trailing` options are `true` `func` will be called * on the trailing edge of the timeout only if the the throttled function is * invoked more than once during the `wait` timeout. * * @static * @memberOf _ * @category Functions * @param {Function} func The function to throttle. * @param {number} wait The number of milliseconds to throttle executions to. * @param {Object} [options] The options object. * @param {boolean} [options.leading=true] Specify execution on the leading edge of the timeout. * @param {boolean} [options.trailing=true] Specify execution on the trailing edge of the timeout. * @returns {Function} Returns the new throttled function. * @example * * // avoid excessively updating the position while scrolling * var throttled = _.throttle(updatePosition, 100); * jQuery(window).on('scroll', throttled); * * // execute `renewToken` when the click event is fired, but not more than once every 5 minutes * jQuery('.interactive').on('click', _.throttle(renewToken, 300000, { * 'trailing': false * })); */ function throttle(func, wait, options) { var leading = true, trailing = true; if (!isFunction(func)) { throw new TypeError; } if (options === false) { leading = false; } else if (isObject(options)) { leading = 'leading' in options ? options.leading : leading; trailing = 'trailing' in options ? options.trailing : trailing; } debounceOptions.leading = leading; debounceOptions.maxWait = wait; debounceOptions.trailing = trailing; var result = debounce(func, wait, debounceOptions); return result; } /** * Creates a function that provides `value` to the wrapper function as its * first argument. Additional arguments provided to the function are appended * to those provided to the wrapper function. The wrapper is executed with * the `this` binding of the created function. * * @static * @memberOf _ * @category Functions * @param {*} value The value to wrap. * @param {Function} wrapper The wrapper function. * @returns {Function} Returns the new function. * @example * * var hello = function(name) { return 'hello ' + name; }; * hello = _.wrap(hello, function(func) { * return 'before, ' + func('moe') + ', after'; * }); * hello(); * // => 'before, hello moe, after' */ function wrap(value, wrapper) { if (!isFunction(wrapper)) { throw new TypeError; } return function() { var args = [value]; push.apply(args, arguments); return wrapper.apply(this, args); }; } /*--------------------------------------------------------------------------*/ /** * Converts the characters `&`, `<`, `>`, `"`, and `'` in `string` to their * corresponding HTML entities. * * @static * @memberOf _ * @category Utilities * @param {string} string The string to escape. * @returns {string} Returns the escaped string. * @example * * _.escape('Moe, Larry & Curly'); * // => 'Moe, Larry &amp; Curly' */ function escape(string) { return string == null ? '' : String(string).replace(reUnescapedHtml, escapeHtmlChar); } /** * This method returns the first argument provided to it. * * @static * @memberOf _ * @category Utilities * @param {*} value Any value. * @returns {*} Returns `value`. * @example * * var moe = { 'name': 'moe' }; * moe === _.identity(moe); * // => true */ function identity(value) { return value; } /** * Adds function properties of a source object to the `lodash` function and * chainable wrapper. * * @static * @memberOf _ * @category Utilities * @param {Object} object The object of function properties to add to `lodash`. * @param {Object} object The object of function properties to add to `lodash`. * @example * * _.mixin({ * 'capitalize': function(string) { * return string.charAt(0).toUpperCase() + string.slice(1).toLowerCase(); * } * }); * * _.capitalize('moe'); * // => 'Moe' * * _('moe').capitalize(); * // => 'Moe' */ function mixin(object, source) { var ctor = object, isFunc = !source || isFunction(ctor); if (!source) { ctor = lodashWrapper; source = object; object = lodash; } forEach(functions(source), function(methodName) { var func = object[methodName] = source[methodName]; if (isFunc) { ctor.prototype[methodName] = function() { var value = this.__wrapped__, args = [value]; push.apply(args, arguments); var result = func.apply(object, args); if (value && typeof value == 'object' && value === result) { return this; } result = new ctor(result); result.__chain__ = this.__chain__; return result; }; } }); } /** * Reverts the '_' variable to its previous value and returns a reference to * the `lodash` function. * * @static * @memberOf _ * @category Utilities * @returns {Function} Returns the `lodash` function. * @example * * var lodash = _.noConflict(); */ function noConflict() { context._ = oldDash; return this; } /** * Converts the given value into an integer of the specified radix. * If `radix` is `undefined` or `0` a `radix` of `10` is used unless the * `value` is a hexadecimal, in which case a `radix` of `16` is used. * * Note: This method avoids differences in native ES3 and ES5 `parseInt` * implementations. See http://es5.github.io/#E. * * @static * @memberOf _ * @category Utilities * @param {string} value The value to parse. * @param {number} [radix] The radix used to interpret the value to parse. * @returns {number} Returns the new integer value. * @example * * _.parseInt('08'); * // => 8 */ var parseInt = nativeParseInt(whitespace + '08') == 8 ? nativeParseInt : function(value, radix) { // Firefox and Opera still follow the ES3 specified implementation of `parseInt` return nativeParseInt(isString(value) ? value.replace(reLeadingSpacesAndZeros, '') : value, radix || 0); }; /** * Produces a random number between `min` and `max` (inclusive). If only one * argument is provided a number between `0` and the given number will be * returned. If `floating` is truey or either `min` or `max` are floats a * floating-point number will be returned instead of an integer. * * @static * @memberOf _ * @category Utilities * @param {number} [min=0] The minimum possible value. * @param {number} [max=1] The maximum possible value. * @param {boolean} [floating=false] Specify returning a floating-point number. * @returns {number} Returns a random number. * @example * * _.random(0, 5); * // => an integer between 0 and 5 * * _.random(5); * // => also an integer between 0 and 5 * * _.random(5, true); * // => a floating-point number between 0 and 5 * * _.random(1.2, 5.2); * // => a floating-point number between 1.2 and 5.2 */ function random(min, max, floating) { var noMin = min == null, noMax = max == null; if (floating == null) { if (typeof min == 'boolean' && noMax) { floating = min; min = 1; } else if (!noMax && typeof max == 'boolean') { floating = max; noMax = true; } } if (noMin && noMax) { max = 1; } min = +min || 0; if (noMax) { max = min; min = 0; } else { max = +max || 0; } var rand = nativeRandom(); return (floating || min % 1 || max % 1) ? nativeMin(min + (rand * (max - min + parseFloat('1e-' + ((rand +'').length - 1)))), max) : min + floor(rand * (max - min + 1)); } /** * Resolves the value of `property` on `object`. If `property` is a function * it will be invoked with the `this` binding of `object` and its result returned, * else the property value is returned. If `object` is falsey then `undefined` * is returned. * * @static * @memberOf _ * @category Utilities * @param {Object} object The object to inspect. * @param {string} property The property to get the value of. * @returns {*} Returns the resolved value. * @example * * var object = { * 'cheese': 'crumpets', * 'stuff': function() { * return 'nonsense'; * } * }; * * _.result(object, 'cheese'); * // => 'crumpets' * * _.result(object, 'stuff'); * // => 'nonsense' */ function result(object, property) { if (object) { var value = object[property]; return isFunction(value) ? object[property]() : value; } } /** * A micro-templating method that handles arbitrary delimiters, preserves * whitespace, and correctly escapes quotes within interpolated code. * * Note: In the development build, `_.template` utilizes sourceURLs for easier * debugging. See http://www.html5rocks.com/en/tutorials/developertools/sourcemaps/#toc-sourceurl * * For more information on precompiling templates see: * http://lodash.com/#custom-builds * * For more information on Chrome extension sandboxes see: * http://developer.chrome.com/stable/extensions/sandboxingEval.html * * @static * @memberOf _ * @category Utilities * @param {string} text The template text. * @param {Object} data The data object used to populate the text. * @param {Object} [options] The options object. * @param {RegExp} [options.escape] The "escape" delimiter. * @param {RegExp} [options.evaluate] The "evaluate" delimiter. * @param {Object} [options.imports] An object to import into the template as local variables. * @param {RegExp} [options.interpolate] The "interpolate" delimiter. * @param {string} [sourceURL] The sourceURL of the template's compiled source. * @param {string} [variable] The data object variable name. * @returns {Function|string} Returns a compiled function when no `data` object * is given, else it returns the interpolated text. * @example * * // using the "interpolate" delimiter to create a compiled template * var compiled = _.template('hello <%= name %>'); * compiled({ 'name': 'moe' }); * // => 'hello moe' * * // using the "escape" delimiter to escape HTML in data property values * _.template('<b><%- value %></b>', { 'value': '<script>' }); * // => '<b>&lt;script&gt;</b>' * * // using the "evaluate" delimiter to generate HTML * var list = '<% _.forEach(people, function(name) { %><li><%- name %></li><% }); %>'; * _.template(list, { 'people': ['moe', 'larry'] }); * // => '<li>moe</li><li>larry</li>' * * // using the ES6 delimiter as an alternative to the default "interpolate" delimiter * _.template('hello ${ name }', { 'name': 'curly' }); * // => 'hello curly' * * // using the internal `print` function in "evaluate" delimiters * _.template('<% print("hello " + name); %>!', { 'name': 'larry' }); * // => 'hello larry!' * * // using a custom template delimiters * _.templateSettings = { * 'interpolate': /{{([\s\S]+?)}}/g * }; * * _.template('hello {{ name }}!', { 'name': 'mustache' }); * // => 'hello mustache!' * * // using the `imports` option to import jQuery * var list = '<% $.each(people, function(name) { %><li><%- name %></li><% }); %>'; * _.template(list, { 'people': ['moe', 'larry'] }, { 'imports': { '$': jQuery } }); * // => '<li>moe</li><li>larry</li>' * * // using the `sourceURL` option to specify a custom sourceURL for the template * var compiled = _.template('hello <%= name %>', null, { 'sourceURL': '/basic/greeting.jst' }); * compiled(data); * // => find the source of "greeting.jst" under the Sources tab or Resources panel of the web inspector * * // using the `variable` option to ensure a with-statement isn't used in the compiled template * var compiled = _.template('hi <%= data.name %>!', null, { 'variable': 'data' }); * compiled.source; * // => function(data) { * var __t, __p = '', __e = _.escape; * __p += 'hi ' + ((__t = ( data.name )) == null ? '' : __t) + '!'; * return __p; * } * * // using the `source` property to inline compiled templates for meaningful * // line numbers in error messages and a stack trace * fs.writeFileSync(path.join(cwd, 'jst.js'), '\ * var JST = {\ * "main": ' + _.template(mainText).source + '\ * };\ * '); */ function template(text, data, options) { // based on John Resig's `tmpl` implementation // http://ejohn.org/blog/javascript-micro-templating/ // and Laura Doktorova's doT.js // https://github.com/olado/doT var settings = lodash.templateSettings; text || (text = ''); // avoid missing dependencies when `iteratorTemplate` is not defined options = defaults({}, options, settings); var imports = defaults({}, options.imports, settings.imports), importsKeys = keys(imports), importsValues = values(imports); var isEvaluating, index = 0, interpolate = options.interpolate || reNoMatch, source = "__p += '"; // compile the regexp to match each delimiter var reDelimiters = RegExp( (options.escape || reNoMatch).source + '|' + interpolate.source + '|' + (interpolate === reInterpolate ? reEsTemplate : reNoMatch).source + '|' + (options.evaluate || reNoMatch).source + '|$' , 'g'); text.replace(reDelimiters, function(match, escapeValue, interpolateValue, esTemplateValue, evaluateValue, offset) { interpolateValue || (interpolateValue = esTemplateValue); // escape characters that cannot be included in string literals source += text.slice(index, offset).replace(reUnescapedString, escapeStringChar); // replace delimiters with snippets if (escapeValue) { source += "' +\n__e(" + escapeValue + ") +\n'"; } if (evaluateValue) { isEvaluating = true; source += "';\n" + evaluateValue + ";\n__p += '"; } if (interpolateValue) { source += "' +\n((__t = (" + interpolateValue + ")) == null ? '' : __t) +\n'"; } index = offset + match.length; // the JS engine embedded in Adobe products requires returning the `match` // string in order to produce the correct `offset` value return match; }); source += "';\n"; // if `variable` is not specified, wrap a with-statement around the generated // code to add the data object to the top of the scope chain var variable = options.variable, hasVariable = variable; if (!hasVariable) { variable = 'obj'; source = 'with (' + variable + ') {\n' + source + '\n}\n'; } // cleanup code by stripping empty strings source = (isEvaluating ? source.replace(reEmptyStringLeading, '') : source) .replace(reEmptyStringMiddle, '$1') .replace(reEmptyStringTrailing, '$1;'); // frame code as the function body source = 'function(' + variable + ') {\n' + (hasVariable ? '' : variable + ' || (' + variable + ' = {});\n') + "var __t, __p = '', __e = _.escape" + (isEvaluating ? ', __j = Array.prototype.join;\n' + "function print() { __p += __j.call(arguments, '') }\n" : ';\n' ) + source + 'return __p\n}'; // Use a sourceURL for easier debugging. // http://www.html5rocks.com/en/tutorials/developertools/sourcemaps/#toc-sourceurl var sourceURL = '\n/*\n//# sourceURL=' + (options.sourceURL || '/lodash/template/source[' + (templateCounter++) + ']') + '\n*/'; try { var result = Function(importsKeys, 'return ' + source + sourceURL).apply(undefined, importsValues); } catch(e) { e.source = source; throw e; } if (data) { return result(data); } // provide the compiled function's source by its `toString` method, in // supported environments, or the `source` property as a convenience for // inlining compiled templates during the build process result.source = source; return result; } /** * Executes the callback `n` times, returning an array of the results * of each callback execution. The callback is bound to `thisArg` and invoked * with one argument; (index). * * @static * @memberOf _ * @category Utilities * @param {number} n The number of times to execute the callback. * @param {Function} callback The function called per iteration. * @param {*} [thisArg] The `this` binding of `callback`. * @returns {Array} Returns an array of the results of each `callback` execution. * @example * * var diceRolls = _.times(3, _.partial(_.random, 1, 6)); * // => [3, 6, 4] * * _.times(3, function(n) { mage.castSpell(n); }); * // => calls `mage.castSpell(n)` three times, passing `n` of `0`, `1`, and `2` respectively * * _.times(3, function(n) { this.cast(n); }, mage); * // => also calls `mage.castSpell(n)` three times */ function times(n, callback, thisArg) { n = (n = +n) > -1 ? n : 0; var index = -1, result = Array(n); callback = baseCreateCallback(callback, thisArg, 1); while (++index < n) { result[index] = callback(index); } return result; } /** * The inverse of `_.escape` this method converts the HTML entities * `&amp;`, `&lt;`, `&gt;`, `&quot;`, and `&#39;` in `string` to their * corresponding characters. * * @static * @memberOf _ * @category Utilities * @param {string} string The string to unescape. * @returns {string} Returns the unescaped string. * @example * * _.unescape('Moe, Larry &amp; Curly'); * // => 'Moe, Larry & Curly' */ function unescape(string) { return string == null ? '' : String(string).replace(reEscapedHtml, unescapeHtmlChar); } /** * Generates a unique ID. If `prefix` is provided the ID will be appended to it. * * @static * @memberOf _ * @category Utilities * @param {string} [prefix] The value to prefix the ID with. * @returns {string} Returns the unique ID. * @example * * _.uniqueId('contact_'); * // => 'contact_104' * * _.uniqueId(); * // => '105' */ function uniqueId(prefix) { var id = ++idCounter; return String(prefix == null ? '' : prefix) + id; } /*--------------------------------------------------------------------------*/ /** * Creates a `lodash` object that wraps the given value with explicit * method chaining enabled. * * @static * @memberOf _ * @category Chaining * @param {*} value The value to wrap. * @returns {Object} Returns the wrapper object. * @example * * var stooges = [ * { 'name': 'moe', 'age': 40 }, * { 'name': 'larry', 'age': 50 }, * { 'name': 'curly', 'age': 60 } * ]; * * var youngest = _.chain(stooges) * .sortBy('age') * .map(function(stooge) { return stooge.name + ' is ' + stooge.age; }) * .first() * .value(); * // => 'moe is 40' */ function chain(value) { value = new lodashWrapper(value); value.__chain__ = true; return value; } /** * Invokes `interceptor` with the `value` as the first argument and then * returns `value`. The purpose of this method is to "tap into" a method * chain in order to perform operations on intermediate results within * the chain. * * @static * @memberOf _ * @category Chaining * @param {*} value The value to provide to `interceptor`. * @param {Function} interceptor The function to invoke. * @returns {*} Returns `value`. * @example * * _([1, 2, 3, 4]) * .filter(function(num) { return num % 2 == 0; }) * .tap(function(array) { console.log(array); }) * .map(function(num) { return num * num; }) * .value(); * // => // [2, 4] (logged) * // => [4, 16] */ function tap(value, interceptor) { interceptor(value); return value; } /** * Enables explicit method chaining on the wrapper object. * * @name chain * @memberOf _ * @category Chaining * @returns {*} Returns the wrapper object. * @example * * var stooges = [ * { 'name': 'moe', 'age': 40 }, * { 'name': 'larry', 'age': 50 } * ]; * * // without explicit chaining * _(stooges).first(); * // => { 'name': 'moe', 'age': 40 } * * // with explicit chaining * _(stooges).chain() * .first() * .pick('age') * .value() * // => { 'age': 40 } */ function wrapperChain() { this.__chain__ = true; return this; } /** * Produces the `toString` result of the wrapped value. * * @name toString * @memberOf _ * @category Chaining * @returns {string} Returns the string result. * @example * * _([1, 2, 3]).toString(); * // => '1,2,3' */ function wrapperToString() { return String(this.__wrapped__); } /** * Extracts the wrapped value. * * @name valueOf * @memberOf _ * @alias value * @category Chaining * @returns {*} Returns the wrapped value. * @example * * _([1, 2, 3]).valueOf(); * // => [1, 2, 3] */ function wrapperValueOf() { return this.__wrapped__; } /*--------------------------------------------------------------------------*/ // add functions that return wrapped values when chaining lodash.after = after; lodash.assign = assign; lodash.at = at; lodash.bind = bind; lodash.bindAll = bindAll; lodash.bindKey = bindKey; lodash.chain = chain; lodash.compact = compact; lodash.compose = compose; lodash.countBy = countBy; lodash.createCallback = createCallback; lodash.curry = curry; lodash.debounce = debounce; lodash.defaults = defaults; lodash.defer = defer; lodash.delay = delay; lodash.difference = difference; lodash.filter = filter; lodash.flatten = flatten; lodash.forEach = forEach; lodash.forEachRight = forEachRight; lodash.forIn = forIn; lodash.forInRight = forInRight; lodash.forOwn = forOwn; lodash.forOwnRight = forOwnRight; lodash.functions = functions; lodash.groupBy = groupBy; lodash.indexBy = indexBy; lodash.initial = initial; lodash.intersection = intersection; lodash.invert = invert; lodash.invoke = invoke; lodash.keys = keys; lodash.map = map; lodash.max = max; lodash.memoize = memoize; lodash.merge = merge; lodash.min = min; lodash.omit = omit; lodash.once = once; lodash.pairs = pairs; lodash.partial = partial; lodash.partialRight = partialRight; lodash.pick = pick; lodash.pluck = pluck; lodash.pull = pull; lodash.range = range; lodash.reject = reject; lodash.remove = remove; lodash.rest = rest; lodash.shuffle = shuffle; lodash.sortBy = sortBy; lodash.tap = tap; lodash.throttle = throttle; lodash.times = times; lodash.toArray = toArray; lodash.transform = transform; lodash.union = union; lodash.uniq = uniq; lodash.values = values; lodash.where = where; lodash.without = without; lodash.wrap = wrap; lodash.zip = zip; lodash.zipObject = zipObject; // add aliases lodash.collect = map; lodash.drop = rest; lodash.each = forEach; lodash.eachRight = forEachRight; lodash.extend = assign; lodash.methods = functions; lodash.object = zipObject; lodash.select = filter; lodash.tail = rest; lodash.unique = uniq; lodash.unzip = zip; // add functions to `lodash.prototype` mixin(lodash); /*--------------------------------------------------------------------------*/ // add functions that return unwrapped values when chaining lodash.clone = clone; lodash.cloneDeep = cloneDeep; lodash.contains = contains; lodash.escape = escape; lodash.every = every; lodash.find = find; lodash.findIndex = findIndex; lodash.findKey = findKey; lodash.findLast = findLast; lodash.findLastIndex = findLastIndex; lodash.findLastKey = findLastKey; lodash.has = has; lodash.identity = identity; lodash.indexOf = indexOf; lodash.isArguments = isArguments; lodash.isArray = isArray; lodash.isBoolean = isBoolean; lodash.isDate = isDate; lodash.isElement = isElement; lodash.isEmpty = isEmpty; lodash.isEqual = isEqual; lodash.isFinite = isFinite; lodash.isFunction = isFunction; lodash.isNaN = isNaN; lodash.isNull = isNull; lodash.isNumber = isNumber; lodash.isObject = isObject; lodash.isPlainObject = isPlainObject; lodash.isRegExp = isRegExp; lodash.isString = isString; lodash.isUndefined = isUndefined; lodash.lastIndexOf = lastIndexOf; lodash.mixin = mixin; lodash.noConflict = noConflict; lodash.parseInt = parseInt; lodash.random = random; lodash.reduce = reduce; lodash.reduceRight = reduceRight; lodash.result = result; lodash.runInContext = runInContext; lodash.size = size; lodash.some = some; lodash.sortedIndex = sortedIndex; lodash.template = template; lodash.unescape = unescape; lodash.uniqueId = uniqueId; // add aliases lodash.all = every; lodash.any = some; lodash.detect = find; lodash.findWhere = find; lodash.foldl = reduce; lodash.foldr = reduceRight; lodash.include = contains; lodash.inject = reduce; forOwn(lodash, function(func, methodName) { if (!lodash.prototype[methodName]) { lodash.prototype[methodName] = function() { var args = [this.__wrapped__], chainAll = this.__chain__; push.apply(args, arguments); var result = func.apply(lodash, args); return chainAll ? new lodashWrapper(result, chainAll) : result; }; } }); /*--------------------------------------------------------------------------*/ // add functions capable of returning wrapped and unwrapped values when chaining lodash.first = first; lodash.last = last; lodash.sample = sample; // add aliases lodash.take = first; lodash.head = first; forOwn(lodash, function(func, methodName) { var callbackable = methodName !== 'sample'; if (!lodash.prototype[methodName]) { lodash.prototype[methodName]= function(n, guard) { var chainAll = this.__chain__, result = func(this.__wrapped__, n, guard); return !chainAll && (n == null || (guard && !(callbackable && typeof n == 'function'))) ? result : new lodashWrapper(result, chainAll); }; } }); /*--------------------------------------------------------------------------*/ /** * The semantic version number. * * @static * @memberOf _ * @type string */ lodash.VERSION = '2.2.1'; // add "Chaining" functions to the wrapper lodash.prototype.chain = wrapperChain; lodash.prototype.toString = wrapperToString; lodash.prototype.value = wrapperValueOf; lodash.prototype.valueOf = wrapperValueOf; // add `Array` functions that return unwrapped values forEach(['join', 'pop', 'shift'], function(methodName) { var func = arrayRef[methodName]; lodash.prototype[methodName] = function() { var chainAll = this.__chain__, result = func.apply(this.__wrapped__, arguments); return chainAll ? new lodashWrapper(result, chainAll) : result; }; }); // add `Array` functions that return the wrapped value forEach(['push', 'reverse', 'sort', 'unshift'], function(methodName) { var func = arrayRef[methodName]; lodash.prototype[methodName] = function() { func.apply(this.__wrapped__, arguments); return this; }; }); // add `Array` functions that return new wrapped values forEach(['concat', 'slice', 'splice'], function(methodName) { var func = arrayRef[methodName]; lodash.prototype[methodName] = function() { return new lodashWrapper(func.apply(this.__wrapped__, arguments), this.__chain__); }; }); return lodash; } /*--------------------------------------------------------------------------*/ // expose Lo-Dash var _ = runInContext(); // some AMD build optimizers, like r.js, check for condition patterns like the following: if (typeof define == 'function' && typeof define.amd == 'object' && define.amd) { // Expose Lo-Dash to the global object even when an AMD loader is present in // case Lo-Dash was injected by a third-party script and not intended to be // loaded as a module. The global assignment can be reverted in the Lo-Dash // module by its `noConflict()` method. root._ = _; // define as an anonymous module so, through path mapping, it can be // referenced as the "underscore" module define(function() { return _; }); } // check for `exports` after `define` in case a build optimizer adds an `exports` object else if (freeExports && freeModule) { // in Node.js or RingoJS if (moduleExports) { (freeModule.exports = _)._ = _; } // in Narwhal or Rhino -require else { freeExports._ = _; } } else { // in a browser or Rhino root._ = _; } }.call(this)); // Backbone.js 1.1.2 // (c) 2010-2014 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors // Backbone may be freely distributed under the MIT license. // For all details and documentation: // http://backbonejs.org (function(root, factory) { // Set up Backbone appropriately for the environment. Start with AMD. if (typeof define === 'function' && define.amd) { define(['underscore', 'jquery', 'exports'], function(_, $, exports) { // Export global even in AMD case in case this script is loaded with // others that may still expect a global Backbone. root.Backbone = factory(root, exports, _, $); }); // Next for Node.js or CommonJS. jQuery may not be needed as a module. } else if (typeof exports !== 'undefined') { var _ = require('underscore'); factory(root, exports, _); // Finally, as a browser global. } else { root.Backbone = factory(root, {}, root._, (root.jQuery || root.Zepto || root.ender || root.$)); } }(this, function(root, Backbone, _, $) { // Initial Setup // ------------- // Save the previous value of the `Backbone` variable, so that it can be // restored later on, if `noConflict` is used. var previousBackbone = root.Backbone; // Create local references to array methods we'll want to use later. var array = []; var push = array.push; var slice = array.slice; var splice = array.splice; // Current version of the library. Keep in sync with `package.json`. Backbone.VERSION = '1.1.2'; // For Backbone's purposes, jQuery, Zepto, Ender, or My Library (kidding) owns // the `$` variable. Backbone.$ = $; // Runs Backbone.js in *noConflict* mode, returning the `Backbone` variable // to its previous owner. Returns a reference to this Backbone object. Backbone.noConflict = function() { root.Backbone = previousBackbone; return this; }; // Turn on `emulateHTTP` to support legacy HTTP servers. Setting this option // will fake `"PATCH"`, `"PUT"` and `"DELETE"` requests via the `_method` parameter and // set a `X-Http-Method-Override` header. Backbone.emulateHTTP = false; // Turn on `emulateJSON` to support legacy servers that can't deal with direct // `application/json` requests ... will encode the body as // `application/x-www-form-urlencoded` instead and will send the model in a // form param named `model`. Backbone.emulateJSON = false; // Backbone.Events // --------------- // A module that can be mixed in to *any object* in order to provide it with // custom events. You may bind with `on` or remove with `off` callback // functions to an event; `trigger`-ing an event fires all callbacks in // succession. // // var object = {}; // _.extend(object, Backbone.Events); // object.on('expand', function(){ alert('expanded'); }); // object.trigger('expand'); // var Events = Backbone.Events = { // Bind an event to a `callback` function. Passing `"all"` will bind // the callback to all events fired. on: function(name, callback, context) { if (!eventsApi(this, 'on', name, [callback, context]) || !callback) return this; this._events || (this._events = {}); var events = this._events[name] || (this._events[name] = []); events.push({callback: callback, context: context, ctx: context || this}); return this; }, // Bind an event to only be triggered a single time. After the first time // the callback is invoked, it will be removed. once: function(name, callback, context) { if (!eventsApi(this, 'once', name, [callback, context]) || !callback) return this; var self = this; var once = _.once(function() { self.off(name, once); callback.apply(this, arguments); }); once._callback = callback; return this.on(name, once, context); }, // Remove one or many callbacks. If `context` is null, removes all // callbacks with that function. If `callback` is null, removes all // callbacks for the event. If `name` is null, removes all bound // callbacks for all events. off: function(name, callback, context) { var retain, ev, events, names, i, l, j, k; if (!this._events || !eventsApi(this, 'off', name, [callback, context])) return this; if (!name && !callback && !context) { this._events = void 0; return this; } names = name ? [name] : _.keys(this._events); for (i = 0, l = names.length; i < l; i++) { name = names[i]; if (events = this._events[name]) { this._events[name] = retain = []; if (callback || context) { for (j = 0, k = events.length; j < k; j++) { ev = events[j]; if ((callback && callback !== ev.callback && callback !== ev.callback._callback) || (context && context !== ev.context)) { retain.push(ev); } } } if (!retain.length) delete this._events[name]; } } return this; }, // Trigger one or many events, firing all bound callbacks. Callbacks are // passed the same arguments as `trigger` is, apart from the event name // (unless you're listening on `"all"`, which will cause your callback to // receive the true name of the event as the first argument). trigger: function(name) { if (!this._events) return this; var args = slice.call(arguments, 1); if (!eventsApi(this, 'trigger', name, args)) return this; var events = this._events[name]; var allEvents = this._events.all; if (events) triggerEvents(events, args); if (allEvents) triggerEvents(allEvents, arguments); return this; }, // Tell this object to stop listening to either specific events ... or // to every object it's currently listening to. stopListening: function(obj, name, callback) { var listeningTo = this._listeningTo; if (!listeningTo) return this; var remove = !name && !callback; if (!callback && typeof name === 'object') callback = this; if (obj) (listeningTo = {})[obj._listenId] = obj; for (var id in listeningTo) { obj = listeningTo[id]; obj.off(name, callback, this); if (remove || _.isEmpty(obj._events)) delete this._listeningTo[id]; } return this; } }; // Regular expression used to split event strings. var eventSplitter = /\s+/; // Implement fancy features of the Events API such as multiple event // names `"change blur"` and jQuery-style event maps `{change: action}` // in terms of the existing API. var eventsApi = function(obj, action, name, rest) { if (!name) return true; // Handle event maps. if (typeof name === 'object') { for (var key in name) { obj[action].apply(obj, [key, name[key]].concat(rest)); } return false; } // Handle space separated event names. if (eventSplitter.test(name)) { var names = name.split(eventSplitter); for (var i = 0, l = names.length; i < l; i++) { obj[action].apply(obj, [names[i]].concat(rest)); } return false; } return true; }; // A difficult-to-believe, but optimized internal dispatch function for // triggering events. Tries to keep the usual cases speedy (most internal // Backbone events have 3 arguments). var triggerEvents = function(events, args) { var ev, i = -1, l = events.length, a1 = args[0], a2 = args[1], a3 = args[2]; switch (args.length) { case 0: while (++i < l) (ev = events[i]).callback.call(ev.ctx); return; case 1: while (++i < l) (ev = events[i]).callback.call(ev.ctx, a1); return; case 2: while (++i < l) (ev = events[i]).callback.call(ev.ctx, a1, a2); return; case 3: while (++i < l) (ev = events[i]).callback.call(ev.ctx, a1, a2, a3); return; default: while (++i < l) (ev = events[i]).callback.apply(ev.ctx, args); return; } }; var listenMethods = {listenTo: 'on', listenToOnce: 'once'}; // Inversion-of-control versions of `on` and `once`. Tell *this* object to // listen to an event in another object ... keeping track of what it's // listening to. _.each(listenMethods, function(implementation, method) { Events[method] = function(obj, name, callback) { var listeningTo = this._listeningTo || (this._listeningTo = {}); var id = obj._listenId || (obj._listenId = _.uniqueId('l')); listeningTo[id] = obj; if (!callback && typeof name === 'object') callback = this; obj[implementation](name, callback, this); return this; }; }); // Aliases for backwards compatibility. Events.bind = Events.on; Events.unbind = Events.off; // Allow the `Backbone` object to serve as a global event bus, for folks who // want global "pubsub" in a convenient place. _.extend(Backbone, Events); // Backbone.Model // -------------- // Backbone **Models** are the basic data object in the framework -- // frequently representing a row in a table in a database on your server. // A discrete chunk of data and a bunch of useful, related methods for // performing computations and transformations on that data. // Create a new model with the specified attributes. A client id (`cid`) // is automatically generated and assigned for you. var Model = Backbone.Model = function(attributes, options) { var attrs = attributes || {}; options || (options = {}); this.cid = _.uniqueId('c'); this.attributes = {}; if (options.collection) this.collection = options.collection; if (options.parse) attrs = this.parse(attrs, options) || {}; attrs = _.defaults({}, attrs, _.result(this, 'defaults')); this.set(attrs, options); this.changed = {}; this.initialize.apply(this, arguments); }; // Attach all inheritable methods to the Model prototype. _.extend(Model.prototype, Events, { // A hash of attributes whose current and previous value differ. changed: null, // The value returned during the last failed validation. validationError: null, // The default name for the JSON `id` attribute is `"id"`. MongoDB and // CouchDB users may want to set this to `"_id"`. idAttribute: 'id', // Initialize is an empty function by default. Override it with your own // initialization logic. initialize: function(){}, // Return a copy of the model's `attributes` object. toJSON: function(options) { return _.clone(this.attributes); }, // Proxy `Backbone.sync` by default -- but override this if you need // custom syncing semantics for *this* particular model. sync: function() { return Backbone.sync.apply(this, arguments); }, // Get the value of an attribute. get: function(attr) { return this.attributes[attr]; }, // Get the HTML-escaped value of an attribute. escape: function(attr) { return _.escape(this.get(attr)); }, // Returns `true` if the attribute contains a value that is not null // or undefined. has: function(attr) { return this.get(attr) != null; }, // Set a hash of model attributes on the object, firing `"change"`. This is // the core primitive operation of a model, updating the data and notifying // anyone who needs to know about the change in state. The heart of the beast. set: function(key, val, options) { var attr, attrs, unset, changes, silent, changing, prev, current; if (key == null) return this; // Handle both `"key", value` and `{key: value}` -style arguments. if (typeof key === 'object') { attrs = key; options = val; } else { (attrs = {})[key] = val; } options || (options = {}); // Run validation. if (!this._validate(attrs, options)) return false; // Extract attributes and options. unset = options.unset; silent = options.silent; changes = []; changing = this._changing; this._changing = true; if (!changing) { this._previousAttributes = _.clone(this.attributes); this.changed = {}; } current = this.attributes, prev = this._previousAttributes; // Check for changes of `id`. if (this.idAttribute in attrs) this.id = attrs[this.idAttribute]; // For each `set` attribute, update or delete the current value. for (attr in attrs) { val = attrs[attr]; if (!_.isEqual(current[attr], val)) changes.push(attr); if (!_.isEqual(prev[attr], val)) { this.changed[attr] = val; } else { delete this.changed[attr]; } unset ? delete current[attr] : current[attr] = val; } // Trigger all relevant attribute changes. if (!silent) { if (changes.length) this._pending = options; for (var i = 0, l = changes.length; i < l; i++) { this.trigger('change:' + changes[i], this, current[changes[i]], options); } } // You might be wondering why there's a `while` loop here. Changes can // be recursively nested within `"change"` events. if (changing) return this; if (!silent) { while (this._pending) { options = this._pending; this._pending = false; this.trigger('change', this, options); } } this._pending = false; this._changing = false; return this; }, // Remove an attribute from the model, firing `"change"`. `unset` is a noop // if the attribute doesn't exist. unset: function(attr, options) { return this.set(attr, void 0, _.extend({}, options, {unset: true})); }, // Clear all attributes on the model, firing `"change"`. clear: function(options) { var attrs = {}; for (var key in this.attributes) attrs[key] = void 0; return this.set(attrs, _.extend({}, options, {unset: true})); }, // Determine if the model has changed since the last `"change"` event. // If you specify an attribute name, determine if that attribute has changed. hasChanged: function(attr) { if (attr == null) return !_.isEmpty(this.changed); return _.has(this.changed, attr); }, // Return an object containing all the attributes that have changed, or // false if there are no changed attributes. Useful for determining what // parts of a view need to be updated and/or what attributes need to be // persisted to the server. Unset attributes will be set to undefined. // You can also pass an attributes object to diff against the model, // determining if there *would be* a change. changedAttributes: function(diff) { if (!diff) return this.hasChanged() ? _.clone(this.changed) : false; var val, changed = false; var old = this._changing ? this._previousAttributes : this.attributes; for (var attr in diff) { if (_.isEqual(old[attr], (val = diff[attr]))) continue; (changed || (changed = {}))[attr] = val; } return changed; }, // Get the previous value of an attribute, recorded at the time the last // `"change"` event was fired. previous: function(attr) { if (attr == null || !this._previousAttributes) return null; return this._previousAttributes[attr]; }, // Get all of the attributes of the model at the time of the previous // `"change"` event. previousAttributes: function() { return _.clone(this._previousAttributes); }, // Fetch the model from the server. If the server's representation of the // model differs from its current attributes, they will be overridden, // triggering a `"change"` event. fetch: function(options) { options = options ? _.clone(options) : {}; if (options.parse === void 0) options.parse = true; var model = this; var success = options.success; options.success = function(resp) { if (!model.set(model.parse(resp, options), options)) return false; if (success) success(model, resp, options); model.trigger('sync', model, resp, options); }; wrapError(this, options); return this.sync('read', this, options); }, // Set a hash of model attributes, and sync the model to the server. // If the server returns an attributes hash that differs, the model's // state will be `set` again. save: function(key, val, options) { var attrs, method, xhr, attributes = this.attributes; // Handle both `"key", value` and `{key: value}` -style arguments. if (key == null || typeof key === 'object') { attrs = key; options = val; } else { (attrs = {})[key] = val; } options = _.extend({validate: true}, options); // If we're not waiting and attributes exist, save acts as // `set(attr).save(null, opts)` with validation. Otherwise, check if // the model will be valid when the attributes, if any, are set. if (attrs && !options.wait) { if (!this.set(attrs, options)) return false; } else { if (!this._validate(attrs, options)) return false; } // Set temporary attributes if `{wait: true}`. if (attrs && options.wait) { this.attributes = _.extend({}, attributes, attrs); } // After a successful server-side save, the client is (optionally) // updated with the server-side state. if (options.parse === void 0) options.parse = true; var model = this; var success = options.success; options.success = function(resp) { // Ensure attributes are restored during synchronous saves. model.attributes = attributes; var serverAttrs = model.parse(resp, options); if (options.wait) serverAttrs = _.extend(attrs || {}, serverAttrs); if (_.isObject(serverAttrs) && !model.set(serverAttrs, options)) { return false; } if (success) success(model, resp, options); model.trigger('sync', model, resp, options); }; wrapError(this, options); method = this.isNew() ? 'create' : (options.patch ? 'patch' : 'update'); if (method === 'patch') options.attrs = attrs; xhr = this.sync(method, this, options); // Restore attributes. if (attrs && options.wait) this.attributes = attributes; return xhr; }, // Destroy this model on the server if it was already persisted. // Optimistically removes the model from its collection, if it has one. // If `wait: true` is passed, waits for the server to respond before removal. destroy: function(options) { options = options ? _.clone(options) : {}; var model = this; var success = options.success; var destroy = function() { model.trigger('destroy', model, model.collection, options); }; options.success = function(resp) { if (options.wait || model.isNew()) destroy(); if (success) success(model, resp, options); if (!model.isNew()) model.trigger('sync', model, resp, options); }; if (this.isNew()) { options.success(); return false; } wrapError(this, options); var xhr = this.sync('delete', this, options); if (!options.wait) destroy(); return xhr; }, // Default URL for the model's representation on the server -- if you're // using Backbone's restful methods, override this to change the endpoint // that will be called. url: function() { var base = _.result(this, 'urlRoot') || _.result(this.collection, 'url') || urlError(); if (this.isNew()) return base; return base.replace(/([^\/])$/, '$1/') + encodeURIComponent(this.id); }, // **parse** converts a response into the hash of attributes to be `set` on // the model. The default implementation is just to pass the response along. parse: function(resp, options) { return resp; }, // Create a new model with identical attributes to this one. clone: function() { return new this.constructor(this.attributes); }, // A model is new if it has never been saved to the server, and lacks an id. isNew: function() { return !this.has(this.idAttribute); }, // Check if the model is currently in a valid state. isValid: function(options) { return this._validate({}, _.extend(options || {}, { validate: true })); }, // Run validation against the next complete set of model attributes, // returning `true` if all is well. Otherwise, fire an `"invalid"` event. _validate: function(attrs, options) { if (!options.validate || !this.validate) return true; attrs = _.extend({}, this.attributes, attrs); var error = this.validationError = this.validate(attrs, options) || null; if (!error) return true; this.trigger('invalid', this, error, _.extend(options, {validationError: error})); return false; } }); // Underscore methods that we want to implement on the Model. var modelMethods = ['keys', 'values', 'pairs', 'invert', 'pick', 'omit']; // Mix in each Underscore method as a proxy to `Model#attributes`. _.each(modelMethods, function(method) { Model.prototype[method] = function() { var args = slice.call(arguments); args.unshift(this.attributes); return _[method].apply(_, args); }; }); // Backbone.Collection // ------------------- // If models tend to represent a single row of data, a Backbone Collection is // more analagous to a table full of data ... or a small slice or page of that // table, or a collection of rows that belong together for a particular reason // -- all of the messages in this particular folder, all of the documents // belonging to this particular author, and so on. Collections maintain // indexes of their models, both in order, and for lookup by `id`. // Create a new **Collection**, perhaps to contain a specific type of `model`. // If a `comparator` is specified, the Collection will maintain // its models in sort order, as they're added and removed. var Collection = Backbone.Collection = function(models, options) { options || (options = {}); if (options.model) this.model = options.model; if (options.comparator !== void 0) this.comparator = options.comparator; this._reset(); this.initialize.apply(this, arguments); if (models) this.reset(models, _.extend({silent: true}, options)); }; // Default options for `Collection#set`. var setOptions = {add: true, remove: true, merge: true}; var addOptions = {add: true, remove: false}; // Define the Collection's inheritable methods. _.extend(Collection.prototype, Events, { // The default model for a collection is just a **Backbone.Model**. // This should be overridden in most cases. model: Model, // Initialize is an empty function by default. Override it with your own // initialization logic. initialize: function(){}, // The JSON representation of a Collection is an array of the // models' attributes. toJSON: function(options) { return this.map(function(model){ return model.toJSON(options); }); }, // Proxy `Backbone.sync` by default. sync: function() { return Backbone.sync.apply(this, arguments); }, // Add a model, or list of models to the set. add: function(models, options) { return this.set(models, _.extend({merge: false}, options, addOptions)); }, // Remove a model, or a list of models from the set. remove: function(models, options) { var singular = !_.isArray(models); models = singular ? [models] : _.clone(models); options || (options = {}); var i, l, index, model; for (i = 0, l = models.length; i < l; i++) { model = models[i] = this.get(models[i]); if (!model) continue; delete this._byId[model.id]; delete this._byId[model.cid]; index = this.indexOf(model); this.models.splice(index, 1); this.length--; if (!options.silent) { options.index = index; model.trigger('remove', model, this, options); } this._removeReference(model, options); } return singular ? models[0] : models; }, // Update a collection by `set`-ing a new list of models, adding new ones, // removing models that are no longer present, and merging models that // already exist in the collection, as necessary. Similar to **Model#set**, // the core operation for updating the data contained by the collection. set: function(models, options) { options = _.defaults({}, options, setOptions); if (options.parse) models = this.parse(models, options); var singular = !_.isArray(models); models = singular ? (models ? [models] : []) : _.clone(models); var i, l, id, model, attrs, existing, sort; var at = options.at; var targetModel = this.model; var sortable = this.comparator && (at == null) && options.sort !== false; var sortAttr = _.isString(this.comparator) ? this.comparator : null; var toAdd = [], toRemove = [], modelMap = {}; var add = options.add, merge = options.merge, remove = options.remove; var order = !sortable && add && remove ? [] : false; // Turn bare objects into model references, and prevent invalid models // from being added. for (i = 0, l = models.length; i < l; i++) { attrs = models[i] || {}; if (attrs instanceof Model) { id = model = attrs; } else { id = attrs[targetModel.prototype.idAttribute || 'id']; } // If a duplicate is found, prevent it from being added and // optionally merge it into the existing model. if (existing = this.get(id)) { if (remove) modelMap[existing.cid] = true; if (merge) { attrs = attrs === model ? model.attributes : attrs; if (options.parse) attrs = existing.parse(attrs, options); existing.set(attrs, options); if (sortable && !sort && existing.hasChanged(sortAttr)) sort = true; } models[i] = existing; // If this is a new, valid model, push it to the `toAdd` list. } else if (add) { model = models[i] = this._prepareModel(attrs, options); if (!model) continue; toAdd.push(model); this._addReference(model, options); } // Do not add multiple models with the same `id`. model = existing || model; if (order && (model.isNew() || !modelMap[model.id])) order.push(model); modelMap[model.id] = true; } // Remove nonexistent models if appropriate. if (remove) { for (i = 0, l = this.length; i < l; ++i) { if (!modelMap[(model = this.models[i]).cid]) toRemove.push(model); } if (toRemove.length) this.remove(toRemove, options); } // See if sorting is needed, update `length` and splice in new models. if (toAdd.length || (order && order.length)) { if (sortable) sort = true; this.length += toAdd.length; if (at != null) { for (i = 0, l = toAdd.length; i < l; i++) { this.models.splice(at + i, 0, toAdd[i]); } } else { if (order) this.models.length = 0; var orderedModels = order || toAdd; for (i = 0, l = orderedModels.length; i < l; i++) { this.models.push(orderedModels[i]); } } } // Silently sort the collection if appropriate. if (sort) this.sort({silent: true}); // Unless silenced, it's time to fire all appropriate add/sort events. if (!options.silent) { for (i = 0, l = toAdd.length; i < l; i++) { (model = toAdd[i]).trigger('add', model, this, options); } if (sort || (order && order.length)) this.trigger('sort', this, options); } // Return the added (or merged) model (or models). return singular ? models[0] : models; }, // When you have more items than you want to add or remove individually, // you can reset the entire set with a new list of models, without firing // any granular `add` or `remove` events. Fires `reset` when finished. // Useful for bulk operations and optimizations. reset: function(models, options) { options || (options = {}); for (var i = 0, l = this.models.length; i < l; i++) { this._removeReference(this.models[i], options); } options.previousModels = this.models; this._reset(); models = this.add(models, _.extend({silent: true}, options)); if (!options.silent) this.trigger('reset', this, options); return models; }, // Add a model to the end of the collection. push: function(model, options) { return this.add(model, _.extend({at: this.length}, options)); }, // Remove a model from the end of the collection. pop: function(options) { var model = this.at(this.length - 1); this.remove(model, options); return model; }, // Add a model to the beginning of the collection. unshift: function(model, options) { return this.add(model, _.extend({at: 0}, options)); }, // Remove a model from the beginning of the collection. shift: function(options) { var model = this.at(0); this.remove(model, options); return model; }, // Slice out a sub-array of models from the collection. slice: function() { return slice.apply(this.models, arguments); }, // Get a model from the set by id. get: function(obj) { if (obj == null) return void 0; return this._byId[obj] || this._byId[obj.id] || this._byId[obj.cid]; }, // Get the model at the given index. at: function(index) { return this.models[index]; }, // Return models with matching attributes. Useful for simple cases of // `filter`. where: function(attrs, first) { if (_.isEmpty(attrs)) return first ? void 0 : []; return this[first ? 'find' : 'filter'](function(model) { for (var key in attrs) { if (attrs[key] !== model.get(key)) return false; } return true; }); }, // Return the first model with matching attributes. Useful for simple cases // of `find`. findWhere: function(attrs) { return this.where(attrs, true); }, // Force the collection to re-sort itself. You don't need to call this under // normal circumstances, as the set will maintain sort order as each item // is added. sort: function(options) { if (!this.comparator) throw new Error('Cannot sort a set without a comparator'); options || (options = {}); // Run sort based on type of `comparator`. if (_.isString(this.comparator) || this.comparator.length === 1) { this.models = this.sortBy(this.comparator, this); } else { this.models.sort(_.bind(this.comparator, this)); } if (!options.silent) this.trigger('sort', this, options); return this; }, // Pluck an attribute from each model in the collection. pluck: function(attr) { return _.invoke(this.models, 'get', attr); }, // Fetch the default set of models for this collection, resetting the // collection when they arrive. If `reset: true` is passed, the response // data will be passed through the `reset` method instead of `set`. fetch: function(options) { options = options ? _.clone(options) : {}; if (options.parse === void 0) options.parse = true; var success = options.success; var collection = this; options.success = function(resp) { var method = options.reset ? 'reset' : 'set'; collection[method](resp, options); if (success) success(collection, resp, options); collection.trigger('sync', collection, resp, options); }; wrapError(this, options); return this.sync('read', this, options); }, // Create a new instance of a model in this collection. Add the model to the // collection immediately, unless `wait: true` is passed, in which case we // wait for the server to agree. create: function(model, options) { options = options ? _.clone(options) : {}; if (!(model = this._prepareModel(model, options))) return false; if (!options.wait) this.add(model, options); var collection = this; var success = options.success; options.success = function(model, resp) { if (options.wait) collection.add(model, options); if (success) success(model, resp, options); }; model.save(null, options); return model; }, // **parse** converts a response into a list of models to be added to the // collection. The default implementation is just to pass it through. parse: function(resp, options) { return resp; }, // Create a new collection with an identical list of models as this one. clone: function() { return new this.constructor(this.models); }, // Private method to reset all internal state. Called when the collection // is first initialized or reset. _reset: function() { this.length = 0; this.models = []; this._byId = {}; }, // Prepare a hash of attributes (or other model) to be added to this // collection. _prepareModel: function(attrs, options) { if (attrs instanceof Model) return attrs; options = options ? _.clone(options) : {}; options.collection = this; var model = new this.model(attrs, options); if (!model.validationError) return model; this.trigger('invalid', this, model.validationError, options); return false; }, // Internal method to create a model's ties to a collection. _addReference: function(model, options) { this._byId[model.cid] = model; if (model.id != null) this._byId[model.id] = model; if (!model.collection) model.collection = this; model.on('all', this._onModelEvent, this); }, // Internal method to sever a model's ties to a collection. _removeReference: function(model, options) { if (this === model.collection) delete model.collection; model.off('all', this._onModelEvent, this); }, // Internal method called every time a model in the set fires an event. // Sets need to update their indexes when models change ids. All other // events simply proxy through. "add" and "remove" events that originate // in other collections are ignored. _onModelEvent: function(event, model, collection, options) { if ((event === 'add' || event === 'remove') && collection !== this) return; if (event === 'destroy') this.remove(model, options); if (model && event === 'change:' + model.idAttribute) { delete this._byId[model.previous(model.idAttribute)]; if (model.id != null) this._byId[model.id] = model; } this.trigger.apply(this, arguments); } }); // Underscore methods that we want to implement on the Collection. // 90% of the core usefulness of Backbone Collections is actually implemented // right here: var methods = ['forEach', 'each', 'map', 'collect', 'reduce', 'foldl', 'inject', 'reduceRight', 'foldr', 'find', 'detect', 'filter', 'select', 'reject', 'every', 'all', 'some', 'any', 'include', 'contains', 'invoke', 'max', 'min', 'toArray', 'size', 'first', 'head', 'take', 'initial', 'rest', 'tail', 'drop', 'last', 'without', 'difference', 'indexOf', 'shuffle', 'lastIndexOf', 'isEmpty', 'chain', 'sample']; // Mix in each Underscore method as a proxy to `Collection#models`. _.each(methods, function(method) { Collection.prototype[method] = function() { var args = slice.call(arguments); args.unshift(this.models); return _[method].apply(_, args); }; }); // Underscore methods that take a property name as an argument. var attributeMethods = ['groupBy', 'countBy', 'sortBy', 'indexBy']; // Use attributes instead of properties. _.each(attributeMethods, function(method) { Collection.prototype[method] = function(value, context) { var iterator = _.isFunction(value) ? value : function(model) { return model.get(value); }; return _[method](this.models, iterator, context); }; }); // Backbone.View // ------------- // Backbone Views are almost more convention than they are actual code. A View // is simply a JavaScript object that represents a logical chunk of UI in the // DOM. This might be a single item, an entire list, a sidebar or panel, or // even the surrounding frame which wraps your whole app. Defining a chunk of // UI as a **View** allows you to define your DOM events declaratively, without // having to worry about render order ... and makes it easy for the view to // react to specific changes in the state of your models. // Creating a Backbone.View creates its initial element outside of the DOM, // if an existing element is not provided... var View = Backbone.View = function(options) { this.cid = _.uniqueId('view'); options || (options = {}); _.extend(this, _.pick(options, viewOptions)); this._ensureElement(); this.initialize.apply(this, arguments); this.delegateEvents(); }; // Cached regex to split keys for `delegate`. var delegateEventSplitter = /^(\S+)\s*(.*)$/; // List of view options to be merged as properties. var viewOptions = ['model', 'collection', 'el', 'id', 'attributes', 'className', 'tagName', 'events']; // Set up all inheritable **Backbone.View** properties and methods. _.extend(View.prototype, Events, { // The default `tagName` of a View's element is `"div"`. tagName: 'div', // jQuery delegate for element lookup, scoped to DOM elements within the // current view. This should be preferred to global lookups where possible. $: function(selector) { return this.$el.find(selector); }, // Initialize is an empty function by default. Override it with your own // initialization logic. initialize: function(){}, // **render** is the core function that your view should override, in order // to populate its element (`this.el`), with the appropriate HTML. The // convention is for **render** to always return `this`. render: function() { return this; }, // Remove this view by taking the element out of the DOM, and removing any // applicable Backbone.Events listeners. remove: function() { this.$el.remove(); this.stopListening(); return this; }, // Change the view's element (`this.el` property), including event // re-delegation. setElement: function(element, delegate) { if (this.$el) this.undelegateEvents(); this.$el = element instanceof Backbone.$ ? element : Backbone.$(element); this.el = this.$el[0]; if (delegate !== false) this.delegateEvents(); return this; }, // Set callbacks, where `this.events` is a hash of // // *{"event selector": "callback"}* // // { // 'mousedown .title': 'edit', // 'click .button': 'save', // 'click .open': function(e) { ... } // } // // pairs. Callbacks will be bound to the view, with `this` set properly. // Uses event delegation for efficiency. // Omitting the selector binds the event to `this.el`. // This only works for delegate-able events: not `focus`, `blur`, and // not `change`, `submit`, and `reset` in Internet Explorer. delegateEvents: function(events) { if (!(events || (events = _.result(this, 'events')))) return this; this.undelegateEvents(); for (var key in events) { var method = events[key]; if (!_.isFunction(method)) method = this[events[key]]; if (!method) continue; var match = key.match(delegateEventSplitter); var eventName = match[1], selector = match[2]; method = _.bind(method, this); eventName += '.delegateEvents' + this.cid; if (selector === '') { this.$el.on(eventName, method); } else { this.$el.on(eventName, selector, method); } } return this; }, // Clears all callbacks previously bound to the view with `delegateEvents`. // You usually don't need to use this, but may wish to if you have multiple // Backbone views attached to the same DOM element. undelegateEvents: function() { this.$el.off('.delegateEvents' + this.cid); return this; }, // Ensure that the View has a DOM element to render into. // If `this.el` is a string, pass it through `$()`, take the first // matching element, and re-assign it to `el`. Otherwise, create // an element from the `id`, `className` and `tagName` properties. _ensureElement: function() { if (!this.el) { var attrs = _.extend({}, _.result(this, 'attributes')); if (this.id) attrs.id = _.result(this, 'id'); if (this.className) attrs['class'] = _.result(this, 'className'); var $el = Backbone.$('<' + _.result(this, 'tagName') + '>').attr(attrs); this.setElement($el, false); } else { this.setElement(_.result(this, 'el'), false); } } }); // Backbone.sync // ------------- // Override this function to change the manner in which Backbone persists // models to the server. You will be passed the type of request, and the // model in question. By default, makes a RESTful Ajax request // to the model's `url()`. Some possible customizations could be: // // * Use `setTimeout` to batch rapid-fire updates into a single request. // * Send up the models as XML instead of JSON. // * Persist models via WebSockets instead of Ajax. // // Turn on `Backbone.emulateHTTP` in order to send `PUT` and `DELETE` requests // as `POST`, with a `_method` parameter containing the true HTTP method, // as well as all requests with the body as `application/x-www-form-urlencoded` // instead of `application/json` with the model in a param named `model`. // Useful when interfacing with server-side languages like **PHP** that make // it difficult to read the body of `PUT` requests. Backbone.sync = function(method, model, options) { var type = methodMap[method]; // Default options, unless specified. _.defaults(options || (options = {}), { emulateHTTP: Backbone.emulateHTTP, emulateJSON: Backbone.emulateJSON }); // Default JSON-request options. var params = {type: type, dataType: 'json'}; // Ensure that we have a URL. if (!options.url) { params.url = _.result(model, 'url') || urlError(); } // Ensure that we have the appropriate request data. if (options.data == null && model && (method === 'create' || method === 'update' || method === 'patch')) { params.contentType = 'application/json'; params.data = JSON.stringify(options.attrs || model.toJSON(options)); } // For older servers, emulate JSON by encoding the request into an HTML-form. if (options.emulateJSON) { params.contentType = 'application/x-www-form-urlencoded'; params.data = params.data ? {model: params.data} : {}; } // For older servers, emulate HTTP by mimicking the HTTP method with `_method` // And an `X-HTTP-Method-Override` header. if (options.emulateHTTP && (type === 'PUT' || type === 'DELETE' || type === 'PATCH')) { params.type = 'POST'; if (options.emulateJSON) params.data._method = type; var beforeSend = options.beforeSend; options.beforeSend = function(xhr) { xhr.setRequestHeader('X-HTTP-Method-Override', type); if (beforeSend) return beforeSend.apply(this, arguments); }; } // Don't process data on a non-GET request. if (params.type !== 'GET' && !options.emulateJSON) { params.processData = false; } // If we're sending a `PATCH` request, and we're in an old Internet Explorer // that still has ActiveX enabled by default, override jQuery to use that // for XHR instead. Remove this line when jQuery supports `PATCH` on IE8. if (params.type === 'PATCH' && noXhrPatch) { params.xhr = function() { return new ActiveXObject("Microsoft.XMLHTTP"); }; } // Make the request, allowing the user to override any Ajax options. var xhr = options.xhr = Backbone.ajax(_.extend(params, options)); model.trigger('request', model, xhr, options); return xhr; }; var noXhrPatch = typeof window !== 'undefined' && !!window.ActiveXObject && !(window.XMLHttpRequest && (new XMLHttpRequest).dispatchEvent); // Map from CRUD to HTTP for our default `Backbone.sync` implementation. var methodMap = { 'create': 'POST', 'update': 'PUT', 'patch': 'PATCH', 'delete': 'DELETE', 'read': 'GET' }; // Set the default implementation of `Backbone.ajax` to proxy through to `$`. // Override this if you'd like to use a different library. Backbone.ajax = function() { return Backbone.$.ajax.apply(Backbone.$, arguments); }; // Backbone.Router // --------------- // Routers map faux-URLs to actions, and fire events when routes are // matched. Creating a new one sets its `routes` hash, if not set statically. var Router = Backbone.Router = function(options) { options || (options = {}); if (options.routes) this.routes = options.routes; this._bindRoutes(); this.initialize.apply(this, arguments); }; // Cached regular expressions for matching named param parts and splatted // parts of route strings. var optionalParam = /\((.*?)\)/g; var namedParam = /(\(\?)?:\w+/g; var splatParam = /\*\w+/g; var escapeRegExp = /[\-{}\[\]+?.,\\\^$|#\s]/g; // Set up all inheritable **Backbone.Router** properties and methods. _.extend(Router.prototype, Events, { // Initialize is an empty function by default. Override it with your own // initialization logic. initialize: function(){}, // Manually bind a single named route to a callback. For example: // // this.route('search/:query/p:num', 'search', function(query, num) { // ... // }); // route: function(route, name, callback) { if (!_.isRegExp(route)) route = this._routeToRegExp(route); if (_.isFunction(name)) { callback = name; name = ''; } if (!callback) callback = this[name]; var router = this; Backbone.history.route(route, function(fragment) { var args = router._extractParameters(route, fragment); router.execute(callback, args); router.trigger.apply(router, ['route:' + name].concat(args)); router.trigger('route', name, args); Backbone.history.trigger('route', router, name, args); }); return this; }, // Execute a route handler with the provided parameters. This is an // excellent place to do pre-route setup or post-route cleanup. execute: function(callback, args) { if (callback) callback.apply(this, args); }, // Simple proxy to `Backbone.history` to save a fragment into the history. navigate: function(fragment, options) { Backbone.history.navigate(fragment, options); return this; }, // Bind all defined routes to `Backbone.history`. We have to reverse the // order of the routes here to support behavior where the most general // routes can be defined at the bottom of the route map. _bindRoutes: function() { if (!this.routes) return; this.routes = _.result(this, 'routes'); var route, routes = _.keys(this.routes); while ((route = routes.pop()) != null) { this.route(route, this.routes[route]); } }, // Convert a route string into a regular expression, suitable for matching // against the current location hash. _routeToRegExp: function(route) { route = route.replace(escapeRegExp, '\\$&') .replace(optionalParam, '(?:$1)?') .replace(namedParam, function(match, optional) { return optional ? match : '([^/?]+)'; }) .replace(splatParam, '([^?]*?)'); return new RegExp('^' + route + '(?:\\?([\\s\\S]*))?$'); }, // Given a route, and a URL fragment that it matches, return the array of // extracted decoded parameters. Empty or unmatched parameters will be // treated as `null` to normalize cross-browser behavior. _extractParameters: function(route, fragment) { var params = route.exec(fragment).slice(1); return _.map(params, function(param, i) { // Don't decode the search params. if (i === params.length - 1) return param || null; return param ? decodeURIComponent(param) : null; }); } }); // Backbone.History // ---------------- // Handles cross-browser history management, based on either // [pushState](http://diveintohtml5.info/history.html) and real URLs, or // [onhashchange](https://developer.mozilla.org/en-US/docs/DOM/window.onhashchange) // and URL fragments. If the browser supports neither (old IE, natch), // falls back to polling. var History = Backbone.History = function() { this.handlers = []; _.bindAll(this, 'checkUrl'); // Ensure that `History` can be used outside of the browser. if (typeof window !== 'undefined') { this.location = window.location; this.history = window.history; } }; // Cached regex for stripping a leading hash/slash and trailing space. var routeStripper = /^[#\/]|\s+$/g; // Cached regex for stripping leading and trailing slashes. var rootStripper = /^\/+|\/+$/g; // Cached regex for detecting MSIE. var isExplorer = /msie [\w.]+/; // Cached regex for removing a trailing slash. var trailingSlash = /\/$/; // Cached regex for stripping urls of hash. var pathStripper = /#.*$/; // Has the history handling already been started? History.started = false; // Set up all inheritable **Backbone.History** properties and methods. _.extend(History.prototype, Events, { // The default interval to poll for hash changes, if necessary, is // twenty times a second. interval: 50, // Are we at the app root? atRoot: function() { return this.location.pathname.replace(/[^\/]$/, '$&/') === this.root; }, // Gets the true hash value. Cannot use location.hash directly due to bug // in Firefox where location.hash will always be decoded. getHash: function(window) { var match = (window || this).location.href.match(/#(.*)$/); return match ? match[1] : ''; }, // Get the cross-browser normalized URL fragment, either from the URL, // the hash, or the override. getFragment: function(fragment, forcePushState) { if (fragment == null) { if (this._hasPushState || !this._wantsHashChange || forcePushState) { fragment = decodeURI(this.location.pathname + this.location.search); var root = this.root.replace(trailingSlash, ''); if (!fragment.indexOf(root)) fragment = fragment.slice(root.length); } else { fragment = this.getHash(); } } return fragment.replace(routeStripper, ''); }, // Start the hash change handling, returning `true` if the current URL matches // an existing route, and `false` otherwise. start: function(options) { if (History.started) throw new Error("Backbone.history has already been started"); History.started = true; // Figure out the initial configuration. Do we need an iframe? // Is pushState desired ... is it available? this.options = _.extend({root: '/'}, this.options, options); this.root = this.options.root; this._wantsHashChange = this.options.hashChange !== false; this._wantsPushState = !!this.options.pushState; this._hasPushState = !!(this.options.pushState && this.history && this.history.pushState); var fragment = this.getFragment(); var docMode = document.documentMode; var oldIE = (isExplorer.exec(navigator.userAgent.toLowerCase()) && (!docMode || docMode <= 7)); // Normalize root to always include a leading and trailing slash. this.root = ('/' + this.root + '/').replace(rootStripper, '/'); if (oldIE && this._wantsHashChange) { var frame = Backbone.$('<iframe src="javascript:0" tabindex="-1">'); this.iframe = frame.hide().appendTo('body')[0].contentWindow; this.navigate(fragment); } // Depending on whether we're using pushState or hashes, and whether // 'onhashchange' is supported, determine how we check the URL state. if (this._hasPushState) { Backbone.$(window).on('popstate', this.checkUrl); } else if (this._wantsHashChange && ('onhashchange' in window) && !oldIE) { Backbone.$(window).on('hashchange', this.checkUrl); } else if (this._wantsHashChange) { this._checkUrlInterval = setInterval(this.checkUrl, this.interval); } // Determine if we need to change the base url, for a pushState link // opened by a non-pushState browser. this.fragment = fragment; var loc = this.location; // Transition from hashChange to pushState or vice versa if both are // requested. if (this._wantsHashChange && this._wantsPushState) { // If we've started off with a route from a `pushState`-enabled // browser, but we're currently in a browser that doesn't support it... if (!this._hasPushState && !this.atRoot()) { this.fragment = this.getFragment(null, true); this.location.replace(this.root + '#' + this.fragment); // Return immediately as browser will do redirect to new url return true; // Or if we've started out with a hash-based route, but we're currently // in a browser where it could be `pushState`-based instead... } else if (this._hasPushState && this.atRoot() && loc.hash) { this.fragment = this.getHash().replace(routeStripper, ''); this.history.replaceState({}, document.title, this.root + this.fragment); } } if (!this.options.silent) return this.loadUrl(); }, // Disable Backbone.history, perhaps temporarily. Not useful in a real app, // but possibly useful for unit testing Routers. stop: function() { Backbone.$(window).off('popstate', this.checkUrl).off('hashchange', this.checkUrl); if (this._checkUrlInterval) clearInterval(this._checkUrlInterval); History.started = false; }, // Add a route to be tested when the fragment changes. Routes added later // may override previous routes. route: function(route, callback) { this.handlers.unshift({route: route, callback: callback}); }, // Checks the current URL to see if it has changed, and if it has, // calls `loadUrl`, normalizing across the hidden iframe. checkUrl: function(e) { var current = this.getFragment(); if (current === this.fragment && this.iframe) { current = this.getFragment(this.getHash(this.iframe)); } if (current === this.fragment) return false; if (this.iframe) this.navigate(current); this.loadUrl(); }, // Attempt to load the current URL fragment. If a route succeeds with a // match, returns `true`. If no defined routes matches the fragment, // returns `false`. loadUrl: function(fragment) { fragment = this.fragment = this.getFragment(fragment); return _.any(this.handlers, function(handler) { if (handler.route.test(fragment)) { handler.callback(fragment); return true; } }); }, // Save a fragment into the hash history, or replace the URL state if the // 'replace' option is passed. You are responsible for properly URL-encoding // the fragment in advance. // // The options object can contain `trigger: true` if you wish to have the // route callback be fired (not usually desirable), or `replace: true`, if // you wish to modify the current URL without adding an entry to the history. navigate: function(fragment, options) { if (!History.started) return false; if (!options || options === true) options = {trigger: !!options}; var url = this.root + (fragment = this.getFragment(fragment || '')); // Strip the hash for matching. fragment = fragment.replace(pathStripper, ''); if (this.fragment === fragment) return; this.fragment = fragment; // Don't include a trailing slash on the root. if (fragment === '' && url !== '/') url = url.slice(0, -1); // If pushState is available, we use it to set the fragment as a real URL. if (this._hasPushState) { this.history[options.replace ? 'replaceState' : 'pushState']({}, document.title, url); // If hash changes haven't been explicitly disabled, update the hash // fragment to store history. } else if (this._wantsHashChange) { this._updateHash(this.location, fragment, options.replace); if (this.iframe && (fragment !== this.getFragment(this.getHash(this.iframe)))) { // Opening and closing the iframe tricks IE7 and earlier to push a // history entry on hash-tag change. When replace is true, we don't // want this. if(!options.replace) this.iframe.document.open().close(); this._updateHash(this.iframe.location, fragment, options.replace); } // If you've told us that you explicitly don't want fallback hashchange- // based history, then `navigate` becomes a page refresh. } else { return this.location.assign(url); } if (options.trigger) return this.loadUrl(fragment); }, // Update the hash location, either replacing the current entry, or adding // a new one to the browser history. _updateHash: function(location, fragment, replace) { if (replace) { var href = location.href.replace(/(javascript:|#).*$/, ''); location.replace(href + '#' + fragment); } else { // Some browsers require that `hash` contains a leading #. location.hash = '#' + fragment; } } }); // Create the default Backbone.history. Backbone.history = new History; // Helpers // ------- // Helper function to correctly set up the prototype chain, for subclasses. // Similar to `goog.inherits`, but uses a hash of prototype properties and // class properties to be extended. var extend = function(protoProps, staticProps) { var parent = this; var child; // The constructor function for the new subclass is either defined by you // (the "constructor" property in your `extend` definition), or defaulted // by us to simply call the parent's constructor. if (protoProps && _.has(protoProps, 'constructor')) { child = protoProps.constructor; } else { child = function(){ return parent.apply(this, arguments); }; } // Add static properties to the constructor function, if supplied. _.extend(child, parent, staticProps); // Set the prototype chain to inherit from `parent`, without calling // `parent`'s constructor function. var Surrogate = function(){ this.constructor = child; }; Surrogate.prototype = parent.prototype; child.prototype = new Surrogate; // Add prototype properties (instance properties) to the subclass, // if supplied. if (protoProps) _.extend(child.prototype, protoProps); // Set a convenience property in case the parent's prototype is needed // later. child.__super__ = parent.prototype; return child; }; // Set up inheritance for the model, collection, router, view and history. Model.extend = Collection.extend = Router.extend = View.extend = History.extend = extend; // Throw an error when a URL is needed, and none is supplied. var urlError = function() { throw new Error('A "url" property or function must be specified'); }; // Wrap an optional error callback with a fallback error event. var wrapError = function(model, options) { var error = options.error; options.error = function(resp) { if (error) error(model, resp, options); model.trigger('error', model, resp, options); }; }; return Backbone; })); // Vectorizer. // ----------- // A tiny library for making your live easier when dealing with SVG. // Copyright © 2012 - 2014 client IO (http://client.io) (function(root, factory) { if (typeof define === 'function' && define.amd) { // AMD. Register as an anonymous module. define([], factory); } else { // Browser globals. root.Vectorizer = root.V = factory(); } }(this, function() { // Well, if SVG is not supported, this library is useless. var SVGsupported = !!(window.SVGAngle || document.implementation.hasFeature('http://www.w3.org/TR/SVG11/feature#BasicStructure', '1.1')); // XML namespaces. var ns = { xmlns: 'http://www.w3.org/2000/svg', xlink: 'http://www.w3.org/1999/xlink' }; // SVG version. var SVGversion = '1.1'; // A function returning a unique identifier for this client session with every call. var idCounter = 0; function uniqueId() { var id = ++idCounter + ''; return 'v-' + id; } // Create SVG element. // ------------------- function createElement(el, attrs, children) { if (!el) return undefined; // If `el` is an object, it is probably a native SVG element. Wrap it to VElement. if (typeof el === 'object') { return new VElement(el); } attrs = attrs || {}; // If `el` is a `'svg'` or `'SVG'` string, create a new SVG canvas. if (el.toLowerCase() === 'svg') { attrs.xmlns = ns.xmlns; attrs['xmlns:xlink'] = ns.xlink; attrs.version = SVGversion; } else if (el[0] === '<') { // Create element from an SVG string. // Allows constructs of type: `document.appendChild(Vectorizer('<rect></rect>').node)`. var svg = '<svg xmlns="' + ns.xmlns + '" xmlns:xlink="' + ns.xlink + '" version="' + SVGversion + '">' + el + '</svg>'; var parser = new DOMParser(); parser.async = false; var svgDoc = parser.parseFromString(svg, 'text/xml').documentElement; // Note that `createElement()` might also return an array should the SVG string passed as // the first argument contain more then one root element. if (svgDoc.childNodes.length > 1) { // Map child nodes to `VElement`s. var ret = []; for (var i = 0, len = svgDoc.childNodes.length; i < len; i++) { var childNode = svgDoc.childNodes[i]; ret.push(new VElement(document.importNode(childNode, true))); } return ret; } return new VElement(document.importNode(svgDoc.firstChild, true)); } el = document.createElementNS(ns.xmlns, el); // Set attributes. for (var key in attrs) { setAttribute(el, key, attrs[key]); } // Normalize `children` array. if (Object.prototype.toString.call(children) != '[object Array]') children = [children]; // Append children if they are specified. var i = 0, len = (children[0] && children.length) || 0, child; for (; i < len; i++) { child = children[i]; el.appendChild(child instanceof VElement ? child.node : child); } return new VElement(el); } function setAttribute(el, name, value) { if (name.indexOf(':') > -1) { // Attribute names can be namespaced. E.g. `image` elements // have a `xlink:href` attribute to set the source of the image. var combinedKey = name.split(':'); el.setAttributeNS(ns[combinedKey[0]], combinedKey[1], value); } else if (name === 'id') { el.id = value; } else { el.setAttribute(name, value); } } function parseTransformString(transform) { var translate, rotate, scale; if (transform) { var separator = /[ ,]+/; var translateMatch = transform.match(/translate\((.*)\)/); if (translateMatch) { translate = translateMatch[1].split(separator); } var rotateMatch = transform.match(/rotate\((.*)\)/); if (rotateMatch) { rotate = rotateMatch[1].split(separator); } var scaleMatch = transform.match(/scale\((.*)\)/); if (scaleMatch) { scale = scaleMatch[1].split(separator); } } var sx = (scale && scale[0]) ? parseFloat(scale[0]) : 1; return { translate: { tx: (translate && translate[0]) ? parseInt(translate[0], 10) : 0, ty: (translate && translate[1]) ? parseInt(translate[1], 10) : 0 }, rotate: { angle: (rotate && rotate[0]) ? parseInt(rotate[0], 10) : 0, cx: (rotate && rotate[1]) ? parseInt(rotate[1], 10) : undefined, cy: (rotate && rotate[2]) ? parseInt(rotate[2], 10) : undefined }, scale: { sx: sx, sy: (scale && scale[1]) ? parseFloat(scale[1]) : sx } }; } // Matrix decomposition. // --------------------- function deltaTransformPoint(matrix, point) { var dx = point.x * matrix.a + point.y * matrix.c + 0; var dy = point.x * matrix.b + point.y * matrix.d + 0; return { x: dx, y: dy }; } function decomposeMatrix(matrix) { // @see https://gist.github.com/2052247 // calculate delta transform point var px = deltaTransformPoint(matrix, { x: 0, y: 1 }); var py = deltaTransformPoint(matrix, { x: 1, y: 0 }); // calculate skew var skewX = ((180 / Math.PI) * Math.atan2(px.y, px.x) - 90); var skewY = ((180 / Math.PI) * Math.atan2(py.y, py.x)); return { translateX: matrix.e, translateY: matrix.f, scaleX: Math.sqrt(matrix.a * matrix.a + matrix.b * matrix.b), scaleY: Math.sqrt(matrix.c * matrix.c + matrix.d * matrix.d), skewX: skewX, skewY: skewY, rotation: skewX // rotation is the same as skew x }; } // VElement. // --------- function VElement(el) { this.node = el; if (!this.node.id) { this.node.id = uniqueId(); } } // VElement public API. // -------------------- VElement.prototype = { translate: function(tx, ty, opt) { opt = opt || {}; ty = ty || 0; var transformAttr = this.attr('transform') || '', transform = parseTransformString(transformAttr); // Is it a getter? if (typeof tx === 'undefined') { return transform.translate; } transformAttr = transformAttr.replace(/translate\([^\)]*\)/g, '').trim(); var newTx = opt.absolute ? tx : transform.translate.tx + tx, newTy = opt.absolute ? ty : transform.translate.ty + ty, newTranslate = 'translate(' + newTx + ',' + newTy + ')'; // Note that `translate()` is always the first transformation. This is // usually the desired case. this.attr('transform', (newTranslate + ' ' + transformAttr).trim()); return this; }, rotate: function(angle, cx, cy, opt) { opt = opt || {}; var transformAttr = this.attr('transform') || '', transform = parseTransformString(transformAttr); // Is it a getter? if (typeof angle === 'undefined') { return transform.rotate; } transformAttr = transformAttr.replace(/rotate\([^\)]*\)/g, '').trim(); angle %= 360; var newAngle = opt.absolute ? angle: transform.rotate.angle + angle, newOrigin = (cx !== undefined && cy !== undefined) ? ',' + cx + ',' + cy : '', newRotate = 'rotate(' + newAngle + newOrigin + ')'; this.attr('transform', (transformAttr + ' ' + newRotate).trim()); return this; }, // Note that `scale` as the only transformation does not combine with previous values. scale: function(sx, sy) { sy = (typeof sy === 'undefined') ? sx : sy; var transformAttr = this.attr('transform') || '', transform = parseTransformString(transformAttr); // Is it a getter? if (typeof sx === 'undefined') { return transform.scale; } transformAttr = transformAttr.replace(/scale\([^\)]*\)/g, '').trim(); var newScale = 'scale(' + sx + ',' + sy + ')'; this.attr('transform', (transformAttr + ' ' + newScale).trim()); return this; }, // Get SVGRect that contains coordinates and dimension of the real bounding box, // i.e. after transformations are applied. // If `target` is specified, bounding box will be computed relatively to `target` element. bbox: function(withoutTransformations, target) { // If the element is not in the live DOM, it does not have a bounding box defined and // so fall back to 'zero' dimension element. if (!this.node.ownerSVGElement) return { x: 0, y: 0, width: 0, height: 0 }; var box; try { box = this.node.getBBox(); // Opera returns infinite values in some cases. // Note that Infinity | 0 produces 0 as opposed to Infinity || 0. // We also have to create new object as the standard says that you can't // modify the attributes of a bbox. box = { x: box.x | 0, y: box.y | 0, width: box.width | 0, height: box.height | 0}; } catch (e) { // Fallback for IE. box = { x: this.node.clientLeft, y: this.node.clientTop, width: this.node.clientWidth, height: this.node.clientHeight }; } if (withoutTransformations) { return box; } var matrix = this.node.getTransformToElement(target || this.node.ownerSVGElement); var corners = []; var point = this.node.ownerSVGElement.createSVGPoint(); point.x = box.x; point.y = box.y; corners.push(point.matrixTransform(matrix)); point.x = box.x + box.width; point.y = box.y; corners.push(point.matrixTransform(matrix)); point.x = box.x + box.width; point.y = box.y + box.height; corners.push(point.matrixTransform(matrix)); point.x = box.x; point.y = box.y + box.height; corners.push(point.matrixTransform(matrix)); var minX = corners[0].x; var maxX = minX; var minY = corners[0].y; var maxY = minY; for (var i = 1, len = corners.length; i < len; i++) { var x = corners[i].x; var y = corners[i].y; if (x < minX) { minX = x; } else if (x > maxX) { maxX = x; } if (y < minY) { minY = y; } else if (y > maxY) { maxY = y; } } return { x: minX, y: minY, width: maxX - minX, height: maxY - minY }; }, text: function(content, opt) { opt = opt || {}; var lines = content.split('\n'); var i = 0; var tspan; // `alignment-baseline` does not work in Firefox. // Setting `dominant-baseline` on the `<text>` element doesn't work in IE9. // In order to have the 0,0 coordinate of the `<text>` element (or the first `<tspan>`) // in the top left corner we translate the `<text>` element by `0.8em`. // See `http://www.w3.org/Graphics/SVG/WG/wiki/How_to_determine_dominant_baseline`. // See also `http://apike.ca/prog_svg_text_style.html`. this.attr('y', '0.8em'); // An empty text gets rendered into the DOM in webkit-based browsers. // In order to unify this behaviour across all browsers // we rather hide the text element when it's empty. this.attr('display', content ? null : 'none'); // Preserve spaces. In other words, we do not want consecutive spaces to get collapsed to one. this.node.setAttributeNS("http://www.w3.org/XML/1998/namespace", "xml:space","preserve"); if (lines.length === 1) { this.node.textContent = content; return this; } // Easy way to erase all `<tspan>` children; this.node.textContent = ''; for (; i < lines.length; i++) { // Shift all the <tspan> but first by one line (`1em`) tspan = V('tspan', { dy: (i == 0 ? '0em' : opt.lineHeight || '1em'), x: this.attr('x') || 0}); // Make sure the textContent is never empty. If it is, add an additional // space (an invisible character) so that following lines are correctly // relatively positioned. `dy=1em` won't work with empty lines otherwise. tspan.node.textContent = lines[i] || ' '; this.append(tspan); } return this; }, attr: function(name, value) { if (typeof name === 'string' && typeof value === 'undefined') { return this.node.getAttribute(name); } if (typeof name === 'object') { for (var attrName in name) { if (name.hasOwnProperty(attrName)) { setAttribute(this.node, attrName, name[attrName]); } } } else { setAttribute(this.node, name, value); } return this; }, remove: function() { if (this.node.parentNode) { this.node.parentNode.removeChild(this.node); } }, append: function(el) { var els = el; if (Object.prototype.toString.call(el) !== '[object Array]') { els = [el]; } for (var i = 0, len = els.length; i < len; i++) { el = els[i]; this.node.appendChild(el instanceof VElement ? el.node : el); } return this; }, prepend: function(el) { this.node.insertBefore(el instanceof VElement ? el.node : el, this.node.firstChild); }, svg: function() { return this.node instanceof window.SVGSVGElement ? this : V(this.node.ownerSVGElement); }, defs: function() { var defs = this.svg().node.getElementsByTagName('defs'); return (defs && defs.length) ? V(defs[0]) : undefined; }, clone: function() { var clone = V(this.node.cloneNode(true)); // Note that clone inherits also ID. Therefore, we need to change it here. clone.node.id = uniqueId(); return clone; }, findOne: function(selector) { var found = this.node.querySelector(selector); return found ? V(found) : undefined; }, find: function(selector) { var nodes = this.node.querySelectorAll(selector); // Map DOM elements to `VElement`s. for (var i = 0, len = nodes.length; i < len; i++) { nodes[i] = V(nodes[i]); } return nodes; }, // Convert global point into the coordinate space of this element. toLocalPoint: function(x, y) { var svg = this.svg().node; var p = svg.createSVGPoint(); p.x = x; p.y = y; try { var globalPoint = p.matrixTransform(svg.getScreenCTM().inverse()); var globalToLocalMatrix = this.node.getTransformToElement(svg).inverse(); } catch(e) { // IE9 throws an exception in odd cases. (`Unexpected call to method or property access`) // We have to make do with the original coordianates. return p; } return globalPoint.matrixTransform(globalToLocalMatrix); }, translateCenterToPoint: function(p) { var bbox = this.bbox(); var center = g.rect(bbox).center(); this.translate(p.x - center.x, p.y - center.y); }, // Efficiently auto-orient an element. This basically implements the orient=auto attribute // of markers. The easiest way of understanding on what this does is to imagine the element is an // arrowhead. Calling this method on the arrowhead makes it point to the `position` point while // being auto-oriented (properly rotated) towards the `reference` point. // `target` is the element relative to which the transformations are applied. Usually a viewport. translateAndAutoOrient: function(position, reference, target) { // Clean-up previously set transformations except the scale. If we didn't clean up the // previous transformations then they'd add up with the old ones. Scale is an exception as // it doesn't add up, consider: `this.scale(2).scale(2).scale(2)`. The result is that the // element is scaled by the factor 2, not 8. var s = this.scale(); this.attr('transform', ''); this.scale(s.sx, s.sy); var svg = this.svg().node; var bbox = this.bbox(false, target); // 1. Translate to origin. var translateToOrigin = svg.createSVGTransform(); translateToOrigin.setTranslate(-bbox.x - bbox.width/2, -bbox.y - bbox.height/2); // 2. Rotate around origin. var rotateAroundOrigin = svg.createSVGTransform(); var angle = g.point(position).changeInAngle(position.x - reference.x, position.y - reference.y, reference); rotateAroundOrigin.setRotate(angle, 0, 0); // 3. Translate to the `position` + the offset (half my width) towards the `reference` point. var translateFinal = svg.createSVGTransform(); var finalPosition = g.point(position).move(reference, bbox.width/2); translateFinal.setTranslate(position.x + (position.x - finalPosition.x), position.y + (position.y - finalPosition.y)); // 4. Apply transformations. var ctm = this.node.getTransformToElement(target); var transform = svg.createSVGTransform(); transform.setMatrix( translateFinal.matrix.multiply( rotateAroundOrigin.matrix.multiply( translateToOrigin.matrix.multiply( ctm))) ); // Instead of directly setting the `matrix()` transform on the element, first, decompose // the matrix into separate transforms. This allows us to use normal Vectorizer methods // as they don't work on matrices. An example of this is to retrieve a scale of an element. // this.node.transform.baseVal.initialize(transform); var decomposition = decomposeMatrix(transform.matrix); this.translate(decomposition.translateX, decomposition.translateY); this.rotate(decomposition.rotation); // Note that scale has been already applied, hence the following line stays commented. (it's here just for reference). //this.scale(decomposition.scaleX, decomposition.scaleY); return this; }, animateAlongPath: function(attrs, path) { var animateMotion = V('animateMotion', attrs); var mpath = V('mpath', { 'xlink:href': '#' + V(path).node.id }); animateMotion.append(mpath); this.append(animateMotion); try { animateMotion.node.beginElement(); } catch (e) { // Fallback for IE 9. // Run the animation programatically if FakeSmile (`http://leunen.me/fakesmile/`) present if (document.documentElement.getAttribute('smiling') === 'fake') { // Register the animation. (See `https://answers.launchpad.net/smil/+question/203333`) var animation = animateMotion.node; animation.animators = []; var animationID = animation.getAttribute('id'); if (animationID) id2anim[animationID] = animation; var targets = getTargets(animation); for (var i = 0, len = targets.length; i < len; i++) { var target = targets[i]; var animator = new Animator(animation, target, i); animators.push(animator); animation.animators[i] = animator; animator.register(); } } } }, hasClass: function(className) { return new RegExp('(\\s|^)' + className + '(\\s|$)').test(this.node.getAttribute('class')); }, addClass: function(className) { if (!this.hasClass(className)) { var prevClasses = this.node.getAttribute('class') || ''; this.node.setAttribute('class', (prevClasses + ' ' + className).trim()); } return this; }, removeClass: function(className) { if (this.hasClass(className)) { var newClasses = this.node.getAttribute('class').replace(new RegExp('(\\s|^)' + className + '(\\s|$)', 'g'), '$2'); this.node.setAttribute('class', newClasses); } return this; }, toggleClass: function(className, toAdd) { var toRemove = typeof toAdd === 'undefined' ? this.hasClass(className) : !toAdd; if (toRemove) { this.removeClass(className); } else { this.addClass(className); } return this; } }; // Convert a rectangle to SVG path commands. `r` is an object of the form: // `{ x: [number], y: [number], width: [number], height: [number], top-ry: [number], top-ry: [number], bottom-rx: [number], bottom-ry: [number] }`, // where `x, y, width, height` are the usual rectangle attributes and [top-/bottom-]rx/ry allows for // specifying radius of the rectangle for all its sides (as opposed to the built-in SVG rectangle // that has only `rx` and `ry` attributes). function rectToPath(r) { var topRx = r.rx || r['top-rx'] || 0; var bottomRx = r.rx || r['bottom-rx'] || 0; var topRy = r.ry || r['top-ry'] || 0; var bottomRy = r.ry || r['bottom-ry'] || 0; return [ 'M', r.x, r.y + topRy, 'v', r.height - topRy - bottomRy, 'a', bottomRx, bottomRy, 0, 0, 0, bottomRx, bottomRy, 'h', r.width - 2 * bottomRx, 'a', bottomRx, bottomRy, 0, 0, 0, bottomRx, -bottomRy, 'v', -(r.height - bottomRy - topRy), 'a', topRx, topRy, 0, 0, 0, -topRx, -topRy, 'h', -(r.width - 2 * topRx), 'a', topRx, topRy, 0, 0, 0, -topRx, topRy ].join(' '); } var V = createElement; V.decomposeMatrix = decomposeMatrix; V.rectToPath = rectToPath; var svgDocument = V('svg').node; V.createSVGMatrix = function(m) { var svgMatrix = svgDocument.createSVGMatrix(); for (var component in m) { svgMatrix[component] = m[component]; } return svgMatrix; }; V.createSVGTransform = function() { return svgDocument.createSVGTransform(); }; V.createSVGPoint = function(x, y) { var p = svgDocument.createSVGPoint(); p.x = x; p.y = y; return p; }; return V; })); // Geometry library. // (c) 2011-2013 client IO (function(root, factory) { if (typeof define === 'function' && define.amd) { // AMD. Register as an anonymous module. define([], factory); } else if (typeof exports === 'object') { // Node. Does not work with strict CommonJS, but // only CommonJS-like environments that support module.exports, // like Node. module.exports = factory(); } else { // Browser globals. root.g = factory(); } }(this, function() { // Declare shorthands to the most used math functions. var math = Math; var abs = math.abs; var cos = math.cos; var sin = math.sin; var sqrt = math.sqrt; var mmin = math.min; var mmax = math.max; var atan = math.atan; var atan2 = math.atan2; var acos = math.acos; var round = math.round; var floor = math.floor; var PI = math.PI; var random = math.random; var toDeg = function(rad) { return (180*rad / PI) % 360; }; var toRad = function(deg) { return (deg % 360) * PI / 180; }; var snapToGrid = function(val, gridSize) { return gridSize * Math.round(val/gridSize); }; var normalizeAngle = function(angle) { return (angle % 360) + (angle < 0 ? 360 : 0); }; // Point // ----- // Point is the most basic object consisting of x/y coordinate,. // Possible instantiations are: // * `point(10, 20)` // * `new point(10, 20)` // * `point('10 20')` // * `point(point(10, 20))` function point(x, y) { if (!(this instanceof point)) return new point(x, y); var xy; if (y === undefined && Object(x) !== x) { xy = x.split(x.indexOf('@') === -1 ? ' ' : '@'); this.x = parseInt(xy[0], 10); this.y = parseInt(xy[1], 10); } else if (Object(x) === x) { this.x = x.x; this.y = x.y; } else { this.x = x; this.y = y; } } point.prototype = { toString: function() { return this.x + "@" + this.y; }, // If point lies outside rectangle `r`, return the nearest point on the boundary of rect `r`, // otherwise return point itself. // (see Squeak Smalltalk, Point>>adhereTo:) adhereToRect: function(r) { if (r.containsPoint(this)){ return this; } this.x = mmin(mmax(this.x, r.x), r.x + r.width); this.y = mmin(mmax(this.y, r.y), r.y + r.height); return this; }, // Compute the angle between me and `p` and the x axis. // (cartesian-to-polar coordinates conversion) // Return theta angle in degrees. theta: function(p) { p = point(p); // Invert the y-axis. var y = -(p.y - this.y); var x = p.x - this.x; // Makes sure that the comparison with zero takes rounding errors into account. var PRECISION = 10; // Note that `atan2` is not defined for `x`, `y` both equal zero. var rad = (y.toFixed(PRECISION) == 0 && x.toFixed(PRECISION) == 0) ? 0 : atan2(y, x); // Correction for III. and IV. quadrant. if (rad < 0) { rad = 2*PI + rad; } return 180*rad / PI; }, // Returns distance between me and point `p`. distance: function(p) { return line(this, p).length(); }, // Returns a manhattan (taxi-cab) distance between me and point `p`. manhattanDistance: function(p) { return abs(p.x - this.x) + abs(p.y - this.y); }, // Offset me by the specified amount. offset: function(dx, dy) { this.x += dx || 0; this.y += dy || 0; return this; }, magnitude: function() { return sqrt((this.x*this.x) + (this.y*this.y)) || 0.01; }, update: function(x, y) { this.x = x || 0; this.y = y || 0; return this; }, round: function(decimals) { this.x = decimals ? this.x.toFixed(decimals) : round(this.x); this.y = decimals ? this.y.toFixed(decimals) : round(this.y); return this; }, // Scale the line segment between (0,0) and me to have a length of len. normalize: function(len) { var s = (len || 1) / this.magnitude(); this.x = s * this.x; this.y = s * this.y; return this; }, difference: function(p) { return point(this.x - p.x, this.y - p.y); }, // Return the bearing between me and point `p`. bearing: function(p) { return line(this, p).bearing(); }, // Converts rectangular to polar coordinates. // An origin can be specified, otherwise it's 0@0. toPolar: function(o) { o = (o && point(o)) || point(0,0); var x = this.x; var y = this.y; this.x = sqrt((x-o.x)*(x-o.x) + (y-o.y)*(y-o.y)); // r this.y = toRad(o.theta(point(x,y))); return this; }, // Rotate point by angle around origin o. rotate: function(o, angle) { angle = (angle + 360) % 360; this.toPolar(o); this.y += toRad(angle); var p = point.fromPolar(this.x, this.y, o); this.x = p.x; this.y = p.y; return this; }, // Move point on line starting from ref ending at me by // distance distance. move: function(ref, distance) { var theta = toRad(point(ref).theta(this)); return this.offset(cos(theta) * distance, -sin(theta) * distance); }, // Returns change in angle from my previous position (-dx, -dy) to my new position // relative to ref point. changeInAngle: function(dx, dy, ref) { // Revert the translation and measure the change in angle around x-axis. return point(this).offset(-dx, -dy).theta(ref) - this.theta(ref); }, equals: function(p) { return this.x === p.x && this.y === p.y; }, snapToGrid: function(gx, gy) { this.x = snapToGrid(this.x, gx) this.y = snapToGrid(this.y, gy || gx) return this; }, // Returns a point that is the reflection of me with // the center of inversion in ref point. reflection: function(ref) { return point(ref).move(this, this.distance(ref)); } }; // Alternative constructor, from polar coordinates. // @param {number} r Distance. // @param {number} angle Angle in radians. // @param {point} [optional] o Origin. point.fromPolar = function(r, angle, o) { o = (o && point(o)) || point(0,0); var x = abs(r * cos(angle)); var y = abs(r * sin(angle)); var deg = normalizeAngle(toDeg(angle)); if (deg < 90) y = -y; else if (deg < 180) { x = -x; y = -y; } else if (deg < 270) x = -x; return point(o.x + x, o.y + y); }; // Create a point with random coordinates that fall into the range `[x1, x2]` and `[y1, y2]`. point.random = function(x1, x2, y1, y2) { return point(floor(random() * (x2 - x1 + 1) + x1), floor(random() * (y2 - y1 + 1) + y1)); }; // Line. // ----- function line(p1, p2) { if (!(this instanceof line)) return new line(p1, p2); this.start = point(p1); this.end = point(p2); } line.prototype = { toString: function() { return this.start.toString() + ' ' + this.end.toString(); }, // @return {double} length of the line length: function() { return sqrt(this.squaredLength()); }, // @return {integer} length without sqrt // @note for applications where the exact length is not necessary (e.g. compare only) squaredLength: function() { var x0 = this.start.x; var y0 = this.start.y; var x1 = this.end.x; var y1 = this.end.y; return (x0 -= x1)*x0 + (y0 -= y1)*y0; }, // @return {point} my midpoint midpoint: function() { return point((this.start.x + this.end.x) / 2, (this.start.y + this.end.y) / 2); }, // @return {point} Point where I'm intersecting l. // @see Squeak Smalltalk, LineSegment>>intersectionWith: intersection: function(l) { var pt1Dir = point(this.end.x - this.start.x, this.end.y - this.start.y); var pt2Dir = point(l.end.x - l.start.x, l.end.y - l.start.y); var det = (pt1Dir.x * pt2Dir.y) - (pt1Dir.y * pt2Dir.x); var deltaPt = point(l.start.x - this.start.x, l.start.y - this.start.y); var alpha = (deltaPt.x * pt2Dir.y) - (deltaPt.y * pt2Dir.x); var beta = (deltaPt.x * pt1Dir.y) - (deltaPt.y * pt1Dir.x); if (det === 0 || alpha * det < 0 || beta * det < 0) { // No intersection found. return null; } if (det > 0){ if (alpha > det || beta > det){ return null; } } else { if (alpha < det || beta < det){ return null; } } return point(this.start.x + (alpha * pt1Dir.x / det), this.start.y + (alpha * pt1Dir.y / det)); }, // @return the bearing (cardinal direction) of the line. For example N, W, or SE. // @returns {String} One of the following bearings : NE, E, SE, S, SW, W, NW, N. bearing: function() { var lat1 = toRad(this.start.y); var lat2 = toRad(this.end.y); var lon1 = this.start.x; var lon2 = this.end.x; var dLon = toRad(lon2 - lon1); var y = sin(dLon) * cos(lat2); var x = cos(lat1) * sin(lat2) - sin(lat1) * cos(lat2) * cos(dLon); var brng = toDeg(atan2(y, x)); var bearings = ['NE', 'E', 'SE', 'S', 'SW', 'W', 'NW', 'N']; var index = brng - 22.5; if (index < 0) index += 360; index = parseInt(index / 45); return bearings[index]; }, // @return {point} my point at 't' <0,1> pointAt: function(t) { var x = (1 - t) * this.start.x + t * this.end.x; var y = (1 - t) * this.start.y + t * this.end.y; return point(x, y); } }; // Rectangle. // ---------- function rect(x, y, w, h) { if (!(this instanceof rect)) return new rect(x, y, w, h); if (y === undefined) { y = x.y; w = x.width; h = x.height; x = x.x; } this.x = x; this.y = y; this.width = w; this.height = h; } rect.prototype = { toString: function() { return this.origin().toString() + ' ' + this.corner().toString(); }, origin: function() { return point(this.x, this.y); }, corner: function() { return point(this.x + this.width, this.y + this.height); }, topRight: function() { return point(this.x + this.width, this.y); }, bottomLeft: function() { return point(this.x, this.y + this.height); }, center: function() { return point(this.x + this.width/2, this.y + this.height/2); }, // @return {boolean} true if rectangles intersect intersect: function(r) { var myOrigin = this.origin(); var myCorner = this.corner(); var rOrigin = r.origin(); var rCorner = r.corner(); if (rCorner.x <= myOrigin.x || rCorner.y <= myOrigin.y || rOrigin.x >= myCorner.x || rOrigin.y >= myCorner.y) return false; return true; }, // @return {string} (left|right|top|bottom) side which is nearest to point // @see Squeak Smalltalk, Rectangle>>sideNearestTo: sideNearestToPoint: function(p) { p = point(p); var distToLeft = p.x - this.x; var distToRight = (this.x + this.width) - p.x; var distToTop = p.y - this.y; var distToBottom = (this.y + this.height) - p.y; var closest = distToLeft; var side = 'left'; if (distToRight < closest) { closest = distToRight; side = 'right'; } if (distToTop < closest) { closest = distToTop; side = 'top'; } if (distToBottom < closest) { closest = distToBottom; side = 'bottom'; } return side; }, // @return {bool} true if point p is insight me containsPoint: function(p) { p = point(p); if (p.x >= this.x && p.x <= this.x + this.width && p.y >= this.y && p.y <= this.y + this.height) { return true; } return false; }, // Algorithm ported from java.awt.Rectangle from OpenJDK. // @return {bool} true if rectangle `r` is inside me. containsRect: function(r) { var nr = rect(r).normalize(); var W = nr.width; var H = nr.height; var X = nr.x; var Y = nr.y; var w = this.width; var h = this.height; if ((w | h | W | H) < 0) { // At least one of the dimensions is negative... return false; } // Note: if any dimension is zero, tests below must return false... var x = this.x; var y = this.y; if (X < x || Y < y) { return false; } w += x; W += X; if (W <= X) { // X+W overflowed or W was zero, return false if... // either original w or W was zero or // x+w did not overflow or // the overflowed x+w is smaller than the overflowed X+W if (w >= x || W > w) return false; } else { // X+W did not overflow and W was not zero, return false if... // original w was zero or // x+w did not overflow and x+w is smaller than X+W if (w >= x && W > w) return false; } h += y; H += Y; if (H <= Y) { if (h >= y || H > h) return false; } else { if (h >= y && H > h) return false; } return true; }, // @return {point} a point on my boundary nearest to p // @see Squeak Smalltalk, Rectangle>>pointNearestTo: pointNearestToPoint: function(p) { p = point(p); if (this.containsPoint(p)) { var side = this.sideNearestToPoint(p); switch (side){ case "right": return point(this.x + this.width, p.y); case "left": return point(this.x, p.y); case "bottom": return point(p.x, this.y + this.height); case "top": return point(p.x, this.y); } } return p.adhereToRect(this); }, // Find point on my boundary where line starting // from my center ending in point p intersects me. // @param {number} angle If angle is specified, intersection with rotated rectangle is computed. intersectionWithLineFromCenterToPoint: function(p, angle) { p = point(p); var center = point(this.x + this.width/2, this.y + this.height/2); var result; if (angle) p.rotate(center, angle); // (clockwise, starting from the top side) var sides = [ line(this.origin(), this.topRight()), line(this.topRight(), this.corner()), line(this.corner(), this.bottomLeft()), line(this.bottomLeft(), this.origin()) ]; var connector = line(center, p); for (var i = sides.length - 1; i >= 0; --i){ var intersection = sides[i].intersection(connector); if (intersection !== null){ result = intersection; break; } } if (result && angle) result.rotate(center, -angle); return result; }, // Move and expand me. // @param r {rectangle} representing deltas moveAndExpand: function(r) { this.x += r.x; this.y += r.y; this.width += r.width; this.height += r.height; return this; }, round: function(decimals) { this.x = decimals ? this.x.toFixed(decimals) : round(this.x); this.y = decimals ? this.y.toFixed(decimals) : round(this.y); this.width = decimals ? this.width.toFixed(decimals) : round(this.width); this.height = decimals ? this.height.toFixed(decimals) : round(this.height); return this; }, // Normalize the rectangle; i.e., make it so that it has a non-negative width and height. // If width < 0 the function swaps the left and right corners, // and it swaps the top and bottom corners if height < 0 // like in http://qt-project.org/doc/qt-4.8/qrectf.html#normalized normalize: function() { var newx = this.x; var newy = this.y; var newwidth = this.width; var newheight = this.height; if (this.width < 0) { newx = this.x + this.width; newwidth = -this.width; } if (this.height < 0) { newy = this.y + this.height; newheight = -this.height; } this.x = newx; this.y = newy; this.width = newwidth; this.height = newheight; return this; }, // Find my bounding box when I'm rotated with the center of rotation in the center of me. // @return r {rectangle} representing a bounding box bbox: function(angle) { var theta = toRad(angle || 0); var st = abs(sin(theta)); var ct = abs(cos(theta)); var w = this.width * ct + this.height * st; var h = this.width * st + this.height * ct; return rect(this.x + (this.width - w) / 2, this.y + (this.height - h) / 2, w, h); } }; // Ellipse. // -------- function ellipse(c, a, b) { if (!(this instanceof ellipse)) return new ellipse(c, a, b); c = point(c); this.x = c.x; this.y = c.y; this.a = a; this.b = b; } ellipse.prototype = { toString: function() { return point(this.x, this.y).toString() + ' ' + this.a + ' ' + this.b; }, bbox: function() { return rect(this.x - this.a, this.y - this.b, 2*this.a, 2*this.b); }, // Find point on me where line from my center to // point p intersects my boundary. // @param {number} angle If angle is specified, intersection with rotated ellipse is computed. intersectionWithLineFromCenterToPoint: function(p, angle) { p = point(p); if (angle) p.rotate(point(this.x, this.y), angle); var dx = p.x - this.x; var dy = p.y - this.y; var result; if (dx === 0) { result = this.bbox().pointNearestToPoint(p); if (angle) return result.rotate(point(this.x, this.y), -angle); return result; } var m = dy / dx; var mSquared = m * m; var aSquared = this.a * this.a; var bSquared = this.b * this.b; var x = sqrt(1 / ((1 / aSquared) + (mSquared / bSquared))); x = dx < 0 ? -x : x; var y = m * x; result = point(this.x + x, this.y + y); if (angle) return result.rotate(point(this.x, this.y), -angle); return result; } }; // Bezier curve. // ------------- var bezier = { // Cubic Bezier curve path through points. // Ported from C# implementation by Oleg V. Polikarpotchkin and Peter Lee (http://www.codeproject.com/KB/graphics/BezierSpline.aspx). // @param {array} points Array of points through which the smooth line will go. // @return {array} SVG Path commands as an array curveThroughPoints: function(points) { var controlPoints = this.getCurveControlPoints(points); var path = ['M', points[0].x, points[0].y]; for (var i = 0; i < controlPoints[0].length; i++) { path.push('C', controlPoints[0][i].x, controlPoints[0][i].y, controlPoints[1][i].x, controlPoints[1][i].y, points[i+1].x, points[i+1].y); } return path; }, // Get open-ended Bezier Spline Control Points. // @param knots Input Knot Bezier spline points (At least two points!). // @param firstControlPoints Output First Control points. Array of knots.length - 1 length. // @param secondControlPoints Output Second Control points. Array of knots.length - 1 length. getCurveControlPoints: function(knots) { var firstControlPoints = []; var secondControlPoints = []; var n = knots.length - 1; var i; // Special case: Bezier curve should be a straight line. if (n == 1) { // 3P1 = 2P0 + P3 firstControlPoints[0] = point((2 * knots[0].x + knots[1].x) / 3, (2 * knots[0].y + knots[1].y) / 3); // P2 = 2P1 – P0 secondControlPoints[0] = point(2 * firstControlPoints[0].x - knots[0].x, 2 * firstControlPoints[0].y - knots[0].y); return [firstControlPoints, secondControlPoints]; } // Calculate first Bezier control points. // Right hand side vector. var rhs = []; // Set right hand side X values. for (i = 1; i < n - 1; i++) { rhs[i] = 4 * knots[i].x + 2 * knots[i + 1].x; } rhs[0] = knots[0].x + 2 * knots[1].x; rhs[n - 1] = (8 * knots[n - 1].x + knots[n].x) / 2.0; // Get first control points X-values. var x = this.getFirstControlPoints(rhs); // Set right hand side Y values. for (i = 1; i < n - 1; ++i) { rhs[i] = 4 * knots[i].y + 2 * knots[i + 1].y; } rhs[0] = knots[0].y + 2 * knots[1].y; rhs[n - 1] = (8 * knots[n - 1].y + knots[n].y) / 2.0; // Get first control points Y-values. var y = this.getFirstControlPoints(rhs); // Fill output arrays. for (i = 0; i < n; i++) { // First control point. firstControlPoints.push(point(x[i], y[i])); // Second control point. if (i < n - 1) { secondControlPoints.push(point(2 * knots [i + 1].x - x[i + 1], 2 * knots[i + 1].y - y[i + 1])); } else { secondControlPoints.push(point((knots[n].x + x[n - 1]) / 2, (knots[n].y + y[n - 1]) / 2)); } } return [firstControlPoints, secondControlPoints]; }, // Solves a tridiagonal system for one of coordinates (x or y) of first Bezier control points. // @param rhs Right hand side vector. // @return Solution vector. getFirstControlPoints: function(rhs) { var n = rhs.length; // `x` is a solution vector. var x = []; var tmp = []; var b = 2.0; x[0] = rhs[0] / b; // Decomposition and forward substitution. for (var i = 1; i < n; i++) { tmp[i] = 1 / b; b = (i < n - 1 ? 4.0 : 3.5) - tmp[i]; x[i] = (rhs[i] - x[i - 1]) / b; } for (i = 1; i < n; i++) { // Backsubstitution. x[n - i - 1] -= tmp[n - i] * x[n - i]; } return x; }, // Solves an inversion problem -- Given the (x, y) coordinates of a point which lies on // a parametric curve x = x(t)/w(t), y = y(t)/w(t), find the parameter value t // which corresponds to that point. // @param control points (start, control start, control end, end) // @return a function accepts a point and returns t. getInversionSolver: function(p0, p1, p2, p3) { var pts = arguments; function l(i,j) { // calculates a determinant 3x3 // [p.x p.y 1] // [pi.x pi.y 1] // [pj.x pj.y 1] var pi = pts[i], pj = pts[j]; return function(p) { var w = (i % 3 ? 3 : 1) * (j % 3 ? 3 : 1); var lij = p.x * (pi.y - pj.y) + p.y * (pj.x - pi.x) + pi.x * pj.y - pi.y * pj.x; return w * lij; }; } return function solveInversion(p) { var ct = 3 * l(2,3)(p1); var c1 = l(1,3)(p0) / ct; var c2 = -l(2,3)(p0) / ct; var la = c1 * l(3,1)(p) + c2 * (l(3,0)(p) + l(2,1)(p)) + l(2,0)(p); var lb = c1 * l(3,0)(p) + c2 * l(2,0)(p) + l(1,0)(p); return lb / (lb - la); }; }, // Divide a Bezier curve into two at point defined by value 't' <0,1>. // Using deCasteljau algorithm. http://math.stackexchange.com/a/317867 // @param control points (start, control start, control end, end) // @return a function accepts t and returns 2 curves each defined by 4 control points. getCurveDivider: function(p0,p1,p2,p3) { return function divideCurve(t) { var l = line(p0,p1).pointAt(t); var m = line(p1,p2).pointAt(t); var n = line(p2,p3).pointAt(t); var p = line(l,m).pointAt(t); var q = line(m,n).pointAt(t); var r = line(p,q).pointAt(t); return [{ p0: p0, p1: l, p2: p, p3: r }, { p0: r, p1: q, p2: n, p3: p3 }]; } } }; // Scale. var scale = { // Return the `value` from the `domain` interval scaled to the `range` interval. linear: function(domain, range, value) { var domainSpan = domain[1] - domain[0]; var rangeSpan = range[1] - range[0]; return (((value - domain[0]) / domainSpan) * rangeSpan + range[0]) || 0; } }; return { toDeg: toDeg, toRad: toRad, snapToGrid: snapToGrid, normalizeAngle: normalizeAngle, point: point, line: line, rect: rect, ellipse: ellipse, bezier: bezier, scale: scale } })); // JointJS library. // (c) 2011-2013 client IO if (typeof exports === 'object') { var _ = require('lodash'); } // Global namespace. var joint = { // `joint.dia` namespace. dia: {}, // `joint.ui` namespace. ui: {}, // `joint.layout` namespace. layout: {}, // `joint.shapes` namespace. shapes: {}, // `joint.format` namespace. format: {}, // `joint.connectors` namespace. connectors: {}, // `joint.routers` namespace. routers: {}, util: { // Return a simple hash code from a string. See http://werxltd.com/wp/2010/05/13/javascript-implementation-of-javas-string-hashcode-method/. hashCode: function(str) { var hash = 0; if (str.length == 0) return hash; for (var i = 0; i < str.length; i++) { var c = str.charCodeAt(i); hash = ((hash << 5) - hash) + c; hash = hash & hash; // Convert to 32bit integer } return hash; }, getByPath: function(obj, path, delim) { delim = delim || '.'; var keys = path.split(delim); var key; while (keys.length) { key = keys.shift(); if (key in obj) { obj = obj[key]; } else { return undefined; } } return obj; }, setByPath: function(obj, path, value, delim) { delim = delim || '.'; var keys = path.split(delim); var diver = obj; var i = 0; if (path.indexOf(delim) > -1) { for (var len = keys.length; i < len - 1; i++) { // diver creates an empty object if there is no nested object under such a key. // This means that one can populate an empty nested object with setByPath(). diver = diver[keys[i]] || (diver[keys[i]] = {}); } diver[keys[len - 1]] = value; } else { obj[path] = value; } return obj; }, unsetByPath: function(obj, path, delim) { delim = delim || '.'; // index of the last delimiter var i = path.lastIndexOf(delim); if (i > -1) { // unsetting a nested attribute var parent = joint.util.getByPath(obj, path.substr(0, i), delim); if (parent) { delete parent[path.slice(i + 1)]; } } else { // unsetting a primitive attribute delete obj[path]; } return obj; }, flattenObject: function(obj, delim, stop) { delim = delim || '.'; var ret = {}; for (var key in obj) { if (!obj.hasOwnProperty(key)) continue; var shouldGoDeeper = typeof obj[key] === 'object'; if (shouldGoDeeper && stop && stop(obj[key])) { shouldGoDeeper = false; } if (shouldGoDeeper) { var flatObject = this.flattenObject(obj[key], delim, stop); for (var flatKey in flatObject) { if (!flatObject.hasOwnProperty(flatKey)) continue; ret[key + delim + flatKey] = flatObject[flatKey]; } } else { ret[key] = obj[key]; } } return ret; }, uuid: function() { // credit: http://stackoverflow.com/posts/2117523/revisions return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) { var r = Math.random()*16|0, v = c == 'x' ? r : (r&0x3|0x8); return v.toString(16); }); }, // Generate global unique id for obj and store it as a property of the object. guid: function(obj) { this.guid.id = this.guid.id || 1; obj.id = (obj.id === undefined ? 'j_' + this.guid.id++ : obj.id); return obj.id; }, // Copy all the properties to the first argument from the following arguments. // All the properties will be overwritten by the properties from the following // arguments. Inherited properties are ignored. mixin: function() { var target = arguments[0]; for (var i = 1, l = arguments.length; i < l; i++) { var extension = arguments[i]; // Only functions and objects can be mixined. if ((Object(extension) !== extension) && !_.isFunction(extension) && (extension === null || extension === undefined)) { continue; } _.each(extension, function(copy, key) { if (this.mixin.deep && (Object(copy) === copy)) { if (!target[key]) { target[key] = _.isArray(copy) ? [] : {}; } this.mixin(target[key], copy); return; } if (target[key] !== copy) { if (!this.mixin.supplement || !target.hasOwnProperty(key)) { target[key] = copy; } } }, this); } return target; }, // Copy all properties to the first argument from the following // arguments only in case if they don't exists in the first argument. // All the function propererties in the first argument will get // additional property base pointing to the extenders same named // property function's call method. supplement: function() { this.mixin.supplement = true; var ret = this.mixin.apply(this, arguments); this.mixin.supplement = false; return ret; }, // Same as `mixin()` but deep version. deepMixin: function() { this.mixin.deep = true; var ret = this.mixin.apply(this, arguments); this.mixin.deep = false; return ret; }, // Same as `supplement()` but deep version. deepSupplement: function() { this.mixin.deep = this.mixin.supplement = true; var ret = this.mixin.apply(this, arguments); this.mixin.deep = this.mixin.supplement = false; return ret; }, normalizeEvent: function(evt) { return (evt.originalEvent && evt.originalEvent.changedTouches && evt.originalEvent.changedTouches.length) ? evt.originalEvent.changedTouches[0] : evt; }, nextFrame:(function() { var raf; var client = typeof window != 'undefined'; if (client) { raf = window.requestAnimationFrame || window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame || window.oRequestAnimationFrame || window.msRequestAnimationFrame; } if (!raf) { var lastTime = 0; raf = function(callback) { var currTime = new Date().getTime(); var timeToCall = Math.max(0, 16 - (currTime - lastTime)); var id = setTimeout(function() { callback(currTime + timeToCall); }, timeToCall); lastTime = currTime + timeToCall; return id; }; } return client ? _.bind(raf, window) : raf; })(), cancelFrame: (function() { var caf; var client = typeof window != 'undefined'; if (client) { caf = window.cancelAnimationFrame || window.webkitCancelAnimationFrame || window.webkitCancelRequestAnimationFrame || window.msCancelAnimationFrame || window.msCancelRequestAnimationFrame || window.oCancelAnimationFrame || window.oCancelRequestAnimationFrame || window.mozCancelAnimationFrame || window.mozCancelRequestAnimationFrame; } caf = caf || clearTimeout; return client ? _.bind(caf, window) : caf; })(), breakText: function(text, size, styles, opt) { opt = opt || {}; var width = size.width; var height = size.height; var svgDocument = opt.svgDocument || V('svg').node; var textElement = V('<text><tspan></tspan></text>').attr(styles || {}).node; var textSpan = textElement.firstChild; var textNode = document.createTextNode(''); textSpan.appendChild(textNode); svgDocument.appendChild(textElement); if (!opt.svgDocument) { document.body.appendChild(svgDocument); } var words = text.split(' '); var full = []; var lines = []; var p; for (var i = 0, l = 0, len = words.length; i < len; i++) { var word = words[i]; textNode.data = lines[l] ? lines[l] + ' ' + word : word; if (textSpan.getComputedTextLength() <= width) { // the current line fits lines[l] = textNode.data; if (p) { // We were partitioning. Put rest of the word onto next line full[l++] = true; // cancel partitioning p = 0; } } else { if (!lines[l] || p) { var partition = !!p; p = word.length - 1; if (partition || !p) { // word has only one character. if (!p) { if (!lines[l]) { // we won't fit this text within our rect lines = []; break; } // partitioning didn't help on the non-empty line // try again, but this time start with a new line // cancel partitions created words.splice(i,2, word + words[i+1]); // adjust word length len--; full[l++] = true; i--; continue; } // move last letter to the beginning of the next word words[i] = word.substring(0,p); words[i+1] = word.substring(p) + words[i+1]; } else { // We initiate partitioning // split the long word into two words words.splice(i, 1, word.substring(0,p), word.substring(p)); // adjust words length len++; if (l && !full[l-1]) { // if the previous line is not full, try to fit max part of // the current word there l--; } } i--; continue; } l++; i--; } // if size.height is defined we have to check whether the height of the entire // text exceeds the rect height if (typeof height !== 'undefined') { // get line height as text height / 0.8 (as text height is approx. 0.8em // and line height is 1em. See vectorizer.text()) var lh = lh || textElement.getBBox().height * 1.25; if (lh * lines.length > height) { // remove overflowing lines lines.splice(Math.floor(height / lh)); break; } } } if (opt.svgDocument) { // svg document was provided, remove the text element only svgDocument.removeChild(textElement); } else { // clean svg document document.body.removeChild(svgDocument); } return lines.join('\n'); }, timing: { linear: function(t) { return t; }, quad: function(t) { return t * t; }, cubic: function(t) { return t * t * t; }, inout: function(t) { if (t <= 0) return 0; if (t >= 1) return 1; var t2 = t * t, t3 = t2 * t; return 4 * (t < .5 ? t3 : 3 * (t - t2) + t3 - .75); }, exponential: function(t) { return Math.pow(2, 10 * (t - 1)); }, bounce: function(t) { for(var a = 0, b = 1; 1; a += b, b /= 2) { if (t >= (7 - 4 * a) / 11) { var q = (11 - 6 * a - 11 * t) / 4; return -q * q + b * b; } } }, reverse: function(f) { return function(t) { return 1 - f(1 - t) } }, reflect: function(f) { return function(t) { return .5 * (t < .5 ? f(2 * t) : (2 - f(2 - 2 * t))); }; }, clamp: function(f,n,x) { n = n || 0; x = x || 1; return function(t) { var r = f(t); return r < n ? n : r > x ? x : r; } }, back: function(s) { if (!s) s = 1.70158; return function(t) { return t * t * ((s + 1) * t - s); }; }, elastic: function(x) { if (!x) x = 1.5; return function(t) { return Math.pow(2, 10 * (t - 1)) * Math.cos(20*Math.PI*x/3*t); } } }, interpolate: { number: function(a, b) { var d = b - a; return function(t) { return a + d * t; }; }, object: function(a, b) { var s = _.keys(a); return function(t) { var i, p, r = {}; for (i = s.length - 1; i != -1; i--) { p = s[i]; r[p] = a[p] + (b[p] - a[p]) * t; } return r; } }, hexColor: function(a, b) { var ca = parseInt(a.slice(1), 16), cb = parseInt(b.slice(1), 16); var ra = ca & 0x0000ff, rd = (cb & 0x0000ff) - ra; var ga = ca & 0x00ff00, gd = (cb & 0x00ff00) - ga; var ba = ca & 0xff0000, bd = (cb & 0xff0000) - ba; return function(t) { var r = (ra + rd * t) & 0x000000ff; var g = (ga + gd * t) & 0x0000ff00; var b = (ba + bd * t) & 0x00ff0000; return '#' + (1 << 24 | r | g | b ).toString(16).slice(1); }; }, unit: function(a, b) { var r = /(-?[0-9]*.[0-9]*)(px|em|cm|mm|in|pt|pc|%)/; var ma = r.exec(a), mb = r.exec(b); var p = mb[1].indexOf('.'), f = p > 0 ? mb[1].length - p - 1 : 0; var a = +ma[1], d = +mb[1] - a, u = ma[2]; return function(t) { return (a + d * t).toFixed(f) + u; } } }, // SVG filters. filter: { // `x` ... horizontal blur // `y` ... vertical blur (optional) blur: function(args) { var x = _.isFinite(args.x) ? args.x : 2; return _.template('<filter><feGaussianBlur stdDeviation="${stdDeviation}"/></filter>', { stdDeviation: _.isFinite(args.y) ? [x, args.y] : x }); }, // `dx` ... horizontal shift // `dy` ... vertical shift // `blur` ... blur // `color` ... color // `opacity` ... opacity dropShadow: function(args) { var tpl = 'SVGFEDropShadowElement' in window ? '<filter><feDropShadow stdDeviation="${blur}" dx="${dx}" dy="${dy}" flood-color="${color}" flood-opacity="${opacity}"/></filter>' : '<filter><feGaussianBlur in="SourceAlpha" stdDeviation="${blur}"/><feOffset dx="${dx}" dy="${dy}" result="offsetblur"/><feFlood flood-color="${color}"/><feComposite in2="offsetblur" operator="in"/><feComponentTransfer><feFuncA type="linear" slope="${opacity}"/></feComponentTransfer><feMerge><feMergeNode/><feMergeNode in="SourceGraphic"/></feMerge></filter>'; return _.template(tpl, { dx: args.dx || 0, dy: args.dy || 0, opacity: _.isFinite(args.opacity) ? args.opacity : 1, color: args.color || 'black', blur: _.isFinite(args.blur) ? args.blur : 4 }); }, // `amount` ... the proportion of the conversion. A value of 1 is completely grayscale. A value of 0 leaves the input unchanged. grayscale: function(args) { var amount = _.isFinite(args.amount) ? args.amount : 1; return _.template('<filter><feColorMatrix type="matrix" values="${a} ${b} ${c} 0 0 ${d} ${e} ${f} 0 0 ${g} ${b} ${h} 0 0 0 0 0 1 0"/></filter>', { a: 0.2126 + 0.7874 * (1 - amount), b: 0.7152 - 0.7152 * (1 - amount), c: 0.0722 - 0.0722 * (1 - amount), d: 0.2126 - 0.2126 * (1 - amount), e: 0.7152 + 0.2848 * (1 - amount), f: 0.0722 - 0.0722 * (1 - amount), g: 0.2126 - 0.2126 * (1 - amount), h: 0.0722 + 0.9278 * (1 - amount) }); }, // `amount` ... the proportion of the conversion. A value of 1 is completely sepia. A value of 0 leaves the input unchanged. sepia: function(args) { var amount = _.isFinite(args.amount) ? args.amount : 1; return _.template('<filter><feColorMatrix type="matrix" values="${a} ${b} ${c} 0 0 ${d} ${e} ${f} 0 0 ${g} ${h} ${i} 0 0 0 0 0 1 0"/></filter>', { a: 0.393 + 0.607 * (1 - amount), b: 0.769 - 0.769 * (1 - amount), c: 0.189 - 0.189 * (1 - amount), d: 0.349 - 0.349 * (1 - amount), e: 0.686 + 0.314 * (1 - amount), f: 0.168 - 0.168 * (1 - amount), g: 0.272 - 0.272 * (1 - amount), h: 0.534 - 0.534 * (1 - amount), i: 0.131 + 0.869 * (1 - amount) }); }, // `amount` ... the proportion of the conversion. A value of 0 is completely un-saturated. A value of 1 leaves the input unchanged. saturate: function(args) { var amount = _.isFinite(args.amount) ? args.amount : 1; return _.template('<filter><feColorMatrix type="saturate" values="${amount}"/></filter>', { amount: 1 - amount }); }, // `angle` ... the number of degrees around the color circle the input samples will be adjusted. hueRotate: function(args) { return _.template('<filter><feColorMatrix type="hueRotate" values="${angle}"/></filter>', { angle: args.angle || 0 }); }, // `amount` ... the proportion of the conversion. A value of 1 is completely inverted. A value of 0 leaves the input unchanged. invert: function(args) { var amount = _.isFinite(args.amount) ? args.amount : 1; return _.template('<filter><feComponentTransfer><feFuncR type="table" tableValues="${amount} ${amount2}"/><feFuncG type="table" tableValues="${amount} ${amount2}"/><feFuncB type="table" tableValues="${amount} ${amount2}"/></feComponentTransfer></filter>', { amount: amount, amount2: 1 - amount }); }, // `amount` ... proportion of the conversion. A value of 0 will create an image that is completely black. A value of 1 leaves the input unchanged. brightness: function(args) { return _.template('<filter><feComponentTransfer><feFuncR type="linear" slope="${amount}"/><feFuncG type="linear" slope="${amount}"/><feFuncB type="linear" slope="${amount}"/></feComponentTransfer></filter>', { amount: _.isFinite(args.amount) ? args.amount : 1 }); }, // `amount` ... proportion of the conversion. A value of 0 will create an image that is completely black. A value of 1 leaves the input unchanged. contrast: function(args) { var amount = _.isFinite(args.amount) ? args.amount : 1; return _.template('<filter><feComponentTransfer><feFuncR type="linear" slope="${amount}" intercept="${amount2}"/><feFuncG type="linear" slope="${amount}" intercept="${amount2}"/><feFuncB type="linear" slope="${amount}" intercept="${amount2}"/></feComponentTransfer></filter>', { amount: amount, amount2: .5 - amount / 2 }); } }, format: { // Formatting numbers via the Python Format Specification Mini-language. // See http://docs.python.org/release/3.1.3/library/string.html#format-specification-mini-language. // Heavilly inspired by the D3.js library implementation. number: function(specifier, value, locale) { locale = locale || { currency: ['$', ''], decimal: '.', thousands: ',', grouping: [3] }; // See Python format specification mini-language: http://docs.python.org/release/3.1.3/library/string.html#format-specification-mini-language. // [[fill]align][sign][symbol][0][width][,][.precision][type] var re = /(?:([^{])?([<>=^]))?([+\- ])?([$#])?(0)?(\d+)?(,)?(\.-?\d+)?([a-z%])?/i; var match = re.exec(specifier); var fill = match[1] || ' '; var align = match[2] || '>'; var sign = match[3] || ''; var symbol = match[4] || ''; var zfill = match[5]; var width = +match[6]; var comma = match[7]; var precision = match[8]; var type = match[9]; var scale = 1; var prefix = ''; var suffix = ''; var integer = false; if (precision) precision = +precision.substring(1); if (zfill || fill === '0' && align === '=') { zfill = fill = '0'; align = '='; if (comma) width -= Math.floor((width - 1) / 4); } switch (type) { case 'n': comma = true; type = 'g'; break; case '%': scale = 100; suffix = '%'; type = 'f'; break; case 'p': scale = 100; suffix = '%'; type = 'r'; break; case 'b': case 'o': case 'x': case 'X': if (symbol === '#') prefix = '0' + type.toLowerCase(); case 'c': case 'd': integer = true; precision = 0; break; case 's': scale = -1; type = 'r'; break; } if (symbol === '$') { prefix = locale.currency[0]; suffix = locale.currency[1]; } // If no precision is specified for `'r'`, fallback to general notation. if (type == 'r' && !precision) type = 'g'; // Ensure that the requested precision is in the supported range. if (precision != null) { if (type == 'g') precision = Math.max(1, Math.min(21, precision)); else if (type == 'e' || type == 'f') precision = Math.max(0, Math.min(20, precision)); } var zcomma = zfill && comma; // Return the empty string for floats formatted as ints. if (integer && (value % 1)) return ''; // Convert negative to positive, and record the sign prefix. var negative = value < 0 || value === 0 && 1 / value < 0 ? (value = -value, '-') : sign; var fullSuffix = suffix; // Apply the scale, computing it from the value's exponent for si format. // Preserve the existing suffix, if any, such as the currency symbol. if (scale < 0) { var unit = this.prefix(value, precision); value = unit.scale(value); fullSuffix = unit.symbol + suffix; } else { value *= scale; } // Convert to the desired precision. value = this.convert(type, value, precision); // Break the value into the integer part (before) and decimal part (after). var i = value.lastIndexOf('.'); var before = i < 0 ? value : value.substring(0, i); var after = i < 0 ? '' : locale.decimal + value.substring(i + 1); function formatGroup(value) { var i = value.length; var t = []; var j = 0; var g = locale.grouping[0]; while (i > 0 && g > 0) { t.push(value.substring(i -= g, i + g)); g = locale.grouping[j = (j + 1) % locale.grouping.length]; } return t.reverse().join(locale.thousands); } // If the fill character is not `'0'`, grouping is applied before padding. if (!zfill && comma && locale.grouping) { before = formatGroup(before); } var length = prefix.length + before.length + after.length + (zcomma ? 0 : negative.length); var padding = length < width ? new Array(length = width - length + 1).join(fill) : ''; // If the fill character is `'0'`, grouping is applied after padding. if (zcomma) before = formatGroup(padding + before); // Apply prefix. negative += prefix; // Rejoin integer and decimal parts. value = before + after; return (align === '<' ? negative + value + padding : align === '>' ? padding + negative + value : align === '^' ? padding.substring(0, length >>= 1) + negative + value + padding.substring(length) : negative + (zcomma ? value : padding + value)) + fullSuffix; }, convert: function(type, value, precision) { switch (type) { case 'b': return value.toString(2); case 'c': return String.fromCharCode(value); case 'o': return value.toString(8); case 'x': return value.toString(16); case 'X': return value.toString(16).toUpperCase(); case 'g': return value.toPrecision(precision); case 'e': return value.toExponential(precision); case 'f': return value.toFixed(precision); case 'r': return (value = this.round(value, this.precision(value, precision))).toFixed(Math.max(0, Math.min(20, this.precision(value * (1 + 1e-15), precision)))); default: return value + ''; } }, round: function(value, precision) { return precision ? Math.round(value * (precision = Math.pow(10, precision))) / precision : Math.round(value); }, precision: function(value, precision) { return precision - (value ? Math.ceil(Math.log(value) / Math.LN10) : 1); }, prefix: function(value, precision) { var prefixes = _.map(['y','z','a','f','p','n','µ','m','','k','M','G','T','P','E','Z','Y'], function(d, i) { var k = Math.pow(10, abs(8 - i) * 3); return { scale: i > 8 ? function(d) { return d / k; } : function(d) { return d * k; }, symbol: d }; }); var i = 0; if (value) { if (value < 0) value *= -1; if (precision) value = d3.round(value, this.precision(value, precision)); i = 1 + Math.floor(1e-12 + Math.log(value) / Math.LN10); i = Math.max(-24, Math.min(24, Math.floor((i <= 0 ? i + 1 : i - 1) / 3) * 3)); } return prefixes[8 + i / 3]; } } } }; if (typeof exports === 'object') { module.exports = joint; } // JointJS, the JavaScript diagramming library. // (c) 2011-2013 client IO if (typeof exports === 'object') { var joint = { dia: { Link: require('./joint.dia.link').Link, Element: require('./joint.dia.element').Element }, shapes: require('../plugins/shapes') }; var Backbone = require('backbone'); var _ = require('lodash'); var g = require('./geometry'); } joint.dia.GraphCells = Backbone.Collection.extend({ initialize: function() { // Backbone automatically doesn't trigger re-sort if models attributes are changed later when // they're already in the collection. Therefore, we're triggering sort manually here. this.on('change:z', this.sort, this); }, model: function(attrs, options) { if (attrs.type === 'link') { return new joint.dia.Link(attrs, options); } var module = attrs.type.split('.')[0]; var entity = attrs.type.split('.')[1]; if (joint.shapes[module] && joint.shapes[module][entity]) { return new joint.shapes[module][entity](attrs, options); } return new joint.dia.Element(attrs, options); }, // `comparator` makes it easy to sort cells based on their `z` index. comparator: function(model) { return model.get('z') || 0; }, // Get all inbound and outbound links connected to the cell `model`. getConnectedLinks: function(model, opt) { opt = opt || {}; if (_.isUndefined(opt.inbound) && _.isUndefined(opt.outbound)) { opt.inbound = opt.outbound = true; } var links = []; this.each(function(cell) { var source = cell.get('source'); var target = cell.get('target'); if (source && source.id === model.id && opt.outbound) { links.push(cell); } if (target && target.id === model.id && opt.inbound) { links.push(cell); } }); return links; } }); joint.dia.Graph = Backbone.Model.extend({ initialize: function() { this.set('cells', new joint.dia.GraphCells); // Make all the events fired in the `cells` collection available. // to the outside world. this.get('cells').on('all', this.trigger, this); this.get('cells').on('remove', this.removeCell, this); }, toJSON: function() { // Backbone does not recursively call `toJSON()` on attributes that are themselves models/collections. // It just clones the attributes. Therefore, we must call `toJSON()` on the cells collection explicitely. var json = Backbone.Model.prototype.toJSON.apply(this, arguments); json.cells = this.get('cells').toJSON(); return json; }, fromJSON: function(json, opt) { if (!json.cells) { throw new Error('Graph JSON must contain cells array.'); } this.set(_.omit(json, 'cells'), opt); this.resetCells(json.cells, opt); }, clear: function(opt) { this.trigger('batch:start'); this.get('cells').remove(this.get('cells').models, opt); this.trigger('batch:stop'); }, _prepareCell: function(cell) { if (cell instanceof Backbone.Model && _.isUndefined(cell.get('z'))) { cell.set('z', this.maxZIndex() + 1, { silent: true }); } else if (_.isUndefined(cell.z)) { cell.z = this.maxZIndex() + 1; } return cell; }, maxZIndex: function() { var lastCell = this.get('cells').last(); return lastCell ? (lastCell.get('z') || 0) : 0; }, addCell: function(cell, options) { if (_.isArray(cell)) { return this.addCells(cell, options); } this.get('cells').add(this._prepareCell(cell), options || {}); return this; }, addCells: function(cells, options) { _.each(cells, function(cell) { this.addCell(cell, options); }, this); return this; }, // When adding a lot of cells, it is much more efficient to // reset the entire cells collection in one go. // Useful for bulk operations and optimizations. resetCells: function(cells, opt) { this.get('cells').reset(_.map(cells, this._prepareCell, this), opt); return this; }, removeCell: function(cell, collection, options) { // Applications might provide a `disconnectLinks` option set to `true` in order to // disconnect links when a cell is removed rather then removing them. The default // is to remove all the associated links. if (options && options.disconnectLinks) { this.disconnectLinks(cell); } else { this.removeLinks(cell); } // Silently remove the cell from the cells collection. Silently, because // `joint.dia.Cell.prototype.remove` already triggers the `remove` event which is // then propagated to the graph model. If we didn't remove the cell silently, two `remove` events // would be triggered on the graph model. this.get('cells').remove(cell, { silent: true }); }, // Get a cell by `id`. getCell: function(id) { return this.get('cells').get(id); }, getElements: function() { return this.get('cells').filter(function(cell) { return cell instanceof joint.dia.Element; }); }, getLinks: function() { return this.get('cells').filter(function(cell) { return cell instanceof joint.dia.Link; }); }, // Get all inbound and outbound links connected to the cell `model`. getConnectedLinks: function(model, opt) { return this.get('cells').getConnectedLinks(model, opt); }, getNeighbors: function(el) { var links = this.getConnectedLinks(el); var neighbors = []; var cells = this.get('cells'); _.each(links, function(link) { var source = link.get('source'); var target = link.get('target'); // Discard if it is a point. if (!source.x) { var sourceElement = cells.get(source.id); if (sourceElement !== el) { neighbors.push(sourceElement); } } if (!target.x) { var targetElement = cells.get(target.id); if (targetElement !== el) { neighbors.push(targetElement); } } }); return neighbors; }, // Disconnect links connected to the cell `model`. disconnectLinks: function(model) { _.each(this.getConnectedLinks(model), function(link) { link.set(link.get('source').id === model.id ? 'source' : 'target', g.point(0, 0)); }); }, // Remove links connected to the cell `model` completely. removeLinks: function(model) { _.invoke(this.getConnectedLinks(model), 'remove'); }, // Find all views at given point findModelsFromPoint: function(p) { return _.filter(this.getElements(), function(el) { return el.getBBox().containsPoint(p); }); }, // Find all views in given area findModelsInArea: function(r) { return _.filter(this.getElements(), function(el) { return el.getBBox().intersect(r); }); }, // Return the bounding box of all `elements`. getBBox: function(elements) { var origin = { x: Infinity, y: Infinity }; var corner = { x: 0, y: 0 }; _.each(elements, function(cell) { var bbox = cell.getBBox(); origin.x = Math.min(origin.x, bbox.x); origin.y = Math.min(origin.y, bbox.y); corner.x = Math.max(corner.x, bbox.x + bbox.width); corner.y = Math.max(corner.y, bbox.y + bbox.height); }); return g.rect(origin.x, origin.y, corner.x - origin.x, corner.y - origin.y); } }); if (typeof exports === 'object') { module.exports.Graph = joint.dia.Graph; } // JointJS. // (c) 2011-2013 client IO if (typeof exports === 'object') { var joint = { util: require('./core').util, dia: { Link: require('./joint.dia.link').Link } }; var Backbone = require('backbone'); var _ = require('lodash'); } // joint.dia.Cell base model. // -------------------------- joint.dia.Cell = Backbone.Model.extend({ // This is the same as Backbone.Model with the only difference that is uses _.merge // instead of just _.extend. The reason is that we want to mixin attributes set in upper classes. constructor: function(attributes, options) { var defaults; var attrs = attributes || {}; this.cid = _.uniqueId('c'); this.attributes = {}; if (options && options.collection) this.collection = options.collection; if (options && options.parse) attrs = this.parse(attrs, options) || {}; if (defaults = _.result(this, 'defaults')) { //<custom code> // Replaced the call to _.defaults with _.merge. attrs = _.merge({}, defaults, attrs); //</custom code> } this.set(attrs, options); this.changed = {}; this.initialize.apply(this, arguments); }, toJSON: function() { var defaultAttrs = this.constructor.prototype.defaults.attrs || {}; var attrs = this.attributes.attrs; var finalAttrs = {}; // Loop through all the attributes and // omit the default attributes as they are implicitly reconstructable by the cell 'type'. _.each(attrs, function(attr, selector) { var defaultAttr = defaultAttrs[selector]; _.each(attr, function(value, name) { // attr is mainly flat though it might have one more level (consider the `style` attribute). // Check if the `value` is object and if yes, go one level deep. if (_.isObject(value) && !_.isArray(value)) { _.each(value, function(value2, name2) { if (!defaultAttr || !defaultAttr[name] || !_.isEqual(defaultAttr[name][name2], value2)) { finalAttrs[selector] = finalAttrs[selector] || {}; (finalAttrs[selector][name] || (finalAttrs[selector][name] = {}))[name2] = value2; } }); } else if (!defaultAttr || !_.isEqual(defaultAttr[name], value)) { // `value` is not an object, default attribute for such a selector does not exist // or it is different than the attribute value set on the model. finalAttrs[selector] = finalAttrs[selector] || {}; finalAttrs[selector][name] = value; } }); }); var attributes = _.cloneDeep(_.omit(this.attributes, 'attrs')); //var attributes = JSON.parse(JSON.stringify(_.omit(this.attributes, 'attrs'))); attributes.attrs = finalAttrs; return attributes; }, initialize: function(options) { if (!options || !options.id) { this.set('id', joint.util.uuid(), { silent: true }); } this._transitionIds = {}; // Collect ports defined in `attrs` and keep collecting whenever `attrs` object changes. this.processPorts(); this.on('change:attrs', this.processPorts, this); }, processPorts: function() { // Whenever `attrs` changes, we extract ports from the `attrs` object and store it // in a more accessible way. Also, if any port got removed and there were links that had `target`/`source` // set to that port, we remove those links as well (to follow the same behaviour as // with a removed element). var previousPorts = this.ports; // Collect ports from the `attrs` object. var ports = {}; _.each(this.get('attrs'), function(attrs, selector) { if (attrs && attrs.port) { // `port` can either be directly an `id` or an object containing an `id` (and potentially other data). if (!_.isUndefined(attrs.port.id)) { ports[attrs.port.id] = attrs.port; } else { ports[attrs.port] = { id: attrs.port }; } } }); // Collect ports that have been removed (compared to the previous ports) - if any. // Use hash table for quick lookup. var removedPorts = {}; _.each(previousPorts, function(port, id) { if (!ports[id]) removedPorts[id] = true; }); // Remove all the incoming/outgoing links that have source/target port set to any of the removed ports. if (this.collection && !_.isEmpty(removedPorts)) { var inboundLinks = this.collection.getConnectedLinks(this, { inbound: true }); _.each(inboundLinks, function(link) { if (removedPorts[link.get('target').port]) link.remove(); }); var outboundLinks = this.collection.getConnectedLinks(this, { outbound: true }); _.each(outboundLinks, function(link) { if (removedPorts[link.get('source').port]) link.remove(); }); } // Update the `ports` object. this.ports = ports; }, remove: function(options) { var collection = this.collection; if (collection) { collection.trigger('batch:start'); } // First, unembed this cell from its parent cell if there is one. var parentCellId = this.get('parent'); if (parentCellId) { var parentCell = this.collection && this.collection.get(parentCellId); parentCell.unembed(this); } _.invoke(this.getEmbeddedCells(), 'remove', options); this.trigger('remove', this, this.collection, options); if (collection) { collection.trigger('batch:stop'); } return this; }, toFront: function() { if (this.collection) { this.set('z', (this.collection.last().get('z') || 0) + 1); } return this; }, toBack: function() { if (this.collection) { this.set('z', (this.collection.first().get('z') || 0) - 1); } return this; }, embed: function(cell) { if (this.get('parent') == cell.id) { throw new Error('Recursive embedding not allowed.'); } else { this.trigger('batch:start'); cell.set('parent', this.id); this.set('embeds', _.uniq((this.get('embeds') || []).concat([cell.id]))); this.trigger('batch:stop'); } return this; }, unembed: function(cell) { this.trigger('batch:start'); var cellId = cell.id; cell.unset('parent'); this.set('embeds', _.without(this.get('embeds'), cellId)); this.trigger('batch:stop'); return this; }, getEmbeddedCells: function() { // Cell models can only be retrieved when this element is part of a collection. // There is no way this element knows about other cells otherwise. // This also means that calling e.g. `translate()` on an element with embeds before // adding it to a graph does not translate its embeds. if (this.collection) { return _.map(this.get('embeds') || [], function(cellId) { return this.collection.get(cellId); }, this); } return []; }, clone: function(opt) { opt = opt || {}; var clone = Backbone.Model.prototype.clone.apply(this, arguments); // We don't want the clone to have the same ID as the original. clone.set('id', joint.util.uuid(), { silent: true }); clone.set('embeds', ''); if (!opt.deep) return clone; // The rest of the `clone()` method deals with embeds. If `deep` option is set to `true`, // the return value is an array of all the embedded clones created. var embeds = _.sortBy(this.getEmbeddedCells(), function(cell) { // Sort embeds that links come before elements. return cell instanceof joint.dia.Element; }); var clones = [clone]; // This mapping stores cloned links under the `id`s of they originals. // This prevents cloning a link more then once. Consider a link 'self loop' for example. var linkCloneMapping = {}; _.each(embeds, function(embed) { var embedClones = embed.clone({ deep: true }); // Embed the first clone returned from `clone({ deep: true })` above. The first // cell is always the clone of the cell that called the `clone()` method, i.e. clone of `embed` in this case. clone.embed(embedClones[0]); _.each(embedClones, function(embedClone) { if (embedClone instanceof joint.dia.Link) { if (embedClone.get('source').id == this.id) { var source = _.clone(embedClone.get('source')); source.id = clone.id; embedClone.set('source', source); } if (embedClone.get('target').id == this.id) { var target = _.clone(embedClone.get('target')); target.id = clone.id; embedClone.set('target', target); } linkCloneMapping[embed.id] = embedClone; // Skip links. Inbound/outbound links are not relevant for them. return; } clones.push(embedClone); // Collect all inbound links, clone them (if not done already) and set their target to the `embedClone.id`. var inboundLinks = this.collection.getConnectedLinks(embed, { inbound: true }); _.each(inboundLinks, function(link) { var linkClone = linkCloneMapping[link.id] || link.clone(); // Make sure we don't clone a link more then once. linkCloneMapping[link.id] = linkClone; var target = _.clone(linkClone.get('target')); target.id = embedClone.id; linkClone.set('target', target); }); // Collect all inbound links, clone them (if not done already) and set their source to the `embedClone.id`. var outboundLinks = this.collection.getConnectedLinks(embed, { outbound: true }); _.each(outboundLinks, function(link) { var linkClone = linkCloneMapping[link.id] || link.clone(); // Make sure we don't clone a link more then once. linkCloneMapping[link.id] = linkClone; var source = _.clone(linkClone.get('source')); source.id = embedClone.id; linkClone.set('source', source); }); }, this); }, this); // Add link clones to the array of all the new clones. clones = clones.concat(_.values(linkCloneMapping)); return clones; }, // A convenient way to set nested attributes. attr: function(attrs, value, opt) { var currentAttrs = this.get('attrs'); var delim = '/'; if (_.isString(attrs)) { // Get/set an attribute by a special path syntax that delimits // nested objects by the colon character. if (typeof value != 'undefined') { var attr = {}; joint.util.setByPath(attr, attrs, value, delim); return this.set('attrs', _.merge({}, currentAttrs, attr), opt); } else { return joint.util.getByPath(currentAttrs, attrs, delim); } } return this.set('attrs', _.merge({}, currentAttrs, attrs), value, opt); }, // A convenient way to unset nested attributes removeAttr: function(path, opt) { if (_.isArray(path)) { _.each(path, function(p) { this.removeAttr(p, opt); }, this); return this; } var attrs = joint.util.unsetByPath(_.merge({}, this.get('attrs')), path, '/'); return this.set('attrs', attrs, _.extend({ dirty: true }, opt)); }, transition: function(path, value, opt, delim) { delim = delim || '/'; var defaults = { duration: 100, delay: 10, timingFunction: joint.util.timing.linear, valueFunction: joint.util.interpolate.number }; opt = _.extend(defaults, opt); var pathArray = path.split(delim); var property = pathArray[0]; var isPropertyNested = pathArray.length > 1; var firstFrameTime = 0; var interpolatingFunction; var setter = _.bind(function(runtime) { var id, progress, propertyValue, status; firstFrameTime = firstFrameTime || runtime; runtime -= firstFrameTime; progress = runtime / opt.duration; if (progress < 1) { this._transitionIds[path] = id = joint.util.nextFrame(setter); } else { progress = 1; delete this._transitionIds[path]; } propertyValue = interpolatingFunction(opt.timingFunction(progress)); if (isPropertyNested) { var nestedPropertyValue = joint.util.setByPath({}, path, propertyValue, delim)[property]; propertyValue = _.merge({}, this.get(property), nestedPropertyValue); } opt.transitionId = id; this.set(property, propertyValue, opt); if (!id) this.trigger('transition:end', this, path); }, this); var initiator =_.bind(function(callback) { this.stopTransitions(path); interpolatingFunction = opt.valueFunction(joint.util.getByPath(this.attributes, path, delim), value); this._transitionIds[path] = joint.util.nextFrame(callback); this.trigger('transition:start', this, path); }, this); return _.delay(initiator, opt.delay, setter); }, getTransitions: function() { return _.keys(this._transitionIds); }, stopTransitions: function(path, delim) { delim = delim || '/'; var pathArray = path && path.split(delim); _(this._transitionIds).keys().filter(pathArray && function(key) { return _.isEqual(pathArray, key.split(delim).slice(0, pathArray.length)); }).each(function(key) { joint.util.cancelFrame(this._transitionIds[key]); delete this._transitionIds[key]; this.trigger('transition:end', this, key); }, this); return this; }, // A shorcut making it easy to create constructs like the following: // `var el = (new joint.shapes.basic.Rect).addTo(graph)`. addTo: function(graph) { graph.addCell(this); return this; } }); // joint.dia.CellView base view and controller. // -------------------------------------------- // This is the base view and controller for `joint.dia.ElementView` and `joint.dia.LinkView`. joint.dia.CellView = Backbone.View.extend({ tagName: 'g', attributes: function() { return { 'model-id': this.model.id } }, constructor: function(options) { this._configure(options); Backbone.View.apply(this, arguments); }, _configure: function(options) { if (this.options) options = _.extend({}, _.result(this, 'options'), options); this.options = options; // Make sure a global unique id is assigned to this view. Store this id also to the properties object. // The global unique id makes sure that the same view can be rendered on e.g. different machines and // still be associated to the same object among all those clients. This is necessary for real-time // collaboration mechanism. this.options.id = this.options.id || joint.util.guid(this); }, initialize: function() { _.bindAll(this, 'remove', 'update'); // Store reference to this to the <g> DOM element so that the view is accessible through the DOM tree. this.$el.data('view', this); this.listenTo(this.model, 'remove', this.remove); this.listenTo(this.model, 'change:attrs', this.onChangeAttrs); }, onChangeAttrs: function(cell, attrs, opt) { if (opt.dirty) { // dirty flag could be set when a model attribute was removed and it needs to be cleared // also from the DOM element. See cell.removeAttr(). return this.render(); } return this.update(); }, // Override the Backbone `_ensureElement()` method in order to create a `<g>` node that wraps // all the nodes of the Cell view. _ensureElement: function() { var el; if (!this.el) { var attrs = _.extend({ id: this.id }, _.result(this, 'attributes')); if (this.className) attrs['class'] = _.result(this, 'className'); el = V(_.result(this, 'tagName'), attrs).node; } else { el = _.result(this, 'el') } this.setElement(el, false); }, findBySelector: function(selector) { // These are either descendants of `this.$el` of `this.$el` itself. // `.` is a special selector used to select the wrapping `<g>` element. var $selected = selector === '.' ? this.$el : this.$el.find(selector); return $selected; }, notify: function(evt) { if (this.paper) { var args = Array.prototype.slice.call(arguments, 1); // Trigger the event on both the element itself and also on the paper. this.trigger.apply(this, [evt].concat(args)); // Paper event handlers receive the view object as the first argument. this.paper.trigger.apply(this.paper, [evt, this].concat(args)); } }, getStrokeBBox: function(el) { // Return a bounding box rectangle that takes into account stroke. // Note that this is a naive and ad-hoc implementation that does not // works only in certain cases and should be replaced as soon as browsers will // start supporting the getStrokeBBox() SVG method. // @TODO any better solution is very welcome! var isMagnet = !!el; el = el || this.el; var bbox = V(el).bbox(false, this.paper.viewport); var strokeWidth; if (isMagnet) { strokeWidth = V(el).attr('stroke-width'); } else { strokeWidth = this.model.attr('rect/stroke-width') || this.model.attr('circle/stroke-width') || this.model.attr('ellipse/stroke-width') || this.model.attr('path/stroke-width'); } strokeWidth = parseFloat(strokeWidth) || 0; return g.rect(bbox).moveAndExpand({ x: -strokeWidth/2, y: -strokeWidth/2, width: strokeWidth, height: strokeWidth }); }, getBBox: function() { return V(this.el).bbox(); }, highlight: function(el) { el = !el ? this.el : this.$(el)[0] || this.el; V(el).addClass('highlighted'); }, unhighlight: function(el) { el = !el ? this.el : this.$(el)[0] || this.el; V(el).removeClass('highlighted'); }, // Find the closest element that has the `magnet` attribute set to `true`. If there was not such // an element found, return the root element of the cell view. findMagnet: function(el) { var $el = this.$(el); if ($el.length === 0 || $el[0] === this.el) { // If the overall cell has set `magnet === false`, then return `undefined` to // announce there is no magnet found for this cell. // This is especially useful to set on cells that have 'ports'. In this case, // only the ports have set `magnet === true` and the overall element has `magnet === false`. var attrs = this.model.get('attrs') || {}; if (attrs['.'] && attrs['.']['magnet'] === false) { return undefined; } return this.el; } if ($el.attr('magnet')) { return $el[0]; } return this.findMagnet($el.parent()); }, // `selector` is a CSS selector or `'.'`. `filter` must be in the special JointJS filter format: // `{ name: <name of the filter>, args: { <arguments>, ... }`. // An example is: `{ filter: { name: 'blur', args: { radius: 5 } } }`. applyFilter: function(selector, filter) { var $selected = this.findBySelector(selector); // Generate a hash code from the stringified filter definition. This gives us // a unique filter ID for different definitions. var filterId = filter.name + this.paper.svg.id + joint.util.hashCode(JSON.stringify(filter)); // If the filter already exists in the document, // we're done and we can just use it (reference it using `url()`). // If not, create one. if (!this.paper.svg.getElementById(filterId)) { var filterSVGString = joint.util.filter[filter.name] && joint.util.filter[filter.name](filter.args || {}); if (!filterSVGString) { throw new Error('Non-existing filter ' + filter.name); } var filterElement = V(filterSVGString); filterElement.attr('filterUnits', 'userSpaceOnUse'); if (filter.attrs) filterElement.attr(filter.attrs); filterElement.node.id = filterId; V(this.paper.svg).defs().append(filterElement); } $selected.each(function() { V(this).attr('filter', 'url(#' + filterId + ')'); }); }, // `selector` is a CSS selector or `'.'`. `attr` is either a `'fill'` or `'stroke'`. // `gradient` must be in the special JointJS gradient format: // `{ type: <linearGradient|radialGradient>, stops: [ { offset: <offset>, color: <color> }, ... ]`. // An example is: `{ fill: { type: 'linearGradient', stops: [ { offset: '10%', color: 'green' }, { offset: '50%', color: 'blue' } ] } }`. applyGradient: function(selector, attr, gradient) { var $selected = this.findBySelector(selector); // Generate a hash code from the stringified filter definition. This gives us // a unique filter ID for different definitions. var gradientId = gradient.type + this.paper.svg.id + joint.util.hashCode(JSON.stringify(gradient)); // If the gradient already exists in the document, // we're done and we can just use it (reference it using `url()`). // If not, create one. if (!this.paper.svg.getElementById(gradientId)) { var gradientSVGString = [ '<' + gradient.type + '>', _.map(gradient.stops, function(stop) { return '<stop offset="' + stop.offset + '" stop-color="' + stop.color + '" stop-opacity="' + (_.isFinite(stop.opacity) ? stop.opacity : 1) + '" />' }).join(''), '</' + gradient.type + '>' ].join(''); var gradientElement = V(gradientSVGString); if (gradient.attrs) { gradientElement.attr(gradient.attrs); } gradientElement.node.id = gradientId; V(this.paper.svg).defs().append(gradientElement); } $selected.each(function() { V(this).attr(attr, 'url(#' + gradientId + ')'); }); }, // Construct a unique selector for the `el` element within this view. // `selector` is being collected through the recursive call. No value for `selector` is expected when using this method. getSelector: function(el, selector) { if (el === this.el) { return selector; } var index = $(el).index(); selector = el.tagName + ':nth-child(' + (index + 1) + ')' + ' ' + (selector || ''); return this.getSelector($(el).parent()[0], selector + ' '); }, // Interaction. The controller part. // --------------------------------- // Interaction is handled by the paper and delegated to the view in interest. // `x` & `y` parameters passed to these functions represent the coordinates already snapped to the paper grid. // If necessary, real coordinates can be obtained from the `evt` event object. // These functions are supposed to be overriden by the views that inherit from `joint.dia.Cell`, // i.e. `joint.dia.Element` and `joint.dia.Link`. pointerdblclick: function(evt, x, y) { this.notify('cell:pointerdblclick', evt, x, y); }, pointerclick: function(evt, x, y) { this.notify('cell:pointerclick', evt, x, y); }, pointerdown: function(evt, x, y) { if (this.model.collection) { this.model.trigger('batch:start'); this._collection = this.model.collection; } this.notify('cell:pointerdown', evt, x, y); }, pointermove: function(evt, x, y) { this.notify('cell:pointermove', evt, x, y); }, pointerup: function(evt, x, y) { this.notify('cell:pointerup', evt, x, y); if (this._collection) { // we don't want to trigger event on model as model doesn't // need to be member of collection anymore (remove) this._collection.trigger('batch:stop'); delete this._collection; } } }); if (typeof exports === 'object') { module.exports.Cell = joint.dia.Cell; module.exports.CellView = joint.dia.CellView; } // JointJS library. // (c) 2011-2013 client IO if (typeof exports === 'object') { var joint = { util: require('./core').util, dia: { Cell: require('./joint.dia.cell').Cell, CellView: require('./joint.dia.cell').CellView } }; var Backbone = require('backbone'); var _ = require('lodash'); } // joint.dia.Element base model. // ----------------------------- joint.dia.Element = joint.dia.Cell.extend({ defaults: { position: { x: 0, y: 0 }, size: { width: 1, height: 1 }, angle: 0 }, position: function(x, y) { this.set('position', { x: x, y: y }); }, translate: function(tx, ty, opt) { ty = ty || 0; if (tx === 0 && ty === 0) { // Like nothing has happened. return this; } var position = this.get('position') || { x: 0, y: 0 }; var translatedPosition = { x: position.x + tx || 0, y: position.y + ty || 0 }; if (opt && opt.transition) { if (!_.isObject(opt.transition)) opt.transition = {}; this.transition('position', translatedPosition, _.extend({}, opt.transition, { valueFunction: joint.util.interpolate.object })); } else { this.set('position', translatedPosition, opt); // Recursively call `translate()` on all the embeds cells. _.invoke(this.getEmbeddedCells(), 'translate', tx, ty, opt); } return this; }, resize: function(width, height) { this.trigger('batch:start'); this.set('size', { width: width, height: height }); this.trigger('batch:stop'); return this; }, // Rotate element by `angle` degrees, optionally around `origin` point. // If `origin` is not provided, it is considered to be the center of the element. // If `absolute` is `true`, the `angle` is considered is abslute, i.e. it is not // the difference from the previous angle. rotate: function(angle, absolute, origin) { if (origin) { var center = this.getBBox().center(); var size = this.get('size'); var position = this.get('position'); center.rotate(origin, (this.get('angle') || 0) - angle); var dx = center.x - size.width/2 - position.x; var dy = center.y - size.height/2 - position.y; this.trigger('batch:start'); this.translate(dx, dy); this.rotate(angle, absolute); this.trigger('batch:stop'); } else { this.set('angle', absolute ? angle : ((this.get('angle') || 0) + angle) % 360); } return this; }, getBBox: function() { var position = this.get('position'); var size = this.get('size'); return g.rect(position.x, position.y, size.width, size.height); } }); // joint.dia.Element base view and controller. // ------------------------------------------- joint.dia.ElementView = joint.dia.CellView.extend({ className: function() { return 'element ' + this.model.get('type').split('.').join(' '); }, initialize: function() { _.bindAll(this, 'translate', 'resize', 'rotate'); joint.dia.CellView.prototype.initialize.apply(this, arguments); this.listenTo(this.model, 'change:position', this.translate); this.listenTo(this.model, 'change:size', this.resize); this.listenTo(this.model, 'change:angle', this.rotate); }, // Default is to process the `attrs` object and set attributes on subelements based on the selectors. update: function(cell, renderingOnlyAttrs) { var allAttrs = this.model.get('attrs'); var rotatable = V(this.$('.rotatable')[0]); if (rotatable) { var rotation = rotatable.attr('transform'); rotatable.attr('transform', ''); } var relativelyPositioned = []; _.each(renderingOnlyAttrs || allAttrs, function(attrs, selector) { // Elements that should be updated. var $selected = this.findBySelector(selector); // No element matched by the `selector` was found. We're done then. if ($selected.length === 0) return; // Special attributes are treated by JointJS, not by SVG. var specialAttributes = ['style', 'text', 'html', 'ref-x', 'ref-y', 'ref-dx', 'ref-dy', 'ref-width', 'ref-height', 'ref', 'x-alignment', 'y-alignment', 'port']; // If the `filter` attribute is an object, it is in the special JointJS filter format and so // it becomes a special attribute and is treated separately. if (_.isObject(attrs.filter)) { specialAttributes.push('filter'); this.applyFilter(selector, attrs.filter); } // If the `fill` or `stroke` attribute is an object, it is in the special JointJS gradient format and so // it becomes a special attribute and is treated separately. if (_.isObject(attrs.fill)) { specialAttributes.push('fill'); this.applyGradient(selector, 'fill', attrs.fill); } if (_.isObject(attrs.stroke)) { specialAttributes.push('stroke'); this.applyGradient(selector, 'stroke', attrs.stroke); } // Make special case for `text` attribute. So that we can set text content of the `<text>` element // via the `attrs` object as well. // Note that it's important to set text before applying the rest of the final attributes. // Vectorizer `text()` method sets on the element its own attributes and it has to be possible // to rewrite them, if needed. (i.e display: 'none') if (!_.isUndefined(attrs.text)) { $selected.each(function() { V(this).text(attrs.text + '', { lineHeight: attrs.lineHeight }); }); } // Set regular attributes on the `$selected` subelement. Note that we cannot use the jQuery attr() // method as some of the attributes might be namespaced (e.g. xlink:href) which fails with jQuery attr(). var finalAttributes = _.omit(attrs, specialAttributes); $selected.each(function() { V(this).attr(finalAttributes); }); // `port` attribute contains the `id` of the port that the underlying magnet represents. if (attrs.port) { $selected.attr('port', _.isUndefined(attrs.port.id) ? attrs.port : attrs.port.id); } // `style` attribute is special in the sense that it sets the CSS style of the subelement. if (attrs.style) { $selected.css(attrs.style); } if (!_.isUndefined(attrs.html)) { $selected.each(function() { $(this).html(attrs.html + ''); }); } // Special `ref-x` and `ref-y` attributes make it possible to set both absolute or // relative positioning of subelements. if (!_.isUndefined(attrs['ref-x']) || !_.isUndefined(attrs['ref-y']) || !_.isUndefined(attrs['ref-dx']) || !_.isUndefined(attrs['ref-dy']) || !_.isUndefined(attrs['x-alignment']) || !_.isUndefined(attrs['y-alignment']) || !_.isUndefined(attrs['ref-width']) || !_.isUndefined(attrs['ref-height']) ) { _.each($selected, function(el, index, list) { var $el = $(el); // copy original list selector to the element $el.selector = list.selector; relativelyPositioned.push($el); }); } }, this); // We don't want the sub elements to affect the bounding box of the root element when // positioning the sub elements relatively to the bounding box. //_.invoke(relativelyPositioned, 'hide'); //_.invoke(relativelyPositioned, 'show'); // Note that we're using the bounding box without transformation because we are already inside // a transformed coordinate system. var bbox = this.el.getBBox(); renderingOnlyAttrs = renderingOnlyAttrs || {}; _.each(relativelyPositioned, function($el) { // if there was a special attribute affecting the position amongst renderingOnlyAttributes // we have to merge it with rest of the element's attributes as they are necessary // to update the position relatively (i.e `ref`) var renderingOnlyElAttrs = renderingOnlyAttrs[$el.selector]; var elAttrs = renderingOnlyElAttrs ? _.merge({}, allAttrs[$el.selector], renderingOnlyElAttrs) : allAttrs[$el.selector]; this.positionRelative($el, bbox, elAttrs); }, this); if (rotatable) { rotatable.attr('transform', rotation || ''); } }, positionRelative: function($el, bbox, elAttrs) { var ref = elAttrs['ref']; var refX = parseFloat(elAttrs['ref-x']); var refY = parseFloat(elAttrs['ref-y']); var refDx = parseFloat(elAttrs['ref-dx']); var refDy = parseFloat(elAttrs['ref-dy']); var yAlignment = elAttrs['y-alignment']; var xAlignment = elAttrs['x-alignment']; var refWidth = parseFloat(elAttrs['ref-width']); var refHeight = parseFloat(elAttrs['ref-height']); // `ref` is the selector of the reference element. If no `ref` is passed, reference // element is the root element. var isScalable = _.contains(_.pluck(_.pluck($el.parents('g'), 'className'), 'baseVal'), 'scalable'); if (ref) { // Get the bounding box of the reference element relative to the root `<g>` element. bbox = V(this.findBySelector(ref)[0]).bbox(false, this.el); } var vel = V($el[0]); // Remove the previous translate() from the transform attribute and translate the element // relative to the root bounding box following the `ref-x` and `ref-y` attributes. if (vel.attr('transform')) { vel.attr('transform', vel.attr('transform').replace(/translate\([^)]*\)/g, '').trim() || ''); } function isDefined(x) { return _.isNumber(x) && !_.isNaN(x); } // The final translation of the subelement. var tx = 0; var ty = 0; // 'ref-width'/'ref-height' defines the width/height of the subelement relatively to // the reference element size // val in 0..1 ref-width = 0.75 sets the width to 75% of the ref. el. width // val < 0 || val > 1 ref-height = -20 sets the height to the the ref. el. height shorter by 20 if (isDefined(refWidth)) { if (refWidth >= 0 && refWidth <= 1) { vel.attr('width', refWidth * bbox.width); } else { vel.attr('width', Math.max(refWidth + bbox.width, 0)); } } if (isDefined(refHeight)) { if (refHeight >= 0 && refHeight <= 1) { vel.attr('height', refHeight * bbox.height); } else { vel.attr('height', Math.max(refHeight + bbox.height, 0)); } } // `ref-dx` and `ref-dy` define the offset of the subelement relative to the right and/or bottom // coordinate of the reference element. if (isDefined(refDx)) { if (isScalable) { // Compensate for the scale grid in case the elemnt is in the scalable group. var scale = V(this.$('.scalable')[0]).scale(); tx = bbox.x + bbox.width + refDx / scale.sx; } else { tx = bbox.x + bbox.width + refDx; } } if (isDefined(refDy)) { if (isScalable) { // Compensate for the scale grid in case the elemnt is in the scalable group. var scale = V(this.$('.scalable')[0]).scale(); ty = bbox.y + bbox.height + refDy / scale.sy; } else { ty = bbox.y + bbox.height + refDy; } } // if `refX` is in [0, 1] then `refX` is a fraction of bounding box width // if `refX` is < 0 then `refX`'s absolute values is the right coordinate of the bounding box // otherwise, `refX` is the left coordinate of the bounding box // Analogical rules apply for `refY`. if (isDefined(refX)) { if (refX > 0 && refX < 1) { tx = bbox.x + bbox.width * refX; } else if (isScalable) { // Compensate for the scale grid in case the elemnt is in the scalable group. var scale = V(this.$('.scalable')[0]).scale(); tx = bbox.x + refX / scale.sx; } else { tx = bbox.x + refX; } } if (isDefined(refY)) { if (refY > 0 && refY < 1) { ty = bbox.y + bbox.height * refY; } else if (isScalable) { // Compensate for the scale grid in case the elemnt is in the scalable group. var scale = V(this.$('.scalable')[0]).scale(); ty = bbox.y + refY / scale.sy; } else { ty = bbox.y + refY; } } var velbbox = vel.bbox(false, this.paper.viewport); // `y-alignment` when set to `middle` causes centering of the subelement around its new y coordinate. if (yAlignment === 'middle') { ty -= velbbox.height/2; } else if (isDefined(yAlignment)) { ty += (yAlignment > -1 && yAlignment < 1) ? velbbox.height * yAlignment : yAlignment; } // `x-alignment` when set to `middle` causes centering of the subelement around its new x coordinate. if (xAlignment === 'middle') { tx -= velbbox.width/2; } else if (isDefined(xAlignment)) { tx += (xAlignment > -1 && xAlignment < 1) ? velbbox.width * xAlignment : xAlignment; } vel.translate(tx, ty); }, // `prototype.markup` is rendered by default. Set the `markup` attribute on the model if the // default markup is not desirable. renderMarkup: function() { var markup = this.model.markup || this.model.get('markup'); if (markup) { var nodes = V(markup); V(this.el).append(nodes); } else { throw new Error('properties.markup is missing while the default render() implementation is used.'); } }, render: function() { this.$el.empty(); this.renderMarkup(); this.update(); this.resize(); this.rotate(); this.translate(); return this; }, // Scale the whole `<g>` group. Note the difference between `scale()` and `resize()` here. // `resize()` doesn't scale the whole `<g>` group but rather adjusts the `box.sx`/`box.sy` only. // `update()` is then responsible for scaling only those elements that have the `follow-scale` // attribute set to `true`. This is desirable in elements that have e.g. a `<text>` subelement // that is not supposed to be scaled together with a surrounding `<rect>` element that IS supposed // be be scaled. scale: function(sx, sy) { // TODO: take into account the origin coordinates `ox` and `oy`. V(this.el).scale(sx, sy); }, resize: function() { var size = this.model.get('size') || { width: 1, height: 1 }; var angle = this.model.get('angle') || 0; var scalable = V(this.$('.scalable')[0]); if (!scalable) { // If there is no scalable elements, than there is nothing to resize. return; } var scalableBbox = scalable.bbox(true); // Make sure `scalableBbox.width` and `scalableBbox.height` are not zero which can happen if the element does not have any content. By making // the width/height 1, we prevent HTML errors of the type `scale(Infinity, Infinity)`. scalable.attr('transform', 'scale(' + (size.width / (scalableBbox.width || 1)) + ',' + (size.height / (scalableBbox.height || 1)) + ')'); // Now the interesting part. The goal is to be able to store the object geometry via just `x`, `y`, `angle`, `width` and `height` // Order of transformations is significant but we want to reconstruct the object always in the order: // resize(), rotate(), translate() no matter of how the object was transformed. For that to work, // we must adjust the `x` and `y` coordinates of the object whenever we resize it (because the origin of the // rotation changes). The new `x` and `y` coordinates are computed by canceling the previous rotation // around the center of the resized object (which is a different origin then the origin of the previous rotation) // and getting the top-left corner of the resulting object. Then we clean up the rotation back to what it originally was. // Cancel the rotation but now around a different origin, which is the center of the scaled object. var rotatable = V(this.$('.rotatable')[0]); var rotation = rotatable && rotatable.attr('transform'); if (rotation && rotation !== 'null') { rotatable.attr('transform', rotation + ' rotate(' + (-angle) + ',' + (size.width/2) + ',' + (size.height/2) + ')'); var rotatableBbox = scalable.bbox(false, this.paper.viewport); // Store new x, y and perform rotate() again against the new rotation origin. this.model.set('position', { x: rotatableBbox.x, y: rotatableBbox.y }); this.rotate(); } // Update must always be called on non-rotated element. Otherwise, relative positioning // would work with wrong (rotated) bounding boxes. this.update(); }, translate: function(model, changes, opt) { var position = this.model.get('position') || { x: 0, y: 0 }; V(this.el).attr('transform', 'translate(' + position.x + ',' + position.y + ')'); }, rotate: function() { var rotatable = V(this.$('.rotatable')[0]); if (!rotatable) { // If there is no rotatable elements, then there is nothing to rotate. return; } var angle = this.model.get('angle') || 0; var size = this.model.get('size') || { width: 1, height: 1 }; var ox = size.width/2; var oy = size.height/2; rotatable.attr('transform', 'rotate(' + angle + ',' + ox + ',' + oy + ')'); }, // Interaction. The controller part. // --------------------------------- pointerdown: function(evt, x, y) { if ( // target is a valid magnet start linking evt.target.getAttribute('magnet') && this.paper.options.validateMagnet.call(this.paper, this, evt.target) ) { this.model.trigger('batch:start'); var link = this.paper.getDefaultLink(this, evt.target); link.set({ source: { id: this.model.id, selector: this.getSelector(evt.target), port: $(evt.target).attr('port') }, target: { x: x, y: y } }); this.paper.model.addCell(link); this._linkView = this.paper.findViewByModel(link); this._linkView.startArrowheadMove('target'); } else { this._dx = x; this._dy = y; joint.dia.CellView.prototype.pointerdown.apply(this, arguments); } }, pointermove: function(evt, x, y) { if (this._linkView) { // let the linkview deal with this event this._linkView.pointermove(evt, x, y); } else { var grid = this.paper.options.gridSize; if (this.options.interactive !== false) { var position = this.model.get('position'); // Make sure the new element's position always snaps to the current grid after // translate as the previous one could be calculated with a different grid size. this.model.translate( g.snapToGrid(position.x, grid) - position.x + g.snapToGrid(x - this._dx, grid), g.snapToGrid(position.y, grid) - position.y + g.snapToGrid(y - this._dy, grid) ); } this._dx = g.snapToGrid(x, grid); this._dy = g.snapToGrid(y, grid); joint.dia.CellView.prototype.pointermove.apply(this, arguments); } }, pointerup: function(evt, x, y) { if (this._linkView) { // let the linkview deal with this event this._linkView.pointerup(evt, x, y); delete this._linkView; this.model.trigger('batch:stop'); } else { joint.dia.CellView.prototype.pointerup.apply(this, arguments); } } }); if (typeof exports === 'object') { module.exports.Element = joint.dia.Element; module.exports.ElementView = joint.dia.ElementView; } // JointJS diagramming library. // (c) 2011-2013 client IO if (typeof exports === 'object') { var joint = { dia: { Cell: require('./joint.dia.cell').Cell, CellView: require('./joint.dia.cell').CellView } }; var Backbone = require('backbone'); var _ = require('lodash'); var g = require('./geometry'); } // joint.dia.Link base model. // -------------------------- joint.dia.Link = joint.dia.Cell.extend({ // The default markup for links. markup: [ '<path class="connection" stroke="black"/>', '<path class="marker-source" fill="black" stroke="black" />', '<path class="marker-target" fill="black" stroke="black" />', '<path class="connection-wrap"/>', '<g class="labels"/>', '<g class="marker-vertices"/>', '<g class="marker-arrowheads"/>', '<g class="link-tools"/>' ].join(''), labelMarkup: [ '<g class="label">', '<rect />', '<text />', '</g>' ].join(''), toolMarkup: [ '<g class="link-tool">', '<g class="tool-remove" event="remove">', '<circle r="11" />', '<path transform="scale(.8) translate(-16, -16)" d="M24.778,21.419 19.276,15.917 24.777,10.415 21.949,7.585 16.447,13.087 10.945,7.585 8.117,10.415 13.618,15.917 8.116,21.419 10.946,24.248 16.447,18.746 21.948,24.248z"/>', '<title>Remove link.</title>', '</g>', '<g class="tool-options" event="link:options">', '<circle r="11" transform="translate(25)"/>', '<path fill="white" transform="scale(.55) translate(29, -16)" d="M31.229,17.736c0.064-0.571,0.104-1.148,0.104-1.736s-0.04-1.166-0.104-1.737l-4.377-1.557c-0.218-0.716-0.504-1.401-0.851-2.05l1.993-4.192c-0.725-0.91-1.549-1.734-2.458-2.459l-4.193,1.994c-0.647-0.347-1.334-0.632-2.049-0.849l-1.558-4.378C17.165,0.708,16.588,0.667,16,0.667s-1.166,0.041-1.737,0.105L12.707,5.15c-0.716,0.217-1.401,0.502-2.05,0.849L6.464,4.005C5.554,4.73,4.73,5.554,4.005,6.464l1.994,4.192c-0.347,0.648-0.632,1.334-0.849,2.05l-4.378,1.557C0.708,14.834,0.667,15.412,0.667,16s0.041,1.165,0.105,1.736l4.378,1.558c0.217,0.715,0.502,1.401,0.849,2.049l-1.994,4.193c0.725,0.909,1.549,1.733,2.459,2.458l4.192-1.993c0.648,0.347,1.334,0.633,2.05,0.851l1.557,4.377c0.571,0.064,1.148,0.104,1.737,0.104c0.588,0,1.165-0.04,1.736-0.104l1.558-4.377c0.715-0.218,1.399-0.504,2.049-0.851l4.193,1.993c0.909-0.725,1.733-1.549,2.458-2.458l-1.993-4.193c0.347-0.647,0.633-1.334,0.851-2.049L31.229,17.736zM16,20.871c-2.69,0-4.872-2.182-4.872-4.871c0-2.69,2.182-4.872,4.872-4.872c2.689,0,4.871,2.182,4.871,4.872C20.871,18.689,18.689,20.871,16,20.871z"/>', '<title>Link options.</title>', '</g>', '</g>' ].join(''), // The default markup for showing/removing vertices. These elements are the children of the .marker-vertices element (see `this.markup`). // Only .marker-vertex and .marker-vertex-remove element have special meaning. The former is used for // dragging vertices (changin their position). The latter is used for removing vertices. vertexMarkup: [ '<g class="marker-vertex-group" transform="translate(<%= x %>, <%= y %>)">', '<circle class="marker-vertex" idx="<%= idx %>" r="10" />', '<path class="marker-vertex-remove-area" idx="<%= idx %>" d="M16,5.333c-7.732,0-14,4.701-14,10.5c0,1.982,0.741,3.833,2.016,5.414L2,25.667l5.613-1.441c2.339,1.317,5.237,2.107,8.387,2.107c7.732,0,14-4.701,14-10.5C30,10.034,23.732,5.333,16,5.333z" transform="translate(5, -33)"/>', '<path class="marker-vertex-remove" idx="<%= idx %>" transform="scale(.8) translate(9.5, -37)" d="M24.778,21.419 19.276,15.917 24.777,10.415 21.949,7.585 16.447,13.087 10.945,7.585 8.117,10.415 13.618,15.917 8.116,21.419 10.946,24.248 16.447,18.746 21.948,24.248z">', '<title>Remove vertex.</title>', '</path>', '</g>' ].join(''), arrowheadMarkup: [ '<g class="marker-arrowhead-group marker-arrowhead-group-<%= end %>">', '<path class="marker-arrowhead" end="<%= end %>" d="M 26 0 L 0 13 L 26 26 z" />', '</g>' ].join(''), defaults: { type: 'link' }, disconnect: function() { return this.set({ source: g.point(0, 0), target: g.point(0, 0) }); }, // A convenient way to set labels. Currently set values will be mixined with `value` if used as a setter. label: function(idx, value) { idx = idx || 0; var labels = this.get('labels') || []; // Is it a getter? if (arguments.length === 0 || arguments.length === 1) { return labels[idx]; } var newValue = _.merge({}, labels[idx], value); var newLabels = labels.slice(); newLabels[idx] = newValue; return this.set({ labels: newLabels }); }, translate: function(tx, ty, opt) { var attrs = {}; var source = this.get('source'); var target = this.get('target'); var vertices = this.get('vertices'); if (!source.id) { attrs.source = { x: source.x + tx, y: source.y + ty }; } if (!target.id) { attrs.target = { x: target.x + tx, y: target.y + ty }; } if (vertices && vertices.length) { attrs.vertices = _.map(vertices, function(vertex) { return { x: vertex.x + tx, y: vertex.y + ty }; }); } return this.set(attrs, opt); } }); // joint.dia.Link base view and controller. // ---------------------------------------- joint.dia.LinkView = joint.dia.CellView.extend({ className: function() { return _.unique(this.model.get('type').split('.').concat('link')).join(' '); }, options: { shortLinkLength: 100 }, initialize: function() { joint.dia.CellView.prototype.initialize.apply(this, arguments); // create methods in prototype, so they can be accessed from any instance and // don't need to be create over and over if (typeof this.constructor.prototype.watchSource !== 'function') { this.constructor.prototype.watchSource = this._createWatcher('source'); this.constructor.prototype.watchTarget = this._createWatcher('target'); } // `_.labelCache` is a mapping of indexes of labels in the `this.get('labels')` array to // `<g class="label">` nodes wrapped by Vectorizer. This allows for quick access to the // nodes in `updateLabelPosition()` in order to update the label positions. this._labelCache = {}; // keeps markers bboxes and positions again for quicker access this._markerCache = {}; // bind events this.startListening(); }, startListening: function() { this.listenTo(this.model, 'change:markup', this.render); this.listenTo(this.model, 'change:smooth change:manhattan change:router change:connector', this.update); this.listenTo(this.model, 'change:toolMarkup', function() { this.renderTools().updateToolsPosition(); }); this.listenTo(this.model, 'change:labels change:labelMarkup', function() { this.renderLabels().updateLabelPositions(); }); this.listenTo(this.model, 'change:vertices change:vertexMarkup', function() { this.renderVertexMarkers().update(); }); this.listenTo(this.model, 'change:source', function(cell, source) { this.watchSource(cell, source).update(); }); this.listenTo(this.model, 'change:target', function(cell, target) { this.watchTarget(cell, target).update(); }); }, // Rendering //---------- render: function() { this.$el.empty(); // A special markup can be given in the `properties.markup` property. This might be handy // if e.g. arrowhead markers should be `<image>` elements or any other element than `<path>`s. // `.connection`, `.connection-wrap`, `.marker-source` and `.marker-target` selectors // of elements with special meaning though. Therefore, those classes should be preserved in any // special markup passed in `properties.markup`. var children = V(this.model.get('markup') || this.model.markup); // custom markup may contain only one children if (!_.isArray(children)) children = [children]; // Cache all children elements for quicker access. this._V = {}; // vectorized markup; _.each(children, function(child) { var c = child.attr('class'); c && (this._V[$.camelCase(c)] = child); }, this); // Only the connection path is mandatory if (!this._V.connection) throw new Error('link: no connection path in the markup'); // partial rendering this.renderTools(); this.renderVertexMarkers(); this.renderArrowheadMarkers(); V(this.el).append(children); // rendering labels has to be run after the link is appended to DOM tree. (otherwise <Text> bbox // returns zero values) this.renderLabels(); // start watching the ends of the link for changes this.watchSource(this.model, this.model.get('source')) .watchTarget(this.model, this.model.get('target')) .update(); return this; }, renderLabels: function() { if (!this._V.labels) return this; this._labelCache = {}; var $labels = $(this._V.labels.node).empty(); var labels = this.model.get('labels') || []; if (!labels.length) return this; var labelTemplate = _.template(this.model.get('labelMarkup') || this.model.labelMarkup); // This is a prepared instance of a vectorized SVGDOM node for the label element resulting from // compilation of the labelTemplate. The purpose is that all labels will just `clone()` this // node to create a duplicate. var labelNodeInstance = V(labelTemplate()); _.each(labels, function(label, idx) { var labelNode = labelNodeInstance.clone().node; // Cache label nodes so that the `updateLabels()` can just update the label node positions. this._labelCache[idx] = V(labelNode); var $text = $(labelNode).find('text'); var $rect = $(labelNode).find('rect'); // Text attributes with the default `text-anchor` and font-size set. var textAttributes = _.extend({ 'text-anchor': 'middle', 'font-size': 14 }, joint.util.getByPath(label, 'attrs/text', '/')); $text.attr(_.omit(textAttributes, 'text')); if (!_.isUndefined(textAttributes.text)) { V($text[0]).text(textAttributes.text + ''); } // Note that we first need to append the `<text>` element to the DOM in order to // get its bounding box. $labels.append(labelNode); // `y-alignment` - center the text element around its y coordinate. var textBbox = V($text[0]).bbox(true, $labels[0]); V($text[0]).translate(0, -textBbox.height/2); // Add default values. var rectAttributes = _.extend({ fill: 'white', rx: 3, ry: 3 }, joint.util.getByPath(label, 'attrs/rect', '/')); $rect.attr(_.extend(rectAttributes, { x: textBbox.x, y: textBbox.y - textBbox.height/2, // Take into account the y-alignment translation. width: textBbox.width, height: textBbox.height })); }, this); return this; }, renderTools: function() { if (!this._V.linkTools) return this; // Tools are a group of clickable elements that manipulate the whole link. // A good example of this is the remove tool that removes the whole link. // Tools appear after hovering the link close to the `source` element/point of the link // but are offset a bit so that they don't cover the `marker-arrowhead`. var $tools = $(this._V.linkTools.node).empty(); var toolTemplate = _.template(this.model.get('toolMarkup') || this.model.toolMarkup); var tool = V(toolTemplate()); $tools.append(tool.node); // Cache the tool node so that the `updateToolsPosition()` can update the tool position quickly. this._toolCache = tool; return this; }, renderVertexMarkers: function() { if (!this._V.markerVertices) return this; var $markerVertices = $(this._V.markerVertices.node).empty(); // A special markup can be given in the `properties.vertexMarkup` property. This might be handy // if default styling (elements) are not desired. This makes it possible to use any // SVG elements for .marker-vertex and .marker-vertex-remove tools. var markupTemplate = _.template(this.model.get('vertexMarkup') || this.model.vertexMarkup); _.each(this.model.get('vertices'), function(vertex, idx) { $markerVertices.append(V(markupTemplate(_.extend({ idx: idx }, vertex))).node); }); return this; }, renderArrowheadMarkers: function() { // Custom markups might not have arrowhead markers. Therefore, jump of this function immediately if that's the case. if (!this._V.markerArrowheads) return this; var $markerArrowheads = $(this._V.markerArrowheads.node); $markerArrowheads.empty(); // A special markup can be given in the `properties.vertexMarkup` property. This might be handy // if default styling (elements) are not desired. This makes it possible to use any // SVG elements for .marker-vertex and .marker-vertex-remove tools. var markupTemplate = _.template(this.model.get('arrowheadMarkup') || this.model.arrowheadMarkup); this._V.sourceArrowhead = V(markupTemplate({ end: 'source' })); this._V.targetArrowhead = V(markupTemplate({ end: 'target' })); $markerArrowheads.append(this._V.sourceArrowhead.node, this._V.targetArrowhead.node); return this; }, // Updating //--------- // Default is to process the `attrs` object and set attributes on subelements based on the selectors. update: function() { // Update attributes. _.each(this.model.get('attrs'), function(attrs, selector) { // If the `filter` attribute is an object, it is in the special JointJS filter format and so // it becomes a special attribute and is treated separately. if (_.isObject(attrs.filter)) { this.findBySelector(selector).attr(_.omit(attrs, 'filter')); this.applyFilter(selector, attrs.filter); } else { this.findBySelector(selector).attr(attrs); } }, this); // Path finding var vertices = this.route = this.findRoute(this.model.get('vertices') || []); // finds all the connection points taking new vertices into account this._findConnectionPoints(vertices); var pathData = this.getPathData(vertices); // The markup needs to contain a `.connection` this._V.connection.attr('d', pathData); this._V.connectionWrap && this._V.connectionWrap.attr('d', pathData); this._translateAndAutoOrientArrows(this._V.markerSource, this._V.markerTarget); //partials updates this.updateLabelPositions(); this.updateToolsPosition(); this.updateArrowheadMarkers(); delete this.options.perpendicular; return this; }, _findConnectionPoints: function(vertices) { // cache source and target points var sourcePoint, targetPoint, sourceMarkerPoint, targetMarkerPoint; var firstVertex = _.first(vertices); sourcePoint = this.getConnectionPoint( 'source', this.model.get('source'), firstVertex || this.model.get('target') ).round(); var lastVertex = _.last(vertices); targetPoint = this.getConnectionPoint( 'target', this.model.get('target'), lastVertex || sourcePoint ).round(); // Move the source point by the width of the marker taking into account // its scale around x-axis. Note that scale is the only transform that // makes sense to be set in `.marker-source` attributes object // as all other transforms (translate/rotate) will be replaced // by the `translateAndAutoOrient()` function. var cache = this._markerCache; if (this._V.markerSource) { cache.sourceBBox = cache.sourceBBox || this._V.markerSource.bbox(true); sourceMarkerPoint = g.point(sourcePoint).move( firstVertex || targetPoint, cache.sourceBBox.width * this._V.markerSource.scale().sx * -1 ).round(); } if (this._V.markerTarget) { cache.targetBBox = cache.targetBBox || this._V.markerTarget.bbox(true); targetMarkerPoint = g.point(targetPoint).move( lastVertex || sourcePoint, cache.targetBBox.width * this._V.markerTarget.scale().sx * -1 ).round(); } // if there was no markup for the marker, use the connection point. cache.sourcePoint = sourceMarkerPoint || sourcePoint; cache.targetPoint = targetMarkerPoint || targetPoint; // make connection points public this.sourcePoint = sourcePoint; this.targetPoint = targetPoint; }, updateLabelPositions: function() { if (!this._V.labels) return this; // This method assumes all the label nodes are stored in the `this._labelCache` hash table // by their indexes in the `this.get('labels')` array. This is done in the `renderLabels()` method. var labels = this.model.get('labels') || []; if (!labels.length) return this; var connectionElement = this._V.connection.node; var connectionLength = connectionElement.getTotalLength(); _.each(labels, function(label, idx) { var position = label.position; position = (position > connectionLength) ? connectionLength : position; // sanity check position = (position < 0) ? connectionLength + position : position; position = position > 1 ? position : connectionLength * position; var labelCoordinates = connectionElement.getPointAtLength(position); this._labelCache[idx].attr('transform', 'translate(' + labelCoordinates.x + ', ' + labelCoordinates.y + ')'); }, this); return this; }, updateToolsPosition: function() { if (!this._V.linkTools) return this; // Move the tools a bit to the target position but don't cover the `sourceArrowhead` marker. // Note that the offset is hardcoded here. The offset should be always // more than the `this.$('.marker-arrowhead[end="source"]')[0].bbox().width` but looking // this up all the time would be slow. var scale = ''; var offset = 40; // If the link is too short, make the tools half the size and the offset twice as low. if (this.getConnectionLength() < this.options.shortLinkLength) { scale = 'scale(.5)'; offset /= 2; } var toolPosition = this.getPointAtLength(offset); this._toolCache.attr('transform', 'translate(' + toolPosition.x + ', ' + toolPosition.y + ') ' + scale); return this; }, updateArrowheadMarkers: function() { if (!this._V.markerArrowheads) return this; // getting bbox of an element with `display="none"` in IE9 ends up with access violation if ($.css(this._V.markerArrowheads.node, 'display') === 'none') return this; var sx = this.getConnectionLength() < this.options.shortLinkLength ? .5 : 1; this._V.sourceArrowhead.scale(sx); this._V.targetArrowhead.scale(sx); this._translateAndAutoOrientArrows(this._V.sourceArrowhead, this._V.targetArrowhead); return this; }, // Returns a function observing changes on an end of the link. If a change happens and new end is a new model, // it stops listening on the previous one and starts listening to the new one. _createWatcher: function(endType) { function watchEnd(link, end) { end = end || {}; var previousEnd = link.previous(endType) || {}; // Pick updateMethod this._sourceBboxUpdate or this._targetBboxUpdate. var updateEndFunction = this['_' + endType + 'BBoxUpdate']; if (this._isModel(previousEnd)) { this.stopListening(this.paper.getModelById(previousEnd.id), 'change', updateEndFunction); } if (this._isModel(end)) { // If the observed model changes, it caches a new bbox and do the link update. this.listenTo(this.paper.getModelById(end.id), 'change', updateEndFunction); } _.bind(updateEndFunction, this)({ cacheOnly: true }); return this; } return watchEnd; }, // It's important to keep both methods (sourceBboxUpdate and targetBboxUpdate) as unique methods // because of loop links. We have to be able to determine, which method we want to stop listen to. // ListenTo(model, event, handler) as model and event will be identical. _sourceBBoxUpdate: function(update) { // keep track which end had been changed very last this.lastEndChange = 'source'; update = update || {}; var end = this.model.get('source'); if (this._isModel(end)) { var selector = this._makeSelector(end); var view = this.paper.findViewByModel(end.id); var magnetElement = this.paper.viewport.querySelector(selector); this.sourceBBox = view.getStrokeBBox(magnetElement); this.sourceView = view; this.sourceMagnet = magnetElement; } else if (end) { // the link end is a point ~ rect 1x1 this.sourceBBox = g.rect(end.x, end.y, 1, 1); } if (!update.cacheOnly) this.update(); }, _targetBBoxUpdate: function(update) { // keep track which end had been changed very last this.lastEndChange = 'target'; update = update || {}; var end = this.model.get('target'); if (this._isModel(end)) { var selector = this._makeSelector(end); var view = this.paper.findViewByModel(end.id); var magnetElement = this.paper.viewport.querySelector(selector); this.targetBBox = view.getStrokeBBox(magnetElement); this.targetView = view; this.targetMagnet = magnetElement; } else if (end) { // the link end is a point ~ rect 1x1 this.targetBBox = g.rect(end.x, end.y, 1, 1); } if (!update.cacheOnly) this.update(); }, _translateAndAutoOrientArrows: function(sourceArrow, targetArrow) { // Make the markers "point" to their sticky points being auto-oriented towards // `targetPosition`/`sourcePosition`. And do so only if there is a markup for them. if (sourceArrow) { sourceArrow.translateAndAutoOrient( this.sourcePoint, _.first(this.route) || this.targetPoint, this.paper.viewport ); } if (targetArrow) { targetArrow.translateAndAutoOrient( this.targetPoint, _.last(this.route) || this.sourcePoint, this.paper.viewport ); } }, removeVertex: function(idx) { var vertices = _.clone(this.model.get('vertices')); if (vertices && vertices.length) { vertices.splice(idx, 1); this.model.set('vertices', vertices); } return this; }, // This method ads a new vertex to the `vertices` array of `.connection`. This method // uses a heuristic to find the index at which the new `vertex` should be placed at assuming // the new vertex is somewhere on the path. addVertex: function(vertex) { this.model.set('attrs', this.model.get('attrs') || {}); var attrs = this.model.get('attrs'); // As it is very hard to find a correct index of the newly created vertex, // a little heuristics is taking place here. // The heuristics checks if length of the newly created // path is lot more than length of the old path. If this is the case, // new vertex was probably put into a wrong index. // Try to put it into another index and repeat the heuristics again. var vertices = (this.model.get('vertices') || []).slice(); // Store the original vertices for a later revert if needed. var originalVertices = vertices.slice(); // A `<path>` element used to compute the length of the path during heuristics. var path = this._V.connection.node.cloneNode(false); // Length of the original path. var originalPathLength = path.getTotalLength(); // Current path length. var pathLength; // Tolerance determines the highest possible difference between the length // of the old and new path. The number has been chosen heuristically. var pathLengthTolerance = 20; // Total number of vertices including source and target points. var idx = vertices.length + 1; // Loop through all possible indexes and check if the difference between // path lengths changes significantly. If not, the found index is // most probably the right one. while (idx--) { vertices.splice(idx, 0, vertex); V(path).attr('d', this.getPathData(this.findRoute(vertices))); pathLength = path.getTotalLength(); // Check if the path lengths changed significantly. if (pathLength - originalPathLength > pathLengthTolerance) { // Revert vertices to the original array. The path length has changed too much // so that the index was not found yet. vertices = originalVertices.slice(); } else { break; } } this.model.set('vertices', vertices); // In manhattan routing, if there are no vertices, the path length changes significantly // with the first vertex added. Shall we check vertices.length === 0? at beginning of addVertex() // in order to avoid the temporary path construction and other operations? return Math.max(idx, 0); }, // Send a token (an SVG element, usually a circle) along the connection path. // Example: `paper.findViewByModel(link).sendToken(V('circle', { r: 7, fill: 'green' }).node)` // `duration` is optional and is a time in milliseconds that the token travels from the source to the target of the link. Default is `1000`. // `callback` is optional and is a function to be called once the token reaches the target. sendToken: function(token, duration, callback) { duration = duration || 1000; V(this.paper.viewport).append(token); V(token).animateAlongPath({ dur: duration + 'ms', repeatCount: 1 }, this._V.connection.node); _.delay(function() { V(token).remove(); callback && callback(); }, duration); }, findRoute: function(oldVertices) { var router = this.model.get('router'); if (!router) { if (this.model.get('manhattan')) { // backwards compability router = { name: 'orthogonal' }; } else { return oldVertices; } } var fn = joint.routers[router.name]; if (!_.isFunction(fn)) { throw 'unknown router: ' + router.name; } var newVertices = fn.call(this, oldVertices || [], router.args || {}, this); return newVertices; }, // Return the `d` attribute value of the `<path>` element representing the link // between `source` and `target`. getPathData: function(vertices) { var connector = this.model.get('connector'); if (!connector) { // backwards compability connector = this.model.get('smooth') ? { name: 'smooth' } : { name: 'normal' }; } if (!_.isFunction(joint.connectors[connector.name])) { throw 'unknown connector: ' + connector.name; } var pathData = joint.connectors[connector.name].call( this, this._markerCache.sourcePoint, // Note that the value is translated by the size this._markerCache.targetPoint, // of the marker. (We'r not using this.sourcePoint) vertices || (this.model.get('vertices') || {}), connector.args || {}, // options this ); return pathData; }, // Find a point that is the start of the connection. // If `selectorOrPoint` is a point, then we're done and that point is the start of the connection. // If the `selectorOrPoint` is an element however, we need to know a reference point (or element) // that the link leads to in order to determine the start of the connection on the original element. getConnectionPoint: function(end, selectorOrPoint, referenceSelectorOrPoint) { var spot; // If the `selectorOrPoint` (or `referenceSelectorOrPoint`) is `undefined`, the `source`/`target` of the link model is `undefined`. // We want to allow this however so that one can create links such as `var link = new joint.dia.Link` and // set the `source`/`target` later. selectorOrPoint = selectorOrPoint || { x: 0, y: 0 }; referenceSelectorOrPoint = referenceSelectorOrPoint || { x: 0, y: 0 }; if (this._isPoint(selectorOrPoint)) { // If the source is a point, we don't need a reference point to find the sticky point of connection. spot = g.point(selectorOrPoint); } else { // If the source is an element, we need to find a point on the element boundary that is closest // to the reference point (or reference element). // Get the bounding box of the spot relative to the paper viewport. This is necessary // in order to follow paper viewport transformations (scale/rotate). // `_sourceBbox` (`_targetBbox`) comes from `_sourceBboxUpdate` (`_sourceBboxUpdate`) // method, it exists since first render and are automatically updated var spotBbox = end === 'source' ? this.sourceBBox : this.targetBBox; var reference; if (this._isPoint(referenceSelectorOrPoint)) { // Reference was passed as a point, therefore, we're ready to find the sticky point of connection on the source element. reference = g.point(referenceSelectorOrPoint); } else { // Reference was passed as an element, therefore we need to find a point on the reference // element boundary closest to the source element. // Get the bounding box of the spot relative to the paper viewport. This is necessary // in order to follow paper viewport transformations (scale/rotate). var referenceBbox = end === 'source' ? this.targetBBox : this.sourceBBox; reference = g.rect(referenceBbox).intersectionWithLineFromCenterToPoint(g.rect(spotBbox).center()); reference = reference || g.rect(referenceBbox).center(); } // If `perpendicularLinks` flag is set on the paper and there are vertices // on the link, then try to find a connection point that makes the link perpendicular // even though the link won't point to the center of the targeted object. if (this.paper.options.perpendicularLinks || this.options.perpendicular) { var horizontalLineRect = g.rect(0, reference.y, this.paper.options.width, 1); var verticalLineRect = g.rect(reference.x, 0, 1, this.paper.options.height); var nearestSide; if (horizontalLineRect.intersect(g.rect(spotBbox))) { nearestSide = g.rect(spotBbox).sideNearestToPoint(reference); switch (nearestSide) { case 'left': spot = g.point(spotBbox.x, reference.y); break; case 'right': spot = g.point(spotBbox.x + spotBbox.width, reference.y); break; default: spot = g.rect(spotBbox).center(); break; } } else if (verticalLineRect.intersect(g.rect(spotBbox))) { nearestSide = g.rect(spotBbox).sideNearestToPoint(reference); switch (nearestSide) { case 'top': spot = g.point(reference.x, spotBbox.y); break; case 'bottom': spot = g.point(reference.x, spotBbox.y + spotBbox.height); break; default: spot = g.rect(spotBbox).center(); break; } } else { // If there is no intersection horizontally or vertically with the object bounding box, // then we fall back to the regular situation finding straight line (not perpendicular) // between the object and the reference point. spot = g.rect(spotBbox).intersectionWithLineFromCenterToPoint(reference); spot = spot || g.rect(spotBbox).center(); } } else if (this.paper.options.linkConnectionPoint) { var view = end === 'target' ? this.targetView : this.sourceView; var magnet = end === 'target' ? this.targetMagnet : this.sourceMagnet; spot = this.paper.options.linkConnectionPoint(this, view, magnet, reference); } else { spot = g.rect(spotBbox).intersectionWithLineFromCenterToPoint(reference); spot = spot || g.rect(spotBbox).center(); } } return spot; }, _isModel: function(end) { return end && end.id; }, _isPoint: function(end) { return !this._isModel(end); }, _makeSelector: function(end) { var selector = '[model-id="' + end.id + '"]'; // `port` has a higher precendence over `selector`. This is because the selector to the magnet // might change while the name of the port can stay the same. if (end.port) { selector += ' [port="' + end.port + '"]'; } else if (end.selector) { selector += ' ' + end.selector; } return selector; }, // Public API // ---------- getConnectionLength: function() { return this._V.connection.node.getTotalLength(); }, getPointAtLength: function(length) { return this._V.connection.node.getPointAtLength(length); }, // Interaction. The controller part. // --------------------------------- _beforeArrowheadMove: function() { this.model.trigger('batch:start'); this._z = this.model.get('z'); this.model.set('z', Number.MAX_VALUE); // Let the pointer propagate throught the link view elements so that // the `evt.target` is another element under the pointer, not the link itself. this.el.style.pointerEvents = 'none'; if (this.paper.options.markAvailable) { this._markAvailableMagnets(); } }, _afterArrowheadMove: function() { if (this._z) { this.model.set('z', this._z); delete this._z; } // Put `pointer-events` back to its original value. See `startArrowheadMove()` for explanation. // Value `auto` doesn't work in IE9. We force to use `visiblePainted` instead. // See `https://developer.mozilla.org/en-US/docs/Web/CSS/pointer-events`. this.el.style.pointerEvents = 'visiblePainted'; if (this.paper.options.markAvailable) { this._unmarkAvailableMagnets(); } this.model.trigger('batch:stop'); }, _createValidateConnectionArgs: function(arrowhead) { // It makes sure the arguments for validateConnection have the following form: // (source view, source magnet, target view, target magnet and link view) var args = []; args[4] = arrowhead; args[5] = this; var oppositeArrowhead, i = 0, j = 0; if (arrowhead === 'source') { i = 2; oppositeArrowhead = 'target'; } else { j = 2; oppositeArrowhead = 'source'; } var end = this.model.get(oppositeArrowhead); if (end.id) { args[i] = this.paper.findViewByModel(end.id); args[i+1] = end.selector && args[i].el.querySelector(end.selector); } function validateConnectionArgs(cellView, magnet) { args[j] = cellView; args[j+1] = cellView.el === magnet ? undefined : magnet; return args; } return validateConnectionArgs; }, _markAvailableMagnets: function() { var elements = this.paper.model.getElements(); var validate = this.paper.options.validateConnection; _.chain(elements).map(this.paper.findViewByModel, this.paper).each(function(view) { var isElementAvailable = view.el.getAttribute('magnet') !== 'false' && validate.apply(this.paper, this._validateConnectionArgs(view, null)); var availableMagnets = _.filter(view.el.querySelectorAll('[magnet]'), function(magnet) { return validate.apply(this.paper, this._validateConnectionArgs(view, magnet)); }, this); if (isElementAvailable) { V(view.el).addClass('available-magnet'); } _.each(availableMagnets, function(magnet) { V(magnet).addClass('available-magnet'); }); if (isElementAvailable || availableMagnets.length) { V(view.el).addClass('available-cell'); } }, this); }, _unmarkAvailableMagnets: function() { _.each(this.paper.el.querySelectorAll('.available-cell, .available-magnet'), function(magnet) { V(magnet).removeClass('available-magnet').removeClass('available-cell'); }); }, startArrowheadMove: function(end) { // Allow to delegate events from an another view to this linkView in order to trigger arrowhead // move without need to click on the actual arrowhead dom element. this._action = 'arrowhead-move'; this._arrowhead = end; this._validateConnectionArgs = this._createValidateConnectionArgs(this._arrowhead); this._beforeArrowheadMove(); }, pointerdown: function(evt, x, y) { joint.dia.CellView.prototype.pointerdown.apply(this, arguments); this._dx = x; this._dy = y; if (this.options.interactive === false) return; var className = evt.target.getAttribute('class'); switch (className) { case 'marker-vertex': this._action = 'vertex-move'; this._vertexIdx = evt.target.getAttribute('idx'); break; case 'marker-vertex-remove': case 'marker-vertex-remove-area': this.removeVertex(evt.target.getAttribute('idx')); break; case 'marker-arrowhead': this.startArrowheadMove(evt.target.getAttribute('end')); break; default: var targetParentEvent = evt.target.parentNode.getAttribute('event'); if (targetParentEvent) { // `remove` event is built-in. Other custom events are triggered on the paper. if (targetParentEvent === 'remove') { this.model.remove(); } else { this.paper.trigger(targetParentEvent, evt, this, x, y); } } else { // Store the index at which the new vertex has just been placed. // We'll be update the very same vertex position in `pointermove()`. this._vertexIdx = this.addVertex({ x: x, y: y }); this._action = 'vertex-move'; } } }, pointermove: function(evt, x, y) { joint.dia.CellView.prototype.pointermove.apply(this, arguments); switch (this._action) { case 'vertex-move': var vertices = _.clone(this.model.get('vertices')); vertices[this._vertexIdx] = { x: x, y: y }; this.model.set('vertices', vertices); break; case 'arrowhead-move': if (this.paper.options.snapLinks) { // checking view in close area of the pointer var r = this.paper.options.snapLinks.radius || 50; var viewsInArea = this.paper.findViewsInArea({ x: x - r, y: y - r, width: 2 * r, height: 2 * r }); this._closestView && this._closestView.unhighlight(this._closestEnd.selector); this._closestView = this._closestEnd = null; var pointer = g.point(x,y); var distance, minDistance = Number.MAX_VALUE; _.each(viewsInArea, function(view) { // skip connecting to the element in case '.': { magnet: false } attribute present if (view.el.getAttribute('magnet') !== 'false') { // find distance from the center of the model to pointer coordinates distance = view.model.getBBox().center().distance(pointer); // the connection is looked up in a circle area by `distance < r` if (distance < r && distance < minDistance) { if (this.paper.options.validateConnection.apply( this.paper, this._validateConnectionArgs(view, null) )) { minDistance = distance; this._closestView = view; this._closestEnd = { id: view.model.id }; } } } view.$('[magnet]').each(_.bind(function(index, magnet) { var bbox = V(magnet).bbox(false, this.paper.viewport); distance = pointer.distance({ x: bbox.x + bbox.width / 2, y: bbox.y + bbox.height / 2 }); if (distance < r && distance < minDistance) { if (this.paper.options.validateConnection.apply( this.paper, this._validateConnectionArgs(view, magnet) )) { minDistance = distance; this._closestView = view; this._closestEnd = { id: view.model.id, selector: view.getSelector(magnet), port: magnet.getAttribute('port') }; } } }, this)); }, this); this._closestView && this._closestView.highlight(this._closestEnd.selector); this.model.set(this._arrowhead, this._closestEnd || { x: x, y: y }); } else { // checking views right under the pointer // Touchmove event's target is not reflecting the element under the coordinates as mousemove does. // It holds the element when a touchstart triggered. var target = (evt.type === 'mousemove') ? evt.target : document.elementFromPoint(evt.clientX, evt.clientY); if (this._targetEvent !== target) { // Unhighlight the previous view under pointer if there was one. this._magnetUnderPointer && this._viewUnderPointer.unhighlight(this._magnetUnderPointer); this._viewUnderPointer = this.paper.findView(target); if (this._viewUnderPointer) { // If we found a view that is under the pointer, we need to find the closest // magnet based on the real target element of the event. this._magnetUnderPointer = this._viewUnderPointer.findMagnet(target); if (this._magnetUnderPointer && this.paper.options.validateConnection.apply( this.paper, this._validateConnectionArgs(this._viewUnderPointer, this._magnetUnderPointer) )) { // If there was no magnet found, do not highlight anything and assume there // is no view under pointer we're interested in reconnecting to. // This can only happen if the overall element has the attribute `'.': { magnet: false }`. this._magnetUnderPointer && this._viewUnderPointer.highlight(this._magnetUnderPointer); } else { // This type of connection is not valid. Disregard this magnet. this._magnetUnderPointer = null; } } else { // Make sure we'll delete previous magnet this._magnetUnderPointer = null; } } this._targetEvent = target; this.model.set(this._arrowhead, { x: x, y: y }); } break; } this._dx = x; this._dy = y; }, pointerup: function(evt) { joint.dia.CellView.prototype.pointerup.apply(this, arguments); if (this._action === 'arrowhead-move') { if (this.paper.options.snapLinks) { this._closestView && this._closestView.unhighlight(this._closestEnd.selector); this._closestView = this._closestEnd = null; } else { if (this._magnetUnderPointer) { this._viewUnderPointer.unhighlight(this._magnetUnderPointer); // Find a unique `selector` of the element under pointer that is a magnet. If the // `this._magnetUnderPointer` is the root element of the `this._viewUnderPointer` itself, // the returned `selector` will be `undefined`. That means we can directly pass it to the // `source`/`target` attribute of the link model below. this.model.set(this._arrowhead, { id: this._viewUnderPointer.model.id, selector: this._viewUnderPointer.getSelector(this._magnetUnderPointer), port: $(this._magnetUnderPointer).attr('port') }); } delete this._viewUnderPointer; delete this._magnetUnderPointer; delete this._staticView; delete this._staticMagnet; } this._afterArrowheadMove(); } delete this._action; } }); if (typeof exports === 'object') { module.exports.Link = joint.dia.Link; module.exports.LinkView = joint.dia.LinkView; } // JointJS library. // (c) 2011-2013 client IO joint.dia.Paper = Backbone.View.extend({ className: 'paper', options: { width: 800, height: 600, origin: { x: 0, y: 0 }, // x,y coordinates in top-left corner gridSize: 50, perpendicularLinks: false, elementView: joint.dia.ElementView, linkView: joint.dia.LinkView, snapLinks: false, // false, true, { radius: value } // Marks all available magnets with 'available-magnet' class name and all available cells with // 'available-cell' class name. Marks them when dragging a link is started and unmark // when the dragging is stopped. markAvailable: false, // Defines what link model is added to the graph after an user clicks on an active magnet. // Value could be the Backbone.model or a function returning the Backbone.model // defaultLink: function(elementView, magnet) { return condition ? new customLink1() : new customLink2() } defaultLink: new joint.dia.Link, // Check whether to add a new link to the graph when user clicks on an a magnet. validateMagnet: function(cellView, magnet) { return magnet.getAttribute('magnet') !== 'passive'; }, // Check whether to allow or disallow the link connection while an arrowhead end (source/target) // being changed. validateConnection: function(cellViewS, magnetS, cellViewT, magnetT, end, linkView) { return (end === 'target' ? cellViewT : cellViewS) instanceof joint.dia.ElementView; } }, events: { 'mousedown': 'pointerdown', 'dblclick': 'mousedblclick', 'click': 'mouseclick', 'touchstart': 'pointerdown', 'mousemove': 'pointermove', 'touchmove': 'pointermove' }, constructor: function(options) { this._configure(options); Backbone.View.apply(this, arguments); }, _configure: function(options) { if (this.options) options = _.extend({}, _.result(this, 'options'), options); this.options = options; }, initialize: function() { _.bindAll(this, 'addCell', 'sortCells', 'resetCells', 'pointerup', 'asyncRenderCells'); this.svg = V('svg').node; this.viewport = V('g').node; // Append `<defs>` element to the SVG document. This is useful for filters and gradients. V(this.svg).append(V('defs').node); V(this.viewport).attr({ 'class': 'viewport' }); V(this.svg).append(this.viewport); this.$el.append(this.svg); this.setOrigin(); this.setDimensions(); this.listenTo(this.model, 'add', this.addCell); this.listenTo(this.model, 'reset', this.resetCells); this.listenTo(this.model, 'sort', this.sortCells); $(document).on('mouseup touchend', this.pointerup); // Hold the value when mouse has been moved: when mouse moved, no click event will be triggered. this._mousemoved = false; }, remove: function() { $(document).off('mouseup touchend', this.pointerup); Backbone.View.prototype.remove.call(this); }, setDimensions: function(width, height) { width = this.options.width = width || this.options.width; height = this.options.height = height || this.options.height; V(this.svg).attr({ width: width, height: height }); this.trigger('resize', width, height); }, setOrigin: function(ox, oy) { this.options.origin.x = ox || 0; this.options.origin.y = oy || 0; V(this.viewport).translate(ox, oy, { absolute: true }); this.trigger('translate', ox, oy); }, // Expand/shrink the paper to fit the content. Snap the width/height to the grid // defined in `gridWidth`, `gridHeight`. `padding` adds to the resulting width/height of the paper. // When options { fitNegative: true } it also translates the viewport in order to make all // the content visible. fitToContent: function(gridWidth, gridHeight, padding, opt) { // alternatively function(opt) if (_.isObject(gridWidth)) { // first parameter is an option object opt = gridWidth; gridWidth = opt.gridWidth || 1; gridHeight = opt.gridHeight || 1; padding = opt.padding || 0; } else { opt = opt || {}; gridWidth = gridWidth || 1; gridHeight = gridHeight || 1; padding = padding || 0; } // Calculate the paper size to accomodate all the graph's elements. var bbox = V(this.viewport).bbox(true, this.svg); var calcWidth = Math.max(Math.ceil((bbox.width + bbox.x) / gridWidth), 1) * gridWidth; var calcHeight = Math.max(Math.ceil((bbox.height + bbox.y) / gridHeight), 1) * gridHeight; var tx = 0; var ty = 0; if (opt.fitNegative) { if (bbox.x < 0) { tx = Math.ceil(-bbox.x / gridWidth) * gridWidth; calcWidth += tx; } if (bbox.y < 0) { ty = Math.ceil(-bbox.y / gridHeight) * gridHeight; calcHeight += ty; } } calcWidth += padding; calcHeight += padding; var dimensionChange = calcWidth != this.options.width || calcHeight != this.options.height; var originChange = opt.fitNegative && (tx != this.options.origin.x || ty != this.options.origin.y); // Change the dimensions only if there is a size discrepency or an origin change if (originChange) { this.setOrigin(tx, ty); } if (dimensionChange) { this.setDimensions(calcWidth, calcHeight); } }, scaleContentToFit: function(opt) { var contentBBox = this.getContentBBox(); if (!contentBBox.width || !contentBBox.height) return; opt = opt || {}; _.defaults(opt, { padding: 0, preserveAspectRatio: true, scaleGrid: null, minScale: 0, maxScale: Number.MAX_VALUE //minScaleX //minScaleY //maxScaleX //maxScaleY //fittingBBox }); var padding = opt.padding; var minScaleX = opt.minScaleX || opt.minScale; var maxScaleX = opt.maxScaleX || opt.maxScale; var minScaleY = opt.minScaleY || opt.minScale; var maxScaleY = opt.maxScaleY || opt.maxScale; var fittingBBox = opt.fittingBBox || ({ x: 0, y: 0, width: this.options.width, height: this.options.height }); fittingBBox = g.rect(fittingBBox).moveAndExpand({ x: padding, y: padding, width: -2 * padding, height: -2 * padding }); var currentScale = V(this.viewport).scale(); var newSx = fittingBBox.width / contentBBox.width * currentScale.sx; var newSy = fittingBBox.height / contentBBox.height * currentScale.sy; if (opt.preserveAspectRatio) { newSx = newSy = Math.min(newSx, newSy); } // snap scale to a grid if (opt.scaleGrid) { var gridSize = opt.scaleGrid; newSx = gridSize * Math.floor(newSx / gridSize); newSy = gridSize * Math.floor(newSy / gridSize); } // scale min/max boundaries newSx = Math.min(maxScaleX, Math.max(minScaleX, newSx)); newSy = Math.min(maxScaleY, Math.max(minScaleY, newSy)); this.scale(newSx, newSy); var contentTranslation = this.getContentBBox(); var newOx = fittingBBox.x - contentTranslation.x; var newOy = fittingBBox.y - contentTranslation.y; this.setOrigin(newOx, newOy); }, getContentBBox: function() { var crect = this.viewport.getBoundingClientRect(); // Using Screen CTM was the only way to get the real viewport bounding box working in both // Google Chrome and Firefox. var screenCTM = this.viewport.getScreenCTM(); // for non-default origin we need to take the viewport translation into account var viewportCTM = this.viewport.getCTM(); var bbox = g.rect({ x: crect.left - screenCTM.e + viewportCTM.e, y: crect.top - screenCTM.f + viewportCTM.f, width: crect.width, height: crect.height }); return bbox; }, createViewForModel: function(cell) { var view; var type = cell.get('type'); var module = type.split('.')[0]; var entity = type.split('.')[1]; // If there is a special view defined for this model, use that one instead of the default `elementView`/`linkView`. if (joint.shapes[module] && joint.shapes[module][entity + 'View']) { view = new joint.shapes[module][entity + 'View']({ model: cell, interactive: this.options.interactive }); } else if (cell instanceof joint.dia.Element) { view = new this.options.elementView({ model: cell, interactive: this.options.interactive }); } else { view = new this.options.linkView({ model: cell, interactive: this.options.interactive }); } return view; }, addCell: function(cell) { var view = this.createViewForModel(cell); V(this.viewport).append(view.el); view.paper = this; view.render(); // This is the only way to prevent image dragging in Firefox that works. // Setting -moz-user-select: none, draggable="false" attribute or user-drag: none didn't help. $(view.el).find('image').on('dragstart', function() { return false; }); }, resetCells: function(cellsCollection) { $(this.viewport).empty(); var cells = cellsCollection.models.slice(); // Make sure links are always added AFTER elements. // They wouldn't find their sources/targets in the DOM otherwise. cells.sort(function(a, b) { return a instanceof joint.dia.Link ? 1 : -1; }); if (this._frameId) { joint.util.cancelFrame(this._frameId); } if (this.options.async) { this.asyncRenderCells(cells); } else { _.each(cells, this.addCell, this); } // Sort the cells in the DOM manually as we might have changed the order they // were added to the DOM (see above). this.sortCells(); }, asyncRenderCells: function(cells) { var done = false; _.each(_.range(this.options.async && this.options.async.batchSize || 50), function() { var cell = cells.shift(); done = !cell; if (!done) this.addCell(cell); }, this); if (done) { this.trigger('render:done'); } else { this._frameId = joint.util.nextFrame(_.bind(function() { this.asyncRenderCells(cells); }, this)); } }, sortCells: function() { // Run insertion sort algorithm in order to efficiently sort DOM elements according to their // associated model `z` attribute. var $cells = $(this.viewport).children('[model-id]'); var cells = this.model.get('cells'); this.sortElements($cells, function(a, b) { var cellA = cells.get($(a).attr('model-id')); var cellB = cells.get($(b).attr('model-id')); return (cellA.get('z') || 0) > (cellB.get('z') || 0) ? 1 : -1; }); }, // Highly inspired by the jquery.sortElements plugin by Padolsey. // See http://james.padolsey.com/javascript/sorting-elements-with-jquery/. sortElements: function(elements, comparator) { var $elements = $(elements); var placements = $elements.map(function() { var sortElement = this; var parentNode = sortElement.parentNode; // Since the element itself will change position, we have // to have some way of storing it's original position in // the DOM. The easiest way is to have a 'flag' node: var nextSibling = parentNode.insertBefore( document.createTextNode(''), sortElement.nextSibling ); return function() { if (parentNode === this) { throw new Error( "You can't sort elements if any one is a descendant of another." ); } // Insert before flag: parentNode.insertBefore(this, nextSibling); // Remove flag: parentNode.removeChild(nextSibling); }; }); return Array.prototype.sort.call($elements, comparator).each(function(i) { placements[i].call(this); }); }, scale: function(sx, sy, ox, oy) { sy = sy || sx; if (_.isUndefined(ox)) { ox = 0; oy = 0; } // Remove previous transform so that the new scale is not affected by previous scales, especially // the old translate() does not affect the new translate if an origin is specified. V(this.viewport).attr('transform', ''); var oldTx = this.options.origin.x; var oldTy = this.options.origin.y; // TODO: V.scale() doesn't support setting scale origin. #Fix if (ox || oy || oldTx || oldTy) { var newTx = oldTx - ox * (sx - 1); var newTy = oldTy - oy * (sy - 1); if (newTx != oldTx || newTy != oldTy) { this.setOrigin(newTx, newTy); } } V(this.viewport).scale(sx, sy); this.trigger('scale', sx, sy, ox, oy); return this; }, rotate: function(deg, ox, oy) { // If the origin is not set explicitely, rotate around the center. Note that // we must use the plain bounding box (`this.el.getBBox()` instead of the one that gives us // the real bounding box (`bbox()`) including transformations). if (_.isUndefined(ox)) { var bbox = this.viewport.getBBox(); ox = bbox.width/2; oy = bbox.height/2; } V(this.viewport).rotate(deg, ox, oy); }, // Find the first view climbing up the DOM tree starting at element `el`. Note that `el` can also // be a selector or a jQuery object. findView: function(el) { var $el = this.$(el); if ($el.length === 0 || $el[0] === this.el) { return undefined; } if ($el.data('view')) { return $el.data('view'); } return this.findView($el.parent()); }, // Find a view for a model `cell`. `cell` can also be a string representing a model `id`. findViewByModel: function(cell) { var id = _.isString(cell) ? cell : cell.id; var $view = this.$('[model-id="' + id + '"]'); if ($view.length) { return $view.data('view'); } return undefined; }, // Find all views at given point findViewsFromPoint: function(p) { p = g.point(p); var views = _.map(this.model.getElements(), this.findViewByModel); return _.filter(views, function(view) { return g.rect(V(view.el).bbox(false, this.viewport)).containsPoint(p); }, this); }, // Find all views in given area findViewsInArea: function(r) { r = g.rect(r); var views = _.map(this.model.getElements(), this.findViewByModel); return _.filter(views, function(view) { return r.intersect(g.rect(V(view.el).bbox(false, this.viewport))); }, this); }, getModelById: function(id) { return this.model.getCell(id); }, snapToGrid: function(p) { // Convert global coordinates to the local ones of the `viewport`. Otherwise, // improper transformation would be applied when the viewport gets transformed (scaled/rotated). var localPoint = V(this.viewport).toLocalPoint(p.x, p.y); return { x: g.snapToGrid(localPoint.x, this.options.gridSize), y: g.snapToGrid(localPoint.y, this.options.gridSize) }; }, getDefaultLink: function(cellView, magnet) { return _.isFunction(this.options.defaultLink) // default link is a function producing link model ? this.options.defaultLink.call(this, cellView, magnet) // default link is the Backbone model : this.options.defaultLink.clone(); }, // Interaction. // ------------ mousedblclick: function(evt) { evt.preventDefault(); evt = joint.util.normalizeEvent(evt); var view = this.findView(evt.target); var localPoint = this.snapToGrid({ x: evt.clientX, y: evt.clientY }); if (view) { view.pointerdblclick(evt, localPoint.x, localPoint.y); } else { this.trigger('blank:pointerdblclick', evt, localPoint.x, localPoint.y); } }, mouseclick: function(evt) { // Trigger event when mouse not moved. if (!this._mousemoved) { evt.preventDefault(); evt = joint.util.normalizeEvent(evt); var view = this.findView(evt.target); var localPoint = this.snapToGrid({ x: evt.clientX, y: evt.clientY }); if (view) { view.pointerclick(evt, localPoint.x, localPoint.y); } else { this.trigger('blank:pointerclick', evt, localPoint.x, localPoint.y); } } this._mousemoved = false; }, pointerdown: function(evt) { evt.preventDefault(); evt = joint.util.normalizeEvent(evt); var view = this.findView(evt.target); var localPoint = this.snapToGrid({ x: evt.clientX, y: evt.clientY }); if (view) { this.sourceView = view; view.pointerdown(evt, localPoint.x, localPoint.y); } else { this.trigger('blank:pointerdown', evt, localPoint.x, localPoint.y); } }, pointermove: function(evt) { evt.preventDefault(); evt = joint.util.normalizeEvent(evt); if (this.sourceView) { // Mouse moved. this._mousemoved = true; var localPoint = this.snapToGrid({ x: evt.clientX, y: evt.clientY }); this.sourceView.pointermove(evt, localPoint.x, localPoint.y); } }, pointerup: function(evt) { evt = joint.util.normalizeEvent(evt); var localPoint = this.snapToGrid({ x: evt.clientX, y: evt.clientY }); if (this.sourceView) { this.sourceView.pointerup(evt, localPoint.x, localPoint.y); //"delete sourceView" occasionally throws an error in chrome (illegal access exception) this.sourceView = null; } else { this.trigger('blank:pointerup', evt, localPoint.x, localPoint.y); } } }); // JointJS library. // (c) 2011-2013 client IO if (typeof exports === 'object') { var joint = { util: require('../src/core').util, shapes: {}, dia: { Element: require('../src/joint.dia.element').Element, ElementView: require('../src/joint.dia.element').ElementView } }; var _ = require('lodash'); } joint.shapes.basic = {}; joint.shapes.basic.Generic = joint.dia.Element.extend({ defaults: joint.util.deepSupplement({ type: 'basic.Generic', attrs: { '.': { fill: '#FFFFFF', stroke: 'none' } } }, joint.dia.Element.prototype.defaults) }); joint.shapes.basic.Rect = joint.shapes.basic.Generic.extend({ markup: '<g class="rotatable"><g class="scalable"><rect/></g><text/></g>', defaults: joint.util.deepSupplement({ type: 'basic.Rect', attrs: { 'rect': { fill: '#FFFFFF', stroke: 'black', width: 100, height: 60 }, 'text': { 'font-size': 14, text: '', 'ref-x': .5, 'ref-y': .5, ref: 'rect', 'y-alignment': 'middle', 'x-alignment': 'middle', fill: 'black', 'font-family': 'Arial, helvetica, sans-serif' } } }, joint.shapes.basic.Generic.prototype.defaults) }); joint.shapes.basic.Text = joint.shapes.basic.Generic.extend({ markup: '<g class="rotatable"><g class="scalable"><text/></g></g>', defaults: joint.util.deepSupplement({ type: 'basic.Text', attrs: { 'text': { 'font-size': 18, fill: 'black' } } }, joint.shapes.basic.Generic.prototype.defaults) }); joint.shapes.basic.Circle = joint.shapes.basic.Generic.extend({ markup: '<g class="rotatable"><g class="scalable"><circle/></g><text/></g>', defaults: joint.util.deepSupplement({ type: 'basic.Circle', size: { width: 60, height: 60 }, attrs: { 'circle': { fill: '#FFFFFF', stroke: 'black', r: 30, transform: 'translate(30, 30)' }, 'text': { 'font-size': 14, text: '', 'text-anchor': 'middle', 'ref-x': .5, 'ref-y': .5, ref: 'circle', 'y-alignment': 'middle', fill: 'black', 'font-family': 'Arial, helvetica, sans-serif' } } }, joint.shapes.basic.Generic.prototype.defaults) }); joint.shapes.basic.Image = joint.shapes.basic.Generic.extend({ markup: '<g class="rotatable"><g class="scalable"><image/></g><text/></g>', defaults: joint.util.deepSupplement({ type: 'basic.Image', attrs: { 'text': { 'font-size': 14, text: '', 'text-anchor': 'middle', 'ref-x': .5, 'ref-dy': 20, ref: 'image', 'y-alignment': 'middle', fill: 'black', 'font-family': 'Arial, helvetica, sans-serif' } } }, joint.shapes.basic.Generic.prototype.defaults) }); joint.shapes.basic.Path = joint.shapes.basic.Generic.extend({ markup: '<g class="rotatable"><g class="scalable"><path/></g><text/></g>', defaults: joint.util.deepSupplement({ type: 'basic.Path', size: { width: 60, height: 60 }, attrs: { 'path': { fill: '#FFFFFF', stroke: 'black' }, 'text': { 'font-size': 14, text: '', 'text-anchor': 'middle', 'ref-x': .5, 'ref-dy': 20, ref: 'path', 'y-alignment': 'middle', fill: 'black', 'font-family': 'Arial, helvetica, sans-serif' } } }, joint.shapes.basic.Generic.prototype.defaults) }); joint.shapes.basic.Rhombus = joint.shapes.basic.Path.extend({ defaults: joint.util.deepSupplement({ type: 'basic.Rhombus', attrs: { 'path': { d: 'M 30 0 L 60 30 30 60 0 30 z' }, 'text': { 'ref-y': .5 } } }, joint.shapes.basic.Path.prototype.defaults) }); // PortsModelInterface is a common interface for shapes that have ports. This interface makes it easy // to create new shapes with ports functionality. It is assumed that the new shapes have // `inPorts` and `outPorts` array properties. Only these properties should be used to set ports. // In other words, using this interface, it is no longer recommended to set ports directly through the // `attrs` object. // Usage: // joint.shapes.custom.MyElementWithPorts = joint.shapes.basic.Path.extend(_.extend({}, joint.shapes.basic.PortsModelInterface, { // getPortAttrs: function(portName, index, total, selector, type) { // var attrs = {}; // var portClass = 'port' + index; // var portSelector = selector + '>.' + portClass; // var portTextSelector = portSelector + '>text'; // var portCircleSelector = portSelector + '>circle'; // // attrs[portTextSelector] = { text: portName }; // attrs[portCircleSelector] = { port: { id: portName || _.uniqueId(type) , type: type } }; // attrs[portSelector] = { ref: 'rect', 'ref-y': (index + 0.5) * (1 / total) }; // // if (selector === '.outPorts') { attrs[portSelector]['ref-dx'] = 0; } // // return attrs; // } //})); joint.shapes.basic.PortsModelInterface = { initialize: function() { this.updatePortsAttrs(); this.on('change:inPorts change:outPorts', this.updatePortsAttrs, this); // Call the `initialize()` of the parent. this.constructor.__super__.constructor.__super__.initialize.apply(this, arguments); }, updatePortsAttrs: function(eventName) { // Delete previously set attributes for ports. var currAttrs = this.get('attrs'); _.each(this._portSelectors, function(selector) { if (currAttrs[selector]) delete currAttrs[selector]; }); // This holds keys to the `attrs` object for all the port specific attribute that // we set in this method. This is necessary in order to remove previously set // attributes for previous ports. this._portSelectors = []; var attrs = {}; _.each(this.get('inPorts'), function(portName, index, ports) { var portAttributes = this.getPortAttrs(portName, index, ports.length, '.inPorts', 'in'); this._portSelectors = this._portSelectors.concat(_.keys(portAttributes)); _.extend(attrs, portAttributes); }, this); _.each(this.get('outPorts'), function(portName, index, ports) { var portAttributes = this.getPortAttrs(portName, index, ports.length, '.outPorts', 'out'); this._portSelectors = this._portSelectors.concat(_.keys(portAttributes)); _.extend(attrs, portAttributes); }, this); // Silently set `attrs` on the cell so that noone knows the attrs have changed. This makes sure // that, for example, command manager does not register `change:attrs` command but only // the important `change:inPorts`/`change:outPorts` command. this.attr(attrs, { silent: true }); // Manually call the `processPorts()` method that is normally called on `change:attrs` (that we just made silent). this.processPorts(); // Let the outside world (mainly the `ModelView`) know that we're done configuring the `attrs` object. this.trigger('process:ports'); }, getPortSelector: function(name) { var selector = '.inPorts'; var index = this.get('inPorts').indexOf(name); if (index < 0) { selector = '.outPorts'; index = this.get('outPorts').indexOf(name); if (index < 0) throw new Error("getPortSelector(): Port doesn't exist."); } return selector + '>g:nth-child(' + (index + 1) + ')>circle'; } }; joint.shapes.basic.PortsViewInterface = { initialize: function() { // `Model` emits the `process:ports` whenever it's done configuring the `attrs` object for ports. this.listenTo(this.model, 'process:ports', this.update); joint.dia.ElementView.prototype.initialize.apply(this, arguments); }, update: function() { // First render ports so that `attrs` can be applied to those newly created DOM elements // in `ElementView.prototype.update()`. this.renderPorts(); joint.dia.ElementView.prototype.update.apply(this, arguments); }, renderPorts: function() { var $inPorts = this.$('.inPorts').empty(); var $outPorts = this.$('.outPorts').empty(); var portTemplate = _.template(this.model.portMarkup); _.each(_.filter(this.model.ports, function(p) { return p.type === 'in' }), function(port, index) { $inPorts.append(V(portTemplate({ id: index, port: port })).node); }); _.each(_.filter(this.model.ports, function(p) { return p.type === 'out' }), function(port, index) { $outPorts.append(V(portTemplate({ id: index, port: port })).node); }); } }; joint.shapes.basic.TextBlock = joint.shapes.basic.Generic.extend({ markup: ['<g class="rotatable"><g class="scalable"><rect/></g><switch>', // if foreignObject supported '<foreignObject requiredFeatures="http://www.w3.org/TR/SVG11/feature#Extensibility" class="fobj">', '<body xmlns="http://www.w3.org/1999/xhtml"><div/></body>', '</foreignObject>', // else foreignObject is not supported (fallback for IE) '<text class="content"/>', '</switch></g>'].join(''), defaults: joint.util.deepSupplement({ type: 'basic.TextBlock', // see joint.css for more element styles attrs: { rect: { fill: '#ffffff', stroke: '#000000', width: 80, height: 100 }, text: { fill: '#000000', 'font-size': 14, 'font-family': 'Arial, helvetica, sans-serif' }, '.content': { text: '', ref: 'rect', 'ref-x': .5, 'ref-y': .5, 'y-alignment': 'middle', 'x-alignment': 'middle' } }, content: '' }, joint.shapes.basic.Generic.prototype.defaults), initialize: function() { if (typeof SVGForeignObjectElement !== 'undefined') { // foreignObject supported this.setForeignObjectSize(this, this.get('size')); this.setDivContent(this, this.get('content')); this.listenTo(this, 'change:size', this.setForeignObjectSize); this.listenTo(this, 'change:content', this.setDivContent); } joint.shapes.basic.Generic.prototype.initialize.apply(this, arguments); }, setForeignObjectSize: function(cell, size) { // Selector `foreignObject' doesn't work accross all browsers, we'r using class selector instead. // We have to clone size as we don't want attributes.div.style to be same object as attributes.size. cell.attr({ '.fobj': _.clone(size), div: { style: _.clone(size) } }); }, setDivContent: function(cell, content) { // Append the content to div as html. cell.attr({ div : { html: content }}); } }); // TextBlockView implements the fallback for IE when no foreignObject exists and // the text needs to be manually broken. joint.shapes.basic.TextBlockView = joint.dia.ElementView.extend({ initialize: function() { joint.dia.ElementView.prototype.initialize.apply(this, arguments); if (typeof SVGForeignObjectElement === 'undefined') { this.noSVGForeignObjectElement = true; this.listenTo(this.model, 'change:content', function(cell) { // avoiding pass of extra paramters this.updateContent(cell); }); } }, update: function(cell, renderingOnlyAttrs) { if (this.noSVGForeignObjectElement) { var model = this.model; // Update everything but the content first. var noTextAttrs = _.omit(renderingOnlyAttrs || model.get('attrs'), '.content'); joint.dia.ElementView.prototype.update.call(this, model, noTextAttrs); if (!renderingOnlyAttrs || _.has(renderingOnlyAttrs, '.content')) { // Update the content itself. this.updateContent(model, renderingOnlyAttrs); } } else { joint.dia.ElementView.prototype.update.call(this, model, renderingOnlyAttrs); } }, updateContent: function(cell, renderingOnlyAttrs) { // Create copy of the text attributes var textAttrs = _.merge({}, (renderingOnlyAttrs || cell.get('attrs'))['.content']); delete textAttrs.text; // Break the content to fit the element size taking into account the attributes // set on the model. var text = joint.util.breakText(cell.get('content'), cell.get('size'), textAttrs, { // measuring sandbox svg document svgDocument: this.paper.svg }); // Create a new attrs with same structure as the model attrs { text: { *textAttributes* }} var attrs = joint.util.setByPath({}, '.content', textAttrs,'/'); // Replace text attribute with the one we just processed. attrs['.content'].text = text; // Update the view using renderingOnlyAttributes parameter. joint.dia.ElementView.prototype.update.call(this, cell, attrs); } }); if (typeof exports === 'object') { module.exports = joint.shapes.basic; } joint.routers.orthogonal = function() { var sourceBBox, targetBBox; // Return the direction that one would have to take traveling from `p1` to `p2`. // This function assumes the line between `p1` and `p2` is orthogonal. function direction(p1, p2) { if (p1.y < p2.y && p1.x === p2.x) { return 'down'; } else if (p1.y > p2.y && p1.x === p2.x) { return 'up'; } else if (p1.x < p2.x && p1.y === p2.y) { return 'right'; } return 'left'; } function bestDirection(p1, p2, preferredDirection) { var directions; // This branching determines possible directions that one can take to travel // from `p1` to `p2`. if (p1.x < p2.x) { if (p1.y > p2.y) { directions = ['up', 'right']; } else if (p1.y < p2.y) { directions = ['down', 'right']; } else { directions = ['right']; } } else if (p1.x > p2.x) { if (p1.y > p2.y) { directions = ['up', 'left']; } else if (p1.y < p2.y) { directions = ['down', 'left']; } else { directions = ['left']; } } else { if (p1.y > p2.y) { directions = ['up']; } else { directions = ['down']; } } if (_.contains(directions, preferredDirection)) { return preferredDirection; } var direction = _.first(directions); // Should the direction be the exact opposite of the preferred direction, // try another one if such direction exists. switch (preferredDirection) { case 'down': if (direction === 'up') return _.last(directions); break; case 'up': if (direction === 'down') return _.last(directions); break; case 'left': if (direction === 'right') return _.last(directions); break; case 'right': if (direction === 'left') return _.last(directions); break; } return direction; }; // Find a vertex in between the vertices `p1` and `p2` so that the route between those vertices // is orthogonal. Prefer going the direction determined by `preferredDirection`. function findMiddleVertex(p1, p2, preferredDirection) { var direction = bestDirection(p1, p2, preferredDirection); if (direction === 'down' || direction === 'up') { return { x: p1.x, y: p2.y, d: direction }; } return { x: p2.x, y: p1.y, d: direction }; } // Return points that one needs to draw a connection through in order to have a orthogonal link // routing from source to target going through `vertices`. function findOrthogonalRoute(vertices) { vertices = (vertices || []).slice(); var orthogonalVertices = []; var sourceCenter = sourceBBox.center(); var targetCenter = targetBBox.center(); if (!vertices.length) { if (Math.abs(sourceCenter.x - targetCenter.x) < (sourceBBox.width / 2) || Math.abs(sourceCenter.y - targetCenter.y) < (sourceBBox.height / 2) ) { vertices = [{ x: Math.min(sourceCenter.x, targetCenter.x) + Math.abs(sourceCenter.x - targetCenter.x) / 2, y: Math.min(sourceCenter.y, targetCenter.y) + Math.abs(sourceCenter.y - targetCenter.y) / 2 }]; } } vertices.unshift(sourceCenter); vertices.push(targetCenter); var orthogonalVertex; var lastOrthogonalVertex; var vertex; var nextVertex; // For all the pairs of link model vertices... for (var i = 0; i < vertices.length - 1; i++) { vertex = vertices[i]; nextVertex = vertices[i + 1]; lastOrthogonalVertex = _.last(orthogonalVertices); if (i > 0) { // Push all the link vertices to the orthogonal route. orthogonalVertex = vertex; // Determine a direction between the last vertex and the new one. // Therefore, each vertex contains the `d` property describing the direction that one // would have to take to travel to that vertex. orthogonalVertex.d = lastOrthogonalVertex ? direction(lastOrthogonalVertex, vertex) : 'top'; orthogonalVertices.push(orthogonalVertex); lastOrthogonalVertex = orthogonalVertex; } // Make sure that we don't create a vertex that would go the opposite direction then // that of the previous one. // Othwerwise, a 'spike' segment would be created which is not desirable. // Find a dummy vertex to keep the link orthogonal. Preferably, take the same direction // as the previous one. var d = lastOrthogonalVertex && lastOrthogonalVertex.d; orthogonalVertex = findMiddleVertex(vertex, nextVertex, d); // Do not add a new vertex that is the same as one of the vertices already added. if (!g.point(orthogonalVertex).equals(g.point(vertex)) && !g.point(orthogonalVertex).equals(g.point(nextVertex))) { orthogonalVertices.push(orthogonalVertex); } } return orthogonalVertices; }; return function(vertices) { sourceBBox = this.sourceBBox; targetBBox = this.targetBBox; return findOrthogonalRoute(vertices); }; }(); joint.routers.manhattan = (function() { 'use strict'; var config = { // size of the step to find a route step: 10, // use of the perpendicular linkView option to connect center of element with first vertex perpendicular: true, // tells how to divide the paper when creating the elements map mapGridSize: 100, // should be source or target not to be consider as an obstacle excludeEnds: [], // 'source', 'target' // should be any element with a certain type not to be consider as an obstacle excludeTypes: ['basic.Text'], // if number of route finding loops exceed the maximum, stops searching and returns // fallback route maximumLoops: 500, // possible starting directions from an element startDirections: ['left','right','top','bottom'], // possible ending directions to an element endDirections: ['left','right','top','bottom'], // specify directions above directionMap: { right: { x: 1, y: 0 }, bottom: { x: 0, y: 1 }, left: { x: -1, y: 0 }, top: { x: 0, y: -1 } }, // maximum change of the direction maxAllowedDirectionChange: 1, // padding applied on the element bounding boxes paddingBox: function() { var step = this.step; return { x: -step, y: -step, width: 2*step, height: 2*step } }, // an array of directions to find next points on the route directions: function() { var step = this.step; return [ { offsetX: step , offsetY: 0 , cost: step }, { offsetX: 0 , offsetY: step , cost: step }, { offsetX: -step , offsetY: 0 , cost: step }, { offsetX: 0 , offsetY: -step , cost: step } ]; }, // a penalty received for direction change penalties: function() { return [0, this.step / 2, this.step]; }, // heurestic method to determine the distance between two points estimateCost: function(from, to) { return from.manhattanDistance(to); }, // a simple route used in situations, when main routing method fails // (exceed loops, inaccessible). fallbackRoute: function(from, to, opts) { // Find an orthogonal route ignoring obstacles. var prevDirIndexes = opts.prevDirIndexes || {}; var point = (prevDirIndexes[from] || 0) % 2 ? g.point(from.x, to.y) : g.point(to.x, from.y); return [point, to]; }, // if a function is provided, it's used to route the link while dragging an end // i.e. function(from, to, opts) { return []; } draggingRoute: null }; // reconstructs a route by concating points with their parents function reconstructRoute(parents, point) { var route = []; var prevDiff = { x: 0, y: 0 }; var current = point; var parent; while ((parent = parents[current])) { var diff = parent.difference(current); if (!diff.equals(prevDiff)) { route.unshift(current); prevDiff = diff; } current = parent; } route.unshift(current); return route; }; // find points around the rectangle taking given directions in the account function getRectPoints(bbox, directionList, opts) { var step = opts.step; var center = bbox.center(); var startPoints = _.chain(opts.directionMap).pick(directionList).map(function(direction) { var x = direction.x * bbox.width / 2; var y = direction.y * bbox.height / 2; var point = g.point(center).offset(x,y).snapToGrid(step); if (bbox.containsPoint(point)) { point.offset(direction.x * step, direction.y * step); } return point; }).value(); return startPoints; }; // returns a direction index from start point to end point function getDirection(start, end, dirLen) { var dirAngle = 360 / dirLen; var q = Math.floor(start.theta(end) / dirAngle); return dirLen - q; } // finds the route between to points/rectangles implementing A* alghoritm function findRoute(start, end, map, opt) { var startDirections = opt.reversed ? opt.endDirections : opt.startDirections; var endDirections = opt.reversed ? opt.startDirections : opt.endDirections; // set of points we start pathfinding from var startSet = start instanceof g.rect ? getRectPoints(start, startDirections, opt) : [start]; // set of points we want the pathfinding to finish at var endSet = end instanceof g.rect ? getRectPoints(end, endDirections, opt) : [end]; var startCenter = startSet.length > 1 ? start.center() : startSet[0]; var endCenter = endSet.length > 1 ? end.center() : endSet[0]; // take into account only accessible end points var endPoints = _.filter(endSet, function(point) { var mapKey = g.point(point).snapToGrid(opt.mapGridSize).toString(); var accesible = _.every(map[mapKey], function(obstacle) { return !obstacle.containsPoint(point); }); return accesible; }); if (endPoints.length) { var step = opt.step; var penalties = opt.penalties; // choose the end point with the shortest estimated path cost var endPoint = _.chain(endPoints).invoke('snapToGrid', step).min(function(point) { return opt.estimateCost(startCenter, point); }).value(); var parents = {}; var costFromStart = {}; var totalCost = {}; // directions var dirs = opt.directions; var dirLen = dirs.length; var dirHalfLen = dirLen / 2; var dirIndexes = opt.previousDirIndexes || {}; // The set of point already evaluated. var closeHash = {}; // keeps only information whether a point was evaluated' // The set of tentative points to be evaluated, initially containing the start points var openHash = {}; // keeps only information whether a point is to be evaluated' var openSet = _.chain(startSet).invoke('snapToGrid', step).each(function(point) { var key = point.toString(); costFromStart[key] = 0; // Cost from start along best known path. totalCost[key] = opt.estimateCost(point, endPoint); dirIndexes[key] = dirIndexes[key] || getDirection(startCenter, point, dirLen); openHash[key] = true; }).map(function(point) { return point.toString(); }).sortBy(function(pointKey) { return totalCost[pointKey]; }).value(); var loopCounter = opt.maximumLoops; var maxAllowedDirectionChange = opt.maxAllowedDirectionChange; // main route finding loop while (openSet.length && loopCounter--) { var currentKey = openSet[0]; var currentPoint = g.point(currentKey); if (endPoint.equals(currentPoint)) { opt.previousDirIndexes = _.pick(dirIndexes, currentKey); return reconstructRoute(parents, currentPoint); } // remove current from the open list openSet.splice(0, 1); openHash[neighborKey] = null; // add current to the close list closeHash[neighborKey] = true; var currentDirIndex = dirIndexes[currentKey]; var currentDist = costFromStart[currentKey]; for (var dirIndex = 0; dirIndex < dirLen; dirIndex++) { var dirChange = Math.abs(dirIndex - currentDirIndex); if (dirChange > dirHalfLen) { dirChange = dirLen - dirChange; } // if the direction changed rapidly don't use this point if (dirChange > maxAllowedDirectionChange) { continue; } var dir = dirs[dirIndex]; var neighborPoint = g.point(currentPoint).offset(dir.offsetX, dir.offsetY); var neighborKey = neighborPoint.toString(); if (closeHash[neighborKey]) { continue; } // is point accesible - no obstacle in the way var mapKey = g.point(neighborPoint).snapToGrid(opt.mapGridSize).toString(); var isAccesible = _.every(map[mapKey], function(obstacle) { return !obstacle.containsPoint(neighborPoint); }); if (!isAccesible) { continue; } var inOpenSet = _.has(openHash, neighborKey); var costToNeighbor = currentDist + dir.cost; if (!inOpenSet || costToNeighbor < costFromStart[neighborKey]) { parents[neighborKey] = currentPoint; dirIndexes[neighborKey] = dirIndex; costFromStart[neighborKey] = costToNeighbor; totalCost[neighborKey] = costToNeighbor + opt.estimateCost(neighborPoint, endPoint) + penalties[dirChange]; if (!inOpenSet) { var openIndex = _.sortedIndex(openSet, neighborKey, function(openKey) { return totalCost[openKey]; }); openSet.splice(openIndex, 0, neighborKey); openHash[neighborKey] = true; } }; }; } } // no route found ('to' point wasn't either accessible or finding route took // way to much calculations) return opt.fallbackRoute(startCenter, endCenter, opt); }; // initiation of the route finding function router(oldVertices, opt) { // resolve some of the options opt.directions = _.result(opt, 'directions'); opt.penalties = _.result(opt, 'penalties'); opt.paddingBox = _.result(opt, 'paddingBox'); // enable/disable linkView perpendicular option this.options.perpendicular = !!opt.perpendicular; // As route changes its shape rapidly when we start finding route from different point // it's necessary to start from the element that was not interacted with // (the position was changed) at very last. var reverseRouting = opt.reversed = (this.lastEndChange === 'source'); var sourceBBox = reverseRouting ? g.rect(this.targetBBox) : g.rect(this.sourceBBox); var targetBBox = reverseRouting ? g.rect(this.sourceBBox) : g.rect(this.targetBBox); // expand boxes by specific padding sourceBBox.moveAndExpand(opt.paddingBox); targetBBox.moveAndExpand(opt.paddingBox); // building an elements map var link = this.model; var graph = this.paper.model; // source or target element could be excluded from set of obstacles var excludedEnds = _.chain(opt.excludeEnds) .map(link.get, link) .pluck('id') .map(graph.getCell, graph).value(); var mapGridSize = opt.mapGridSize; // builds a map of all elements for quicker obstacle queries (i.e. is a point contained // in any obstacle?) (a simplified grid search) // The paper is divided to smaller cells, where each of them holds an information which // elements belong to it. When we query whether a point is in an obstacle we don't need // to go through all obstacles, we check only those in a particular cell. var map = _.chain(graph.getElements()) // remove source and target element if required .difference(excludedEnds) // remove all elements whose type is listed in excludedTypes array .reject(function(element) { return _.contains(opt.excludeTypes, element.get('type')); }) // change elements (models) to their bounding boxes .invoke('getBBox') // expand their boxes by specific padding .invoke('moveAndExpand', opt.paddingBox) // build the map .foldl(function(res, bbox) { var origin = bbox.origin().snapToGrid(mapGridSize); var corner = bbox.corner().snapToGrid(mapGridSize); for (var x = origin.x; x <= corner.x; x += mapGridSize) { for (var y = origin.y; y <= corner.y; y += mapGridSize) { var gridKey = x + '@' + y; res[gridKey] = res[gridKey] || []; res[gridKey].push(bbox); } } return res; }, {}).value(); // pathfinding var newVertices = []; var points = _.map(oldVertices, g.point); var tailPoint = sourceBBox.center(); // find a route by concating all partial routes (routes need to go through the vertices) // startElement -> vertex[1] -> ... -> vertex[n] -> endElement for (var i = 0, len = points.length; i <= len; i++) { var partialRoute = null; var from = to || sourceBBox; var to = points[i]; if (!to) { to = targetBBox; // 'to' is not a vertex. If the target is a point (i.e. it's not an element), we // might use dragging route instead of main routing method if that is enabled. var endingAtPoint = !this.model.get('source').id || !this.model.get('target').id; if (endingAtPoint && _.isFunction(opt.draggingRoute)) { // Make sure we passing points only (not rects). var dragFrom = from instanceof g.rect ? from.center() : from; partialRoute = opt.draggingRoute(dragFrom, to.origin(), opt); } } // if partial route has not been calculated yet use the main routing method to find one partialRoute = partialRoute || findRoute(from, to, map, opt); var leadPoint = _.first(partialRoute); if (leadPoint && leadPoint.equals(tailPoint)) { // remove the first point if the previous partial route had the same point as last partialRoute.shift(); } tailPoint = _.last(partialRoute) || tailPoint; newVertices = newVertices.concat(partialRoute); }; // we might have to reverse the result if we swapped source and target at the beginning return reverseRouting ? newVertices.reverse() : newVertices; }; // public function return function(vertices, opt, linkView) { return router.call(linkView, vertices, _.extend({}, config, opt)); }; })(); joint.routers.metro = (function() { if (!_.isFunction(joint.routers.manhattan)) { throw('Metro requires the manhattan router.'); } var config = { // cost of a diagonal step (calculated if not defined). diagonalCost: null, // an array of directions to find next points on the route directions: function() { var step = this.step; var diagonalCost = this.diagonalCost || Math.ceil(Math.sqrt(step * step << 1)); return [ { offsetX: step , offsetY: 0 , cost: step }, { offsetX: step , offsetY: step , cost: diagonalCost }, { offsetX: 0 , offsetY: step , cost: step }, { offsetX: -step , offsetY: step , cost: diagonalCost }, { offsetX: -step , offsetY: 0 , cost: step }, { offsetX: -step , offsetY: -step , cost: diagonalCost }, { offsetX: 0 , offsetY: -step , cost: step }, { offsetX: step , offsetY: -step , cost: diagonalCost } ]; }, // a simple route used in situations, when main routing method fails // (exceed loops, inaccessible). fallbackRoute: function(from, to, opts) { // Find a route which breaks by 45 degrees ignoring all obstacles. var theta = from.theta(to); var a = { x: to.x, y: from.y }; var b = { x: from.x, y: to.y }; if (theta % 180 > 90) { var t = a; a = b; b = t; } var p1 = (theta % 90) < 45 ? a : b; var l1 = g.line(from, p1); var alpha = 90 * Math.ceil(theta / 90); var p2 = g.point.fromPolar(l1.squaredLength(), g.toRad(alpha + 135), p1); var l2 = g.line(to, p2); var point = l1.intersection(l2); return point ? [point.round(), to] : [to]; } }; // public function return function(vertices, opts, linkView) { return joint.routers.manhattan(vertices, _.extend({}, config, opts), linkView); }; })(); joint.connectors.normal = function(sourcePoint, targetPoint, vertices) { // Construct the `d` attribute of the `<path>` element. var d = ['M', sourcePoint.x, sourcePoint.y]; _.each(vertices, function(vertex) { d.push(vertex.x, vertex.y); }); d.push(targetPoint.x, targetPoint.y); return d.join(' '); }; joint.connectors.rounded = function(sourcePoint, targetPoint, vertices, opts) { var offset = opts.radius || 10; var c1, c2, d1, d2, prev, next; // Construct the `d` attribute of the `<path>` element. var d = ['M', sourcePoint.x, sourcePoint.y]; _.each(vertices, function(vertex, index) { // the closest vertices prev = vertices[index-1] || sourcePoint; next = vertices[index+1] || targetPoint; // a half distance to the closest vertex d1 = d2 || g.point(vertex).distance(prev) / 2; d2 = g.point(vertex).distance(next) / 2; // control points c1 = g.point(vertex).move(prev, -Math.min(offset, d1)).round(); c2 = g.point(vertex).move(next, -Math.min(offset, d2)).round(); d.push(c1.x, c1.y, 'S', vertex.x, vertex.y, c2.x, c2.y, 'L'); }); d.push(targetPoint.x, targetPoint.y); return d.join(' '); }; joint.connectors.smooth = function(sourcePoint, targetPoint, vertices) { var d; if (vertices.length) { d = g.bezier.curveThroughPoints([sourcePoint].concat(vertices).concat([targetPoint])); } else { // if we have no vertices use a default cubic bezier curve, cubic bezier requires // two control points. The two control points are both defined with X as mid way // between the source and target points. SourceControlPoint Y is equal to sourcePoint Y // and targetControlPointY being equal to targetPointY. Handle situation were // sourcePointX is greater or less then targetPointX. var controlPointX = (sourcePoint.x < targetPoint.x) ? targetPoint.x - ((targetPoint.x - sourcePoint.x) / 2) : sourcePoint.x - ((sourcePoint.x - targetPoint.x) / 2); d = [ 'M', sourcePoint.x, sourcePoint.y, 'C', controlPointX, sourcePoint.y, controlPointX, targetPoint.y, targetPoint.x, targetPoint.y ]; } return d.join(' '); };
docs/src/pages/system/spacing/HorizontalCentering.js
allanalexandre/material-ui
import React from 'react'; import Box from '@material-ui/core/Box'; function HorizontalCentering() { return ( <div> <Box mx="auto" bgcolor="background.paper" p={1}> Centered element </Box> </div> ); } export default HorizontalCentering;
src/components/markdown/htags.js
Hacker0x01/react-storybook-addon-info
import React from 'react'; import { baseFonts } from '../theme'; export class H1 extends React.Component { render() { const styles = { ...baseFonts, borderBottom: '1px solid #eee', fontWeight: 600, margin: 0, padding: 0, fontSize: '40', }; return <h1 id={this.props.id} style={styles}>{this.props.children}</h1>; } } export class H2 extends React.Component { render() { const styles = { ...baseFonts, fontWeight: 600, margin: 0, padding: 0, fontSize: '30', }; return <h2 id={this.props.id} style={styles}>{this.props.children}</h2>; } } export class H3 extends React.Component { render() { const styles = { ...baseFonts, fontWeight: 600, margin: 0, padding: 0, fontSize: '22', textTransform: 'uppercase', }; return <h3 id={this.props.id} style={styles}>{this.props.children}</h3>; } } export class H4 extends React.Component { render() { const styles = { ...baseFonts, fontWeight: 600, margin: 0, padding: 0, fontSize: '20', }; return <h4 id={this.props.id} style={styles}>{this.props.children}</h4>; } } export class H5 extends React.Component { render() { const styles = { ...baseFonts, fontWeight: 600, margin: 0, padding: 0, fontSize: '18', }; return <h5 id={this.props.id} style={styles}>{this.props.children}</h5>; } } export class H6 extends React.Component { render() { const styles = { ...baseFonts, fontWeight: 400, margin: 0, padding: 0, fontSize: '18', }; return <h6 id={this.props.id} style={styles}>{this.props.children}</h6>; } }
src/components/note_form.js
asommer70/thehoick-notes-server
import React, { Component } from 'react'; import { Link, browserHistory } from 'react-router' import cookie from 'react-cookie'; import Store from '../lib/store'; var store = new Store(); var socket = io(); class NoteForm extends Component { constructor(props) { super(props); this.username = cookie.load('username'); this.state = {id: '', title: '', text: '', users: [this.username], tags: [], created_by: this.username, new: true, currentUsers: [this.username]}; if (!this.username) { this.props.history.push('/login'); } if (props.route.path != '/notes/new') { store.findNote(this.props.params.id, (error, note) => { console.log('note:', note); this.setState({ id: note.id, title: note.get('title'), text: note.get('text'), users: note.get('users'), tags: note.get('tags'), created_by: note.get('created_by'), new: false }, (note) => { console.log('this.state.currentUsers:', this.state.currentUsers); document.getElementById('text').style.height = document.getElementById('text').scrollHeight + 5 + 'px'; }); }); } socket.on('text-entered', (obj) => { console.log('txt:', obj.txt, 'name:', obj.name); if (obj.platform != 'web') { var newState = {}; newState[obj.name] = obj.txt; // Add the new Note user if it's they're not already in the list. var currentUsers = this.state.currentUsers; if (currentUsers.indexOf(obj.username) === -1) { currentUsers.push(obj.username); newState.currentUsers = currentUsers; } this.setState(newState); } }); } saveNote(event) { console.log('saveNote this.state:', this.state); if (this.state.new) { // Create Note. store.createNote(this.state, (error, note) => { if (error) { console.log('saveNote error:', error); } this.setState({note}); this.props.history.push('/notes'); }); } else { // Update Note. if (this.state.users.indexOf(this.username) === -1) { var users = this.state.users; users.push(this.username); this.setState({users: users}, () => { store.updateNote(this.state, (error, note) => { if (error) { console.log('saveNote error:', error); } console.log('saveNote updated note:', note); this.setState({note}); console.log('this.props:', this.props); this.props.history.push(`/notes/${note.id}`); }); }) } else { store.updateNote(this.state, (error, note) => { if (error) { console.log('saveNote error:', error); } console.log('saveNote updated note:', note); this.setState({note}); console.log('this.props:', this.props); this.props.history.push(`/notes/${note.id}`); }); } } } deleteNote(event) { console.log('deleting note...'); store.deleteNote(this.state, (status) => { console.log('deleteNote status:', status); this.props.history.push('/notes'); }); } textChange(event) { this.setState({text: event.target.value}); socket.emit('text-entered', {txt: event.target.value, name: event.target.name, platform: 'web', username: this.username}); } textChange(event) { this.setState({text: event.target.value}); socket.emit('text-entered', {txt: event.target.value, name: event.target.name, platform: 'web', username: this.username}); } render() { var deleteButton = <span></span>; if (!this.state.new) { deleteButton = <input type="submit" className="button is-small is-outlined is-danger" value="Delete Note" onClick={this.deleteNote.bind(this)} />; } return ( <div> <div className="card"> <div className="card-content"> <h3 className="title is-4">{this.state.new ? 'New Note' : `Edit Note: ${this.state.title}`}</h3> <div className="columns"> <div className="column is-4"> <label htmlFor="title">{this.state.new ? '' : 'Title'}</label> <input name="title" id="title" type="text" placeholder="Title" value={this.state.title} onChange={event => this.titleChange(event).bind(this)} /> </div> </div> <div className="columns"> <div className="column is-4"> <label htmlFor="text">{this.state.new ? '' : 'Text'}</label> <textarea name="text" id="text" placeholder="Text" value={this.state.text} onChange={event => this.textChange(event).bind(this)}></textarea> </div> </div> <div className="columns"> <div className="column is-4"> <div className="user-info"> <span className="subtitle">Users:</span> <ul className="users"> {this.state.users.map((user, index) => { return <li key={index}>{user}</li> })} </ul> </div> </div> </div> <div className="columns"> <div className="column is-4"> <div className="user-info"> <span className="subtitle">Current Users:</span> <ul className="users"> {this.state.currentUsers.map((user, index) => { return <li key={index}> <span className="tag is-warning">{user}</span> </li> })} </ul> </div> </div> </div> <div className="columns"> <div className="column is-12"> <ul className="tags"> {this.state.tags.map((tag, index) => { return <li key={index}> <span className="tag is-info"> {tag} <button className="delete"></button> </span> </li> })} </ul> </div> </div> <div className="columns"> <div className="column is-4"> <input type="submit" className="button is-success" value="Save Note" onClick={this.saveNote.bind(this)} /> </div> </div> <div className="columns is-pulled-right"> <div className="column is-2"> {deleteButton} </div> </div> <br/> </div> </div> </div> ) } } export default NoteForm;
webpack/scenes/SmartProxy/Content.js
Katello/katello
import React from 'react'; import PropTypes from 'prop-types'; import SmartProxyContentTable from './SmartProxyContentTable'; const Content = ({ smartProxyId }) => ( <SmartProxyContentTable smartProxyId={smartProxyId} /> ); Content.propTypes = { smartProxyId: PropTypes.number, }; Content.defaultProps = { smartProxyId: null, }; export default Content;
node_modules/react-native/local-cli/library/library.js
reallin/MyReact-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'; const copyAndReplace = require('../util/copyAndReplace'); const fs = require('fs'); const isValidPackageName = require('../util/isValidPackageName'); const parseCommandLine = require('../util/parseCommandLine'); const path = require('path'); const Promise = require('promise'); const walk = require('../util/walk'); /** * Creates a new native library with the given name */ function library(argv, config) { return new Promise((resolve, reject) => { _library(argv, config, resolve, reject); }); } function _library(argv, config, resolve, reject) { const args = parseCommandLine([{ command: 'name', description: 'Library name', type: 'string', required: true, }], argv); if (!isValidPackageName(args.name)) { reject( args.name + ' is not a valid name for a project. Please use a valid ' + 'identifier name (alphanumeric).' ); } const root = process.cwd(); const libraries = path.resolve(root, 'Libraries'); const libraryDest = path.resolve(libraries, args.name); const source = path.resolve('node_modules', 'react-native', 'Libraries', 'Sample'); if (!fs.existsSync(libraries)) { fs.mkdir(libraries); } if (fs.existsSync(libraryDest)) { reject('Library already exists in', libraryDest); } walk(source).forEach(f => { if (f.indexOf('project.xcworkspace') !== -1 || f.indexOf('.xcodeproj/xcuserdata') !== -1) { return; } const dest = f.replace(/Sample/g, args.name).replace(/^_/, '.'); copyAndReplace( path.resolve(source, f), path.resolve(libraryDest, dest), {'Sample': args.name} ); }); console.log('Created library in', libraryDest); console.log('Next Steps:'); console.log(' Link your library in Xcode:'); console.log(' https://facebook.github.io/react-native/docs/linking-libraries-ios.html#content\n'); resolve(); } module.exports = library;
sites/all/libraries/wvega-timepicker/external/jquery-1.6.2.min.js
baiqj/ybzx
/*! * jQuery JavaScript Library v1.6.2 * http://jquery.com/ * * Copyright 2011, John Resig * Dual licensed under the MIT or GPL Version 2 licenses. * http://jquery.org/license * * Includes Sizzle.js * http://sizzlejs.com/ * Copyright 2011, The Dojo Foundation * Released under the MIT, BSD, and GPL Licenses. * * Date: Thu Jun 30 14:16:56 2011 -0400 */ (function(a,b){function cv(a){return f.isWindow(a)?a:a.nodeType===9?a.defaultView||a.parentWindow:!1}function cs(a){if(!cg[a]){var b=c.body,d=f("<"+a+">").appendTo(b),e=d.css("display");d.remove();if(e==="none"||e===""){ch||(ch=c.createElement("iframe"),ch.frameBorder=ch.width=ch.height=0),b.appendChild(ch);if(!ci||!ch.createElement)ci=(ch.contentWindow||ch.contentDocument).document,ci.write((c.compatMode==="CSS1Compat"?"<!doctype html>":"")+"<html><body>"),ci.close();d=ci.createElement(a),ci.body.appendChild(d),e=f.css(d,"display"),b.removeChild(ch)}cg[a]=e}return cg[a]}function cr(a,b){var c={};f.each(cm.concat.apply([],cm.slice(0,b)),function(){c[this]=a});return c}function cq(){cn=b}function cp(){setTimeout(cq,0);return cn=f.now()}function cf(){try{return new a.ActiveXObject("Microsoft.XMLHTTP")}catch(b){}}function ce(){try{return new a.XMLHttpRequest}catch(b){}}function b$(a,c){a.dataFilter&&(c=a.dataFilter(c,a.dataType));var d=a.dataTypes,e={},g,h,i=d.length,j,k=d[0],l,m,n,o,p;for(g=1;g<i;g++){if(g===1)for(h in a.converters)typeof h=="string"&&(e[h.toLowerCase()]=a.converters[h]);l=k,k=d[g];if(k==="*")k=l;else if(l!=="*"&&l!==k){m=l+" "+k,n=e[m]||e["* "+k];if(!n){p=b;for(o in e){j=o.split(" ");if(j[0]===l||j[0]==="*"){p=e[j[1]+" "+k];if(p){o=e[o],o===!0?n=p:p===!0&&(n=o);break}}}}!n&&!p&&f.error("No conversion from "+m.replace(" "," to ")),n!==!0&&(c=n?n(c):p(o(c)))}}return c}function bZ(a,c,d){var e=a.contents,f=a.dataTypes,g=a.responseFields,h,i,j,k;for(i in g)i in d&&(c[g[i]]=d[i]);while(f[0]==="*")f.shift(),h===b&&(h=a.mimeType||c.getResponseHeader("content-type"));if(h)for(i in e)if(e[i]&&e[i].test(h)){f.unshift(i);break}if(f[0]in d)j=f[0];else{for(i in d){if(!f[0]||a.converters[i+" "+f[0]]){j=i;break}k||(k=i)}j=j||k}if(j){j!==f[0]&&f.unshift(j);return d[j]}}function bY(a,b,c,d){if(f.isArray(b))f.each(b,function(b,e){c||bC.test(a)?d(a,e):bY(a+"["+(typeof e=="object"||f.isArray(e)?b:"")+"]",e,c,d)});else if(!c&&b!=null&&typeof b=="object")for(var e in b)bY(a+"["+e+"]",b[e],c,d);else d(a,b)}function bX(a,c,d,e,f,g){f=f||c.dataTypes[0],g=g||{},g[f]=!0;var h=a[f],i=0,j=h?h.length:0,k=a===bR,l;for(;i<j&&(k||!l);i++)l=h[i](c,d,e),typeof l=="string"&&(!k||g[l]?l=b:(c.dataTypes.unshift(l),l=bX(a,c,d,e,l,g)));(k||!l)&&!g["*"]&&(l=bX(a,c,d,e,"*",g));return l}function bW(a){return function(b,c){typeof b!="string"&&(c=b,b="*");if(f.isFunction(c)){var d=b.toLowerCase().split(bN),e=0,g=d.length,h,i,j;for(;e<g;e++)h=d[e],j=/^\+/.test(h),j&&(h=h.substr(1)||"*"),i=a[h]=a[h]||[],i[j?"unshift":"push"](c)}}}function bA(a,b,c){var d=b==="width"?a.offsetWidth:a.offsetHeight,e=b==="width"?bv:bw;if(d>0){c!=="border"&&f.each(e,function(){c||(d-=parseFloat(f.css(a,"padding"+this))||0),c==="margin"?d+=parseFloat(f.css(a,c+this))||0:d-=parseFloat(f.css(a,"border"+this+"Width"))||0});return d+"px"}d=bx(a,b,b);if(d<0||d==null)d=a.style[b]||0;d=parseFloat(d)||0,c&&f.each(e,function(){d+=parseFloat(f.css(a,"padding"+this))||0,c!=="padding"&&(d+=parseFloat(f.css(a,"border"+this+"Width"))||0),c==="margin"&&(d+=parseFloat(f.css(a,c+this))||0)});return d+"px"}function bm(a,b){b.src?f.ajax({url:b.src,async:!1,dataType:"script"}):f.globalEval((b.text||b.textContent||b.innerHTML||"").replace(be,"/*$0*/")),b.parentNode&&b.parentNode.removeChild(b)}function bl(a){f.nodeName(a,"input")?bk(a):"getElementsByTagName"in a&&f.grep(a.getElementsByTagName("input"),bk)}function bk(a){if(a.type==="checkbox"||a.type==="radio")a.defaultChecked=a.checked}function bj(a){return"getElementsByTagName"in a?a.getElementsByTagName("*"):"querySelectorAll"in a?a.querySelectorAll("*"):[]}function bi(a,b){var c;if(b.nodeType===1){b.clearAttributes&&b.clearAttributes(),b.mergeAttributes&&b.mergeAttributes(a),c=b.nodeName.toLowerCase();if(c==="object")b.outerHTML=a.outerHTML;else if(c!=="input"||a.type!=="checkbox"&&a.type!=="radio"){if(c==="option")b.selected=a.defaultSelected;else if(c==="input"||c==="textarea")b.defaultValue=a.defaultValue}else a.checked&&(b.defaultChecked=b.checked=a.checked),b.value!==a.value&&(b.value=a.value);b.removeAttribute(f.expando)}}function bh(a,b){if(b.nodeType===1&&!!f.hasData(a)){var c=f.expando,d=f.data(a),e=f.data(b,d);if(d=d[c]){var g=d.events;e=e[c]=f.extend({},d);if(g){delete e.handle,e.events={};for(var h in g)for(var i=0,j=g[h].length;i<j;i++)f.event.add(b,h+(g[h][i].namespace?".":"")+g[h][i].namespace,g[h][i],g[h][i].data)}}}}function bg(a,b){return f.nodeName(a,"table")?a.getElementsByTagName("tbody")[0]||a.appendChild(a.ownerDocument.createElement("tbody")):a}function W(a,b,c){b=b||0;if(f.isFunction(b))return f.grep(a,function(a,d){var e=!!b.call(a,d,a);return e===c});if(b.nodeType)return f.grep(a,function(a,d){return a===b===c});if(typeof b=="string"){var d=f.grep(a,function(a){return a.nodeType===1});if(R.test(b))return f.filter(b,d,!c);b=f.filter(b,d)}return f.grep(a,function(a,d){return f.inArray(a,b)>=0===c})}function V(a){return!a||!a.parentNode||a.parentNode.nodeType===11}function N(a,b){return(a&&a!=="*"?a+".":"")+b.replace(z,"`").replace(A,"&")}function M(a){var b,c,d,e,g,h,i,j,k,l,m,n,o,p=[],q=[],r=f._data(this,"events");if(!(a.liveFired===this||!r||!r.live||a.target.disabled||a.button&&a.type==="click")){a.namespace&&(n=new RegExp("(^|\\.)"+a.namespace.split(".").join("\\.(?:.*\\.)?")+"(\\.|$)")),a.liveFired=this;var s=r.live.slice(0);for(i=0;i<s.length;i++)g=s[i],g.origType.replace(x,"")===a.type?q.push(g.selector):s.splice(i--,1);e=f(a.target).closest(q,a.currentTarget);for(j=0,k=e.length;j<k;j++){m=e[j];for(i=0;i<s.length;i++){g=s[i];if(m.selector===g.selector&&(!n||n.test(g.namespace))&&!m.elem.disabled){h=m.elem,d=null;if(g.preType==="mouseenter"||g.preType==="mouseleave")a.type=g.preType,d=f(a.relatedTarget).closest(g.selector)[0],d&&f.contains(h,d)&&(d=h);(!d||d!==h)&&p.push({elem:h,handleObj:g,level:m.level})}}}for(j=0,k=p.length;j<k;j++){e=p[j];if(c&&e.level>c)break;a.currentTarget=e.elem,a.data=e.handleObj.data,a.handleObj=e.handleObj,o=e.handleObj.origHandler.apply(e.elem,arguments);if(o===!1||a.isPropagationStopped()){c=e.level,o===!1&&(b=!1);if(a.isImmediatePropagationStopped())break}}return b}}function K(a,c,d){var e=f.extend({},d[0]);e.type=a,e.originalEvent={},e.liveFired=b,f.event.handle.call(c,e),e.isDefaultPrevented()&&d[0].preventDefault()}function E(){return!0}function D(){return!1}function m(a,c,d){var e=c+"defer",g=c+"queue",h=c+"mark",i=f.data(a,e,b,!0);i&&(d==="queue"||!f.data(a,g,b,!0))&&(d==="mark"||!f.data(a,h,b,!0))&&setTimeout(function(){!f.data(a,g,b,!0)&&!f.data(a,h,b,!0)&&(f.removeData(a,e,!0),i.resolve())},0)}function l(a){for(var b in a)if(b!=="toJSON")return!1;return!0}function k(a,c,d){if(d===b&&a.nodeType===1){var e="data-"+c.replace(j,"$1-$2").toLowerCase();d=a.getAttribute(e);if(typeof d=="string"){try{d=d==="true"?!0:d==="false"?!1:d==="null"?null:f.isNaN(d)?i.test(d)?f.parseJSON(d):d:parseFloat(d)}catch(g){}f.data(a,c,d)}else d=b}return d}var c=a.document,d=a.navigator,e=a.location,f=function(){function J(){if(!e.isReady){try{c.documentElement.doScroll("left")}catch(a){setTimeout(J,1);return}e.ready()}}var e=function(a,b){return new e.fn.init(a,b,h)},f=a.jQuery,g=a.$,h,i=/^(?:[^<]*(<[\w\W]+>)[^>]*$|#([\w\-]*)$)/,j=/\S/,k=/^\s+/,l=/\s+$/,m=/\d/,n=/^<(\w+)\s*\/?>(?:<\/\1>)?$/,o=/^[\],:{}\s]*$/,p=/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g,q=/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g,r=/(?:^|:|,)(?:\s*\[)+/g,s=/(webkit)[ \/]([\w.]+)/,t=/(opera)(?:.*version)?[ \/]([\w.]+)/,u=/(msie) ([\w.]+)/,v=/(mozilla)(?:.*? rv:([\w.]+))?/,w=/-([a-z])/ig,x=function(a,b){return b.toUpperCase()},y=d.userAgent,z,A,B,C=Object.prototype.toString,D=Object.prototype.hasOwnProperty,E=Array.prototype.push,F=Array.prototype.slice,G=String.prototype.trim,H=Array.prototype.indexOf,I={};e.fn=e.prototype={constructor:e,init:function(a,d,f){var g,h,j,k;if(!a)return this;if(a.nodeType){this.context=this[0]=a,this.length=1;return this}if(a==="body"&&!d&&c.body){this.context=c,this[0]=c.body,this.selector=a,this.length=1;return this}if(typeof a=="string"){a.charAt(0)!=="<"||a.charAt(a.length-1)!==">"||a.length<3?g=i.exec(a):g=[null,a,null];if(g&&(g[1]||!d)){if(g[1]){d=d instanceof e?d[0]:d,k=d?d.ownerDocument||d:c,j=n.exec(a),j?e.isPlainObject(d)?(a=[c.createElement(j[1])],e.fn.attr.call(a,d,!0)):a=[k.createElement(j[1])]:(j=e.buildFragment([g[1]],[k]),a=(j.cacheable?e.clone(j.fragment):j.fragment).childNodes);return e.merge(this,a)}h=c.getElementById(g[2]);if(h&&h.parentNode){if(h.id!==g[2])return f.find(a);this.length=1,this[0]=h}this.context=c,this.selector=a;return this}return!d||d.jquery?(d||f).find(a):this.constructor(d).find(a)}if(e.isFunction(a))return f.ready(a);a.selector!==b&&(this.selector=a.selector,this.context=a.context);return e.makeArray(a,this)},selector:"",jquery:"1.6.2",length:0,size:function(){return this.length},toArray:function(){return F.call(this,0)},get:function(a){return a==null?this.toArray():a<0?this[this.length+a]:this[a]},pushStack:function(a,b,c){var d=this.constructor();e.isArray(a)?E.apply(d,a):e.merge(d,a),d.prevObject=this,d.context=this.context,b==="find"?d.selector=this.selector+(this.selector?" ":"")+c:b&&(d.selector=this.selector+"."+b+"("+c+")");return d},each:function(a,b){return e.each(this,a,b)},ready:function(a){e.bindReady(),A.done(a);return this},eq:function(a){return a===-1?this.slice(a):this.slice(a,+a+1)},first:function(){return this.eq(0)},last:function(){return this.eq(-1)},slice:function(){return this.pushStack(F.apply(this,arguments),"slice",F.call(arguments).join(","))},map:function(a){return this.pushStack(e.map(this,function(b,c){return a.call(b,c,b)}))},end:function(){return this.prevObject||this.constructor(null)},push:E,sort:[].sort,splice:[].splice},e.fn.init.prototype=e.fn,e.extend=e.fn.extend=function(){var a,c,d,f,g,h,i=arguments[0]||{},j=1,k=arguments.length,l=!1;typeof i=="boolean"&&(l=i,i=arguments[1]||{},j=2),typeof i!="object"&&!e.isFunction(i)&&(i={}),k===j&&(i=this,--j);for(;j<k;j++)if((a=arguments[j])!=null)for(c in a){d=i[c],f=a[c];if(i===f)continue;l&&f&&(e.isPlainObject(f)||(g=e.isArray(f)))?(g?(g=!1,h=d&&e.isArray(d)?d:[]):h=d&&e.isPlainObject(d)?d:{},i[c]=e.extend(l,h,f)):f!==b&&(i[c]=f)}return i},e.extend({noConflict:function(b){a.$===e&&(a.$=g),b&&a.jQuery===e&&(a.jQuery=f);return e},isReady:!1,readyWait:1,holdReady:function(a){a?e.readyWait++:e.ready(!0)},ready:function(a){if(a===!0&&!--e.readyWait||a!==!0&&!e.isReady){if(!c.body)return setTimeout(e.ready,1);e.isReady=!0;if(a!==!0&&--e.readyWait>0)return;A.resolveWith(c,[e]),e.fn.trigger&&e(c).trigger("ready").unbind("ready")}},bindReady:function(){if(!A){A=e._Deferred();if(c.readyState==="complete")return setTimeout(e.ready,1);if(c.addEventListener)c.addEventListener("DOMContentLoaded",B,!1),a.addEventListener("load",e.ready,!1);else if(c.attachEvent){c.attachEvent("onreadystatechange",B),a.attachEvent("onload",e.ready);var b=!1;try{b=a.frameElement==null}catch(d){}c.documentElement.doScroll&&b&&J()}}},isFunction:function(a){return e.type(a)==="function"},isArray:Array.isArray||function(a){return e.type(a)==="array"},isWindow:function(a){return a&&typeof a=="object"&&"setInterval"in a},isNaN:function(a){return a==null||!m.test(a)||isNaN(a)},type:function(a){return a==null?String(a):I[C.call(a)]||"object"},isPlainObject:function(a){if(!a||e.type(a)!=="object"||a.nodeType||e.isWindow(a))return!1;if(a.constructor&&!D.call(a,"constructor")&&!D.call(a.constructor.prototype,"isPrototypeOf"))return!1;var c;for(c in a);return c===b||D.call(a,c)},isEmptyObject:function(a){for(var b in a)return!1;return!0},error:function(a){throw a},parseJSON:function(b){if(typeof b!="string"||!b)return null;b=e.trim(b);if(a.JSON&&a.JSON.parse)return a.JSON.parse(b);if(o.test(b.replace(p,"@").replace(q,"]").replace(r,"")))return(new Function("return "+b))();e.error("Invalid JSON: "+b)},parseXML:function(b,c,d){a.DOMParser?(d=new DOMParser,c=d.parseFromString(b,"text/xml")):(c=new ActiveXObject("Microsoft.XMLDOM"),c.async="false",c.loadXML(b)),d=c.documentElement,(!d||!d.nodeName||d.nodeName==="parsererror")&&e.error("Invalid XML: "+b);return c},noop:function(){},globalEval:function(b){b&&j.test(b)&&(a.execScript||function(b){a.eval.call(a,b)})(b)},camelCase:function(a){return a.replace(w,x)},nodeName:function(a,b){return a.nodeName&&a.nodeName.toUpperCase()===b.toUpperCase()},each:function(a,c,d){var f,g=0,h=a.length,i=h===b||e.isFunction(a);if(d){if(i){for(f in a)if(c.apply(a[f],d)===!1)break}else for(;g<h;)if(c.apply(a[g++],d)===!1)break}else if(i){for(f in a)if(c.call(a[f],f,a[f])===!1)break}else for(;g<h;)if(c.call(a[g],g,a[g++])===!1)break;return a},trim:G?function(a){return a==null?"":G.call(a)}:function(a){return a==null?"":(a+"").replace(k,"").replace(l,"")},makeArray:function(a,b){var c=b||[];if(a!=null){var d=e.type(a);a.length==null||d==="string"||d==="function"||d==="regexp"||e.isWindow(a)?E.call(c,a):e.merge(c,a)}return c},inArray:function(a,b){if(H)return H.call(b,a);for(var c=0,d=b.length;c<d;c++)if(b[c]===a)return c;return-1},merge:function(a,c){var d=a.length,e=0;if(typeof c.length=="number")for(var f=c.length;e<f;e++)a[d++]=c[e];else while(c[e]!==b)a[d++]=c[e++];a.length=d;return a},grep:function(a,b,c){var d=[],e;c=!!c;for(var f=0,g=a.length;f<g;f++)e=!!b(a[f],f),c!==e&&d.push(a[f]);return d},map:function(a,c,d){var f,g,h=[],i=0,j=a.length,k=a instanceof e||j!==b&&typeof j=="number"&&(j>0&&a[0]&&a[j-1]||j===0||e.isArray(a));if(k)for(;i<j;i++)f=c(a[i],i,d),f!=null&&(h[h.length]=f);else for(g in a)f=c(a[g],g,d),f!=null&&(h[h.length]=f);return h.concat.apply([],h)},guid:1,proxy:function(a,c){if(typeof c=="string"){var d=a[c];c=a,a=d}if(!e.isFunction(a))return b;var f=F.call(arguments,2),g=function(){return a.apply(c,f.concat(F.call(arguments)))};g.guid=a.guid=a.guid||g.guid||e.guid++;return g},access:function(a,c,d,f,g,h){var i=a.length;if(typeof c=="object"){for(var j in c)e.access(a,j,c[j],f,g,d);return a}if(d!==b){f=!h&&f&&e.isFunction(d);for(var k=0;k<i;k++)g(a[k],c,f?d.call(a[k],k,g(a[k],c)):d,h);return a}return i?g(a[0],c):b},now:function(){return(new Date).getTime()},uaMatch:function(a){a=a.toLowerCase();var b=s.exec(a)||t.exec(a)||u.exec(a)||a.indexOf("compatible")<0&&v.exec(a)||[];return{browser:b[1]||"",version:b[2]||"0"}},sub:function(){function a(b,c){return new a.fn.init(b,c)}e.extend(!0,a,this),a.superclass=this,a.fn=a.prototype=this(),a.fn.constructor=a,a.sub=this.sub,a.fn.init=function(d,f){f&&f instanceof e&&!(f instanceof a)&&(f=a(f));return e.fn.init.call(this,d,f,b)},a.fn.init.prototype=a.fn;var b=a(c);return a},browser:{}}),e.each("Boolean Number String Function Array Date RegExp Object".split(" "),function(a,b){I["[object "+b+"]"]=b.toLowerCase()}),z=e.uaMatch(y),z.browser&&(e.browser[z.browser]=!0,e.browser.version=z.version),e.browser.webkit&&(e.browser.safari=!0),j.test(" ")&&(k=/^[\s\xA0]+/,l=/[\s\xA0]+$/),h=e(c),c.addEventListener?B=function(){c.removeEventListener("DOMContentLoaded",B,!1),e.ready()}:c.attachEvent&&(B=function(){c.readyState==="complete"&&(c.detachEvent("onreadystatechange",B),e.ready())});return e}(),g="done fail isResolved isRejected promise then always pipe".split(" "),h=[].slice;f.extend({_Deferred:function(){var a=[],b,c,d,e={done:function(){if(!d){var c=arguments,g,h,i,j,k;b&&(k=b,b=0);for(g=0,h=c.length;g<h;g++)i=c[g],j=f.type(i),j==="array"?e.done.apply(e,i):j==="function"&&a.push(i);k&&e.resolveWith(k[0],k[1])}return this},resolveWith:function(e,f){if(!d&&!b&&!c){f=f||[],c=1;try{while(a[0])a.shift().apply(e,f)}finally{b=[e,f],c=0}}return this},resolve:function(){e.resolveWith(this,arguments);return this},isResolved:function(){return!!c||!!b},cancel:function(){d=1,a=[];return this}};return e},Deferred:function(a){var b=f._Deferred(),c=f._Deferred(),d;f.extend(b,{then:function(a,c){b.done(a).fail(c);return this},always:function(){return b.done.apply(b,arguments).fail.apply(this,arguments)},fail:c.done,rejectWith:c.resolveWith,reject:c.resolve,isRejected:c.isResolved,pipe:function(a,c){return f.Deferred(function(d){f.each({done:[a,"resolve"],fail:[c,"reject"]},function(a,c){var e=c[0],g=c[1],h;f.isFunction(e)?b[a](function(){h=e.apply(this,arguments),h&&f.isFunction(h.promise)?h.promise().then(d.resolve,d.reject):d[g](h)}):b[a](d[g])})}).promise()},promise:function(a){if(a==null){if(d)return d;d=a={}}var c=g.length;while(c--)a[g[c]]=b[g[c]];return a}}),b.done(c.cancel).fail(b.cancel),delete b.cancel,a&&a.call(b,b);return b},when:function(a){function i(a){return function(c){b[a]=arguments.length>1?h.call(arguments,0):c,--e||g.resolveWith(g,h.call(b,0))}}var b=arguments,c=0,d=b.length,e=d,g=d<=1&&a&&f.isFunction(a.promise)?a:f.Deferred();if(d>1){for(;c<d;c++)b[c]&&f.isFunction(b[c].promise)?b[c].promise().then(i(c),g.reject):--e;e||g.resolveWith(g,b)}else g!==a&&g.resolveWith(g,d?[a]:[]);return g.promise()}}),f.support=function(){var a=c.createElement("div"),b=c.documentElement,d,e,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u;a.setAttribute("className","t"),a.innerHTML=" <link/><table></table><a href='/a' style='top:1px;float:left;opacity:.55;'>a</a><input type='checkbox'/>",d=a.getElementsByTagName("*"),e=a.getElementsByTagName("a")[0];if(!d||!d.length||!e)return{};g=c.createElement("select"),h=g.appendChild(c.createElement("option")),i=a.getElementsByTagName("input")[0],k={leadingWhitespace:a.firstChild.nodeType===3,tbody:!a.getElementsByTagName("tbody").length,htmlSerialize:!!a.getElementsByTagName("link").length,style:/top/.test(e.getAttribute("style")),hrefNormalized:e.getAttribute("href")==="/a",opacity:/^0.55$/.test(e.style.opacity),cssFloat:!!e.style.cssFloat,checkOn:i.value==="on",optSelected:h.selected,getSetAttribute:a.className!=="t",submitBubbles:!0,changeBubbles:!0,focusinBubbles:!1,deleteExpando:!0,noCloneEvent:!0,inlineBlockNeedsLayout:!1,shrinkWrapBlocks:!1,reliableMarginRight:!0},i.checked=!0,k.noCloneChecked=i.cloneNode(!0).checked,g.disabled=!0,k.optDisabled=!h.disabled;try{delete a.test}catch(v){k.deleteExpando=!1}!a.addEventListener&&a.attachEvent&&a.fireEvent&&(a.attachEvent("onclick",function(){k.noCloneEvent=!1}),a.cloneNode(!0).fireEvent("onclick")),i=c.createElement("input"),i.value="t",i.setAttribute("type","radio"),k.radioValue=i.value==="t",i.setAttribute("checked","checked"),a.appendChild(i),l=c.createDocumentFragment(),l.appendChild(a.firstChild),k.checkClone=l.cloneNode(!0).cloneNode(!0).lastChild.checked,a.innerHTML="",a.style.width=a.style.paddingLeft="1px",m=c.getElementsByTagName("body")[0],o=c.createElement(m?"div":"body"),p={visibility:"hidden",width:0,height:0,border:0,margin:0},m&&f.extend(p,{position:"absolute",left:-1e3,top:-1e3});for(t in p)o.style[t]=p[t];o.appendChild(a),n=m||b,n.insertBefore(o,n.firstChild),k.appendChecked=i.checked,k.boxModel=a.offsetWidth===2,"zoom"in a.style&&(a.style.display="inline",a.style.zoom=1,k.inlineBlockNeedsLayout=a.offsetWidth===2,a.style.display="",a.innerHTML="<div style='width:4px;'></div>",k.shrinkWrapBlocks=a.offsetWidth!==2),a.innerHTML="<table><tr><td style='padding:0;border:0;display:none'></td><td>t</td></tr></table>",q=a.getElementsByTagName("td"),u=q[0].offsetHeight===0,q[0].style.display="",q[1].style.display="none",k.reliableHiddenOffsets=u&&q[0].offsetHeight===0,a.innerHTML="",c.defaultView&&c.defaultView.getComputedStyle&&(j=c.createElement("div"),j.style.width="0",j.style.marginRight="0",a.appendChild(j),k.reliableMarginRight=(parseInt((c.defaultView.getComputedStyle(j,null)||{marginRight:0}).marginRight,10)||0)===0),o.innerHTML="",n.removeChild(o);if(a.attachEvent)for(t in{submit:1,change:1,focusin:1})s="on"+t,u=s in a,u||(a.setAttribute(s,"return;"),u=typeof a[s]=="function"),k[t+"Bubbles"]=u;o=l=g=h=m=j=a=i=null;return k}(),f.boxModel=f.support.boxModel;var i=/^(?:\{.*\}|\[.*\])$/,j=/([a-z])([A-Z])/g;f.extend({cache:{},uuid:0,expando:"jQuery"+(f.fn.jquery+Math.random()).replace(/\D/g,""),noData:{embed:!0,object:"clsid:D27CDB6E-AE6D-11cf-96B8-444553540000",applet:!0},hasData:function(a){a=a.nodeType?f.cache[a[f.expando]]:a[f.expando];return!!a&&!l(a)},data:function(a,c,d,e){if(!!f.acceptData(a)){var g=f.expando,h=typeof c=="string",i,j=a.nodeType,k=j?f.cache:a,l=j?a[f.expando]:a[f.expando]&&f.expando;if((!l||e&&l&&!k[l][g])&&h&&d===b)return;l||(j?a[f.expando]=l=++f.uuid:l=f.expando),k[l]||(k[l]={},j||(k[l].toJSON=f.noop));if(typeof c=="object"||typeof c=="function")e?k[l][g]=f.extend(k[l][g],c):k[l]=f.extend(k[l],c);i=k[l],e&&(i[g]||(i[g]={}),i=i[g]),d!==b&&(i[f.camelCase(c)]=d);if(c==="events"&&!i[c])return i[g]&&i[g].events;return h?i[f.camelCase(c)]||i[c]:i}},removeData:function(b,c,d){if(!!f.acceptData(b)){var e=f.expando,g=b.nodeType,h=g?f.cache:b,i=g?b[f.expando]:f.expando;if(!h[i])return;if(c){var j=d?h[i][e]:h[i];if(j){delete j[c];if(!l(j))return}}if(d){delete h[i][e];if(!l(h[i]))return}var k=h[i][e];f.support.deleteExpando||h!=a?delete h[i]:h[i]=null,k?(h[i]={},g||(h[i].toJSON=f.noop),h[i][e]=k):g&&(f.support.deleteExpando?delete b[f.expando]:b.removeAttribute?b.removeAttribute(f.expando):b[f.expando]=null)}},_data:function(a,b,c){return f.data(a,b,c,!0)},acceptData:function(a){if(a.nodeName){var b=f.noData[a.nodeName.toLowerCase()];if(b)return b!==!0&&a.getAttribute("classid")===b}return!0}}),f.fn.extend({data:function(a,c){var d=null;if(typeof a=="undefined"){if(this.length){d=f.data(this[0]);if(this[0].nodeType===1){var e=this[0].attributes,g;for(var h=0,i=e.length;h<i;h++)g=e[h].name,g.indexOf("data-")===0&&(g=f.camelCase(g.substring(5)),k(this[0],g,d[g]))}}return d}if(typeof a=="object")return this.each(function(){f.data(this,a)});var j=a.split(".");j[1]=j[1]?"."+j[1]:"";if(c===b){d=this.triggerHandler("getData"+j[1]+"!",[j[0]]),d===b&&this.length&&(d=f.data(this[0],a),d=k(this[0],a,d));return d===b&&j[1]?this.data(j[0]):d}return this.each(function(){var b=f(this),d=[j[0],c];b.triggerHandler("setData"+j[1]+"!",d),f.data(this,a,c),b.triggerHandler("changeData"+j[1]+"!",d)})},removeData:function(a){return this.each(function(){f.removeData(this,a)})}}),f.extend({_mark:function(a,c){a&&(c=(c||"fx")+"mark",f.data(a,c,(f.data(a,c,b,!0)||0)+1,!0))},_unmark:function(a,c,d){a!==!0&&(d=c,c=a,a=!1);if(c){d=d||"fx";var e=d+"mark",g=a?0:(f.data(c,e,b,!0)||1)-1;g?f.data(c,e,g,!0):(f.removeData(c,e,!0),m(c,d,"mark"))}},queue:function(a,c,d){if(a){c=(c||"fx")+"queue";var e=f.data(a,c,b,!0);d&&(!e||f.isArray(d)?e=f.data(a,c,f.makeArray(d),!0):e.push(d));return e||[]}},dequeue:function(a,b){b=b||"fx";var c=f.queue(a,b),d=c.shift(),e;d==="inprogress"&&(d=c.shift()),d&&(b==="fx"&&c.unshift("inprogress"),d.call(a,function(){f.dequeue(a,b)})),c.length||(f.removeData(a,b+"queue",!0),m(a,b,"queue"))}}),f.fn.extend({queue:function(a,c){typeof a!="string"&&(c=a,a="fx");if(c===b)return f.queue(this[0],a);return this.each(function(){var b=f.queue(this,a,c);a==="fx"&&b[0]!=="inprogress"&&f.dequeue(this,a)})},dequeue:function(a){return this.each(function(){f.dequeue(this,a)})},delay:function(a,b){a=f.fx?f.fx.speeds[a]||a:a,b=b||"fx";return this.queue(b,function(){var c=this;setTimeout(function(){f.dequeue(c,b)},a)})},clearQueue:function(a){return this.queue(a||"fx",[])},promise:function(a,c){function m(){--h||d.resolveWith(e,[e])}typeof a!="string"&&(c=a,a=b),a=a||"fx";var d=f.Deferred(),e=this,g=e.length,h=1,i=a+"defer",j=a+"queue",k=a+"mark",l;while(g--)if(l=f.data(e[g],i,b,!0)||(f.data(e[g],j,b,!0)||f.data(e[g],k,b,!0))&&f.data(e[g],i,f._Deferred(),!0))h++,l.done(m);m();return d.promise()}});var n=/[\n\t\r]/g,o=/\s+/,p=/\r/g,q=/^(?:button|input)$/i,r=/^(?:button|input|object|select|textarea)$/i,s=/^a(?:rea)?$/i,t=/^(?:autofocus|autoplay|async|checked|controls|defer|disabled|hidden|loop|multiple|open|readonly|required|scoped|selected)$/i,u=/\:|^on/,v,w;f.fn.extend({attr:function(a,b){return f.access(this,a,b,!0,f.attr)},removeAttr:function(a){return this.each(function(){f.removeAttr(this,a)})},prop:function(a,b){return f.access(this,a,b,!0,f.prop)},removeProp:function(a){a=f.propFix[a]||a;return this.each(function(){try{this[a]=b,delete this[a]}catch(c){}})},addClass:function(a){var b,c,d,e,g,h,i;if(f.isFunction(a))return this.each(function(b){f(this).addClass(a.call(this,b,this.className))});if(a&&typeof a=="string"){b=a.split(o);for(c=0,d=this.length;c<d;c++){e=this[c];if(e.nodeType===1)if(!e.className&&b.length===1)e.className=a;else{g=" "+e.className+" ";for(h=0,i=b.length;h<i;h++)~g.indexOf(" "+b[h]+" ")||(g+=b[h]+" ");e.className=f.trim(g)}}}return this},removeClass:function(a){var c,d,e,g,h,i,j;if(f.isFunction(a))return this.each(function(b){f(this).removeClass(a.call(this,b,this.className))});if(a&&typeof a=="string"||a===b){c=(a||"").split(o);for(d=0,e=this.length;d<e;d++){g=this[d];if(g.nodeType===1&&g.className)if(a){h=(" "+g.className+" ").replace(n," ");for(i=0,j=c.length;i<j;i++)h=h.replace(" "+c[i]+" "," ");g.className=f.trim(h)}else g.className=""}}return this},toggleClass:function(a,b){var c=typeof a,d=typeof b=="boolean";if(f.isFunction(a))return this.each(function(c){f(this).toggleClass(a.call(this,c,this.className,b),b)});return this.each(function(){if(c==="string"){var e,g=0,h=f(this),i=b,j=a.split(o);while(e=j[g++])i=d?i:!h.hasClass(e),h[i?"addClass":"removeClass"](e)}else if(c==="undefined"||c==="boolean")this.className&&f._data(this,"__className__",this.className),this.className=this.className||a===!1?"":f._data(this,"__className__")||""})},hasClass:function(a){var b=" "+a+" ";for(var c=0,d=this.length;c<d;c++)if((" "+this[c].className+" ").replace(n," ").indexOf(b)>-1)return!0;return!1},val:function(a){var c,d,e=this[0];if(!arguments.length){if(e){c=f.valHooks[e.nodeName.toLowerCase()]||f.valHooks[e.type];if(c&&"get"in c&&(d=c.get(e,"value"))!==b)return d;d=e.value;return typeof d=="string"?d.replace(p,""):d==null?"":d}return b}var g=f.isFunction(a);return this.each(function(d){var e=f(this),h;if(this.nodeType===1){g?h=a.call(this,d,e.val()):h=a,h==null?h="":typeof h=="number"?h+="":f.isArray(h)&&(h=f.map(h,function(a){return a==null?"":a+""})),c=f.valHooks[this.nodeName.toLowerCase()]||f.valHooks[this.type];if(!c||!("set"in c)||c.set(this,h,"value")===b)this.value=h}})}}),f.extend({valHooks:{option:{get:function(a){var b=a.attributes.value;return!b||b.specified?a.value:a.text}},select:{get:function(a){var b,c=a.selectedIndex,d=[],e=a.options,g=a.type==="select-one";if(c<0)return null;for(var h=g?c:0,i=g?c+1:e.length;h<i;h++){var j=e[h];if(j.selected&&(f.support.optDisabled?!j.disabled:j.getAttribute("disabled")===null)&&(!j.parentNode.disabled||!f.nodeName(j.parentNode,"optgroup"))){b=f(j).val();if(g)return b;d.push(b)}}if(g&&!d.length&&e.length)return f(e[c]).val();return d},set:function(a,b){var c=f.makeArray(b);f(a).find("option").each(function(){this.selected=f.inArray(f(this).val(),c)>=0}),c.length||(a.selectedIndex=-1);return c}}},attrFn:{val:!0,css:!0,html:!0,text:!0,data:!0,width:!0,height:!0,offset:!0},attrFix:{tabindex:"tabIndex"},attr:function(a,c,d,e){var g=a.nodeType;if(!a||g===3||g===8||g===2)return b;if(e&&c in f.attrFn)return f(a)[c](d);if(!("getAttribute"in a))return f.prop(a,c,d);var h,i,j=g!==1||!f.isXMLDoc(a);j&&(c=f.attrFix[c]||c,i=f.attrHooks[c],i||(t.test(c)?i=w:v&&c!=="className"&&(f.nodeName(a,"form")||u.test(c))&&(i=v)));if(d!==b){if(d===null){f.removeAttr(a,c);return b}if(i&&"set"in i&&j&&(h=i.set(a,d,c))!==b)return h;a.setAttribute(c,""+d);return d}if(i&&"get"in i&&j&&(h=i.get(a,c))!==null)return h;h=a.getAttribute(c);return h===null?b:h},removeAttr:function(a,b){var c;a.nodeType===1&&(b=f.attrFix[b]||b,f.support.getSetAttribute?a.removeAttribute(b):(f.attr(a,b,""),a.removeAttributeNode(a.getAttributeNode(b))),t.test(b)&&(c=f.propFix[b]||b)in a&&(a[c]=!1))},attrHooks:{type:{set:function(a,b){if(q.test(a.nodeName)&&a.parentNode)f.error("type property can't be changed");else if(!f.support.radioValue&&b==="radio"&&f.nodeName(a,"input")){var c=a.value;a.setAttribute("type",b),c&&(a.value=c);return b}}},tabIndex:{get:function(a){var c=a.getAttributeNode("tabIndex");return c&&c.specified?parseInt(c.value,10):r.test(a.nodeName)||s.test(a.nodeName)&&a.href?0:b}},value:{get:function(a,b){if(v&&f.nodeName(a,"button"))return v.get(a,b);return b in a?a.value:null},set:function(a,b,c){if(v&&f.nodeName(a,"button"))return v.set(a,b,c);a.value=b}}},propFix:{tabindex:"tabIndex",readonly:"readOnly","for":"htmlFor","class":"className",maxlength:"maxLength",cellspacing:"cellSpacing",cellpadding:"cellPadding",rowspan:"rowSpan",colspan:"colSpan",usemap:"useMap",frameborder:"frameBorder",contenteditable:"contentEditable"},prop:function(a,c,d){var e=a.nodeType;if(!a||e===3||e===8||e===2)return b;var g,h,i=e!==1||!f.isXMLDoc(a);i&&(c=f.propFix[c]||c,h=f.propHooks[c]);return d!==b?h&&"set"in h&&(g=h.set(a,d,c))!==b?g:a[c]=d:h&&"get"in h&&(g=h.get(a,c))!==b?g:a[c]},propHooks:{}}),w={get:function(a,c){return f.prop(a,c)?c.toLowerCase():b},set:function(a,b,c){var d;b===!1?f.removeAttr(a,c):(d=f.propFix[c]||c,d in a&&(a[d]=!0),a.setAttribute(c,c.toLowerCase()));return c}},f.support.getSetAttribute||(f.attrFix=f.propFix,v=f.attrHooks.name=f.attrHooks.title=f.valHooks.button={get:function(a,c){var d;d=a.getAttributeNode(c);return d&&d.nodeValue!==""?d.nodeValue:b},set:function(a,b,c){var d=a.getAttributeNode(c);if(d){d.nodeValue=b;return b}}},f.each(["width","height"],function(a,b){f.attrHooks[b]=f.extend(f.attrHooks[b],{set:function(a,c){if(c===""){a.setAttribute(b,"auto");return c}}})})),f.support.hrefNormalized||f.each(["href","src","width","height"],function(a,c){f.attrHooks[c]=f.extend(f.attrHooks[c],{get:function(a){var d=a.getAttribute(c,2);return d===null?b:d}})}),f.support.style||(f.attrHooks.style={get:function(a){return a.style.cssText.toLowerCase()||b},set:function(a,b){return a.style.cssText=""+b}}),f.support.optSelected||(f.propHooks.selected=f.extend(f.propHooks.selected,{get:function(a){var b=a.parentNode;b&&(b.selectedIndex,b.parentNode&&b.parentNode.selectedIndex)}})),f.support.checkOn||f.each(["radio","checkbox"],function(){f.valHooks[this]={get:function(a){return a.getAttribute("value")===null?"on":a.value}}}),f.each(["radio","checkbox"],function(){f.valHooks[this]=f.extend(f.valHooks[this],{set:function(a,b){if(f.isArray(b))return a.checked=f.inArray(f(a).val(),b)>=0}})});var x=/\.(.*)$/,y=/^(?:textarea|input|select)$/i,z=/\./g,A=/ /g,B=/[^\w\s.|`]/g,C=function(a){return a.replace(B,"\\$&")};f.event={add:function(a,c,d,e){if(a.nodeType!==3&&a.nodeType!==8){if(d===!1)d=D;else if(!d)return;var g,h;d.handler&&(g=d,d=g.handler),d.guid||(d.guid=f.guid++);var i=f._data(a);if(!i)return;var j=i.events,k=i.handle;j||(i.events=j={}),k||(i.handle=k=function(a){return typeof f!="undefined"&&(!a||f.event.triggered!==a.type)?f.event.handle.apply(k.elem,arguments):b}),k.elem=a,c=c.split(" ");var l,m=0,n;while(l=c[m++]){h=g?f.extend({},g):{handler:d,data:e},l.indexOf(".")>-1?(n=l.split("."),l=n.shift(),h.namespace=n.slice(0).sort().join(".")):(n=[],h.namespace=""),h.type=l,h.guid||(h.guid=d.guid);var o=j[l],p=f.event.special[l]||{};if(!o){o=j[l]=[];if(!p.setup||p.setup.call(a,e,n,k)===!1)a.addEventListener?a.addEventListener(l,k,!1):a.attachEvent&&a.attachEvent("on"+l,k)}p.add&&(p.add.call(a,h),h.handler.guid||(h.handler.guid=d.guid)),o.push(h),f.event.global[l]=!0}a=null}},global:{},remove:function(a,c,d,e){if(a.nodeType!==3&&a.nodeType!==8){d===!1&&(d=D);var g,h,i,j,k=0,l,m,n,o,p,q,r,s=f.hasData(a)&&f._data(a),t=s&&s.events;if(!s||!t)return;c&&c.type&&(d=c.handler,c=c.type);if(!c||typeof c=="string"&&c.charAt(0)==="."){c=c||"";for(h in t)f.event.remove(a,h+c);return}c=c.split(" ");while(h=c[k++]){r=h,q=null,l=h.indexOf(".")<0,m=[],l||(m=h.split("."),h=m.shift(),n=new RegExp("(^|\\.)"+f.map(m.slice(0).sort(),C).join("\\.(?:.*\\.)?")+"(\\.|$)")),p=t[h];if(!p)continue;if(!d){for(j=0;j<p.length;j++){q=p[j];if(l||n.test(q.namespace))f.event.remove(a,r,q.handler,j),p.splice(j--,1)}continue}o=f.event.special[h]||{};for(j=e||0;j<p.length;j++){q=p[j];if(d.guid===q.guid){if(l||n.test(q.namespace))e==null&&p.splice(j--,1),o.remove&&o.remove.call(a,q);if(e!=null)break}}if(p.length===0||e!=null&&p.length===1)(!o.teardown||o.teardown.call(a,m)===!1)&&f.removeEvent(a,h,s.handle),g=null,delete t[h]}if(f.isEmptyObject(t)){var u=s.handle;u&&(u.elem=null),delete s.events,delete s.handle,f.isEmptyObject(s)&&f.removeData(a,b,!0)}}},customEvent:{getData:!0,setData:!0,changeData:!0},trigger:function(c,d,e,g){var h=c.type||c,i=[],j;h.indexOf("!")>=0&&(h=h.slice(0,-1),j=!0),h.indexOf(".")>=0&&(i=h.split("."),h=i. shift(),i.sort());if(!!e&&!f.event.customEvent[h]||!!f.event.global[h]){c=typeof c=="object"?c[f.expando]?c:new f.Event(h,c):new f.Event(h),c.type=h,c.exclusive=j,c.namespace=i.join("."),c.namespace_re=new RegExp("(^|\\.)"+i.join("\\.(?:.*\\.)?")+"(\\.|$)");if(g||!e)c.preventDefault(),c.stopPropagation();if(!e){f.each(f.cache,function(){var a=f.expando,b=this[a];b&&b.events&&b.events[h]&&f.event.trigger(c,d,b.handle.elem)});return}if(e.nodeType===3||e.nodeType===8)return;c.result=b,c.target=e,d=d!=null?f.makeArray(d):[],d.unshift(c);var k=e,l=h.indexOf(":")<0?"on"+h:"";do{var m=f._data(k,"handle");c.currentTarget=k,m&&m.apply(k,d),l&&f.acceptData(k)&&k[l]&&k[l].apply(k,d)===!1&&(c.result=!1,c.preventDefault()),k=k.parentNode||k.ownerDocument||k===c.target.ownerDocument&&a}while(k&&!c.isPropagationStopped());if(!c.isDefaultPrevented()){var n,o=f.event.special[h]||{};if((!o._default||o._default.call(e.ownerDocument,c)===!1)&&(h!=="click"||!f.nodeName(e,"a"))&&f.acceptData(e)){try{l&&e[h]&&(n=e[l],n&&(e[l]=null),f.event.triggered=h,e[h]())}catch(p){}n&&(e[l]=n),f.event.triggered=b}}return c.result}},handle:function(c){c=f.event.fix(c||a.event);var d=((f._data(this,"events")||{})[c.type]||[]).slice(0),e=!c.exclusive&&!c.namespace,g=Array.prototype.slice.call(arguments,0);g[0]=c,c.currentTarget=this;for(var h=0,i=d.length;h<i;h++){var j=d[h];if(e||c.namespace_re.test(j.namespace)){c.handler=j.handler,c.data=j.data,c.handleObj=j;var k=j.handler.apply(this,g);k!==b&&(c.result=k,k===!1&&(c.preventDefault(),c.stopPropagation()));if(c.isImmediatePropagationStopped())break}}return c.result},props:"altKey attrChange attrName bubbles button cancelable charCode clientX clientY ctrlKey currentTarget data detail eventPhase fromElement handler keyCode layerX layerY metaKey newValue offsetX offsetY pageX pageY prevValue relatedNode relatedTarget screenX screenY shiftKey srcElement target toElement view wheelDelta which".split(" "),fix:function(a){if(a[f.expando])return a;var d=a;a=f.Event(d);for(var e=this.props.length,g;e;)g=this.props[--e],a[g]=d[g];a.target||(a.target=a.srcElement||c),a.target.nodeType===3&&(a.target=a.target.parentNode),!a.relatedTarget&&a.fromElement&&(a.relatedTarget=a.fromElement===a.target?a.toElement:a.fromElement);if(a.pageX==null&&a.clientX!=null){var h=a.target.ownerDocument||c,i=h.documentElement,j=h.body;a.pageX=a.clientX+(i&&i.scrollLeft||j&&j.scrollLeft||0)-(i&&i.clientLeft||j&&j.clientLeft||0),a.pageY=a.clientY+(i&&i.scrollTop||j&&j.scrollTop||0)-(i&&i.clientTop||j&&j.clientTop||0)}a.which==null&&(a.charCode!=null||a.keyCode!=null)&&(a.which=a.charCode!=null?a.charCode:a.keyCode),!a.metaKey&&a.ctrlKey&&(a.metaKey=a.ctrlKey),!a.which&&a.button!==b&&(a.which=a.button&1?1:a.button&2?3:a.button&4?2:0);return a},guid:1e8,proxy:f.proxy,special:{ready:{setup:f.bindReady,teardown:f.noop},live:{add:function(a){f.event.add(this,N(a.origType,a.selector),f.extend({},a,{handler:M,guid:a.handler.guid}))},remove:function(a){f.event.remove(this,N(a.origType,a.selector),a)}},beforeunload:{setup:function(a,b,c){f.isWindow(this)&&(this.onbeforeunload=c)},teardown:function(a,b){this.onbeforeunload===b&&(this.onbeforeunload=null)}}}},f.removeEvent=c.removeEventListener?function(a,b,c){a.removeEventListener&&a.removeEventListener(b,c,!1)}:function(a,b,c){a.detachEvent&&a.detachEvent("on"+b,c)},f.Event=function(a,b){if(!this.preventDefault)return new f.Event(a,b);a&&a.type?(this.originalEvent=a,this.type=a.type,this.isDefaultPrevented=a.defaultPrevented||a.returnValue===!1||a.getPreventDefault&&a.getPreventDefault()?E:D):this.type=a,b&&f.extend(this,b),this.timeStamp=f.now(),this[f.expando]=!0},f.Event.prototype={preventDefault:function(){this.isDefaultPrevented=E;var a=this.originalEvent;!a||(a.preventDefault?a.preventDefault():a.returnValue=!1)},stopPropagation:function(){this.isPropagationStopped=E;var a=this.originalEvent;!a||(a.stopPropagation&&a.stopPropagation(),a.cancelBubble=!0)},stopImmediatePropagation:function(){this.isImmediatePropagationStopped=E,this.stopPropagation()},isDefaultPrevented:D,isPropagationStopped:D,isImmediatePropagationStopped:D};var F=function(a){var b=a.relatedTarget,c=!1,d=a.type;a.type=a.data,b!==this&&(b&&(c=f.contains(this,b)),c||(f.event.handle.apply(this,arguments),a.type=d))},G=function(a){a.type=a.data,f.event.handle.apply(this,arguments)};f.each({mouseenter:"mouseover",mouseleave:"mouseout"},function(a,b){f.event.special[a]={setup:function(c){f.event.add(this,b,c&&c.selector?G:F,a)},teardown:function(a){f.event.remove(this,b,a&&a.selector?G:F)}}}),f.support.submitBubbles||(f.event.special.submit={setup:function(a,b){if(!f.nodeName(this,"form"))f.event.add(this,"click.specialSubmit",function(a){var b=a.target,c=b.type;(c==="submit"||c==="image")&&f(b).closest("form").length&&K("submit",this,arguments)}),f.event.add(this,"keypress.specialSubmit",function(a){var b=a.target,c=b.type;(c==="text"||c==="password")&&f(b).closest("form").length&&a.keyCode===13&&K("submit",this,arguments)});else return!1},teardown:function(a){f.event.remove(this,".specialSubmit")}});if(!f.support.changeBubbles){var H,I=function(a){var b=a.type,c=a.value;b==="radio"||b==="checkbox"?c=a.checked:b==="select-multiple"?c=a.selectedIndex>-1?f.map(a.options,function(a){return a.selected}).join("-"):"":f.nodeName(a,"select")&&(c=a.selectedIndex);return c},J=function(c){var d=c.target,e,g;if(!!y.test(d.nodeName)&&!d.readOnly){e=f._data(d,"_change_data"),g=I(d),(c.type!=="focusout"||d.type!=="radio")&&f._data(d,"_change_data",g);if(e===b||g===e)return;if(e!=null||g)c.type="change",c.liveFired=b,f.event.trigger(c,arguments[1],d)}};f.event.special.change={filters:{focusout:J,beforedeactivate:J,click:function(a){var b=a.target,c=f.nodeName(b,"input")?b.type:"";(c==="radio"||c==="checkbox"||f.nodeName(b,"select"))&&J.call(this,a)},keydown:function(a){var b=a.target,c=f.nodeName(b,"input")?b.type:"";(a.keyCode===13&&!f.nodeName(b,"textarea")||a.keyCode===32&&(c==="checkbox"||c==="radio")||c==="select-multiple")&&J.call(this,a)},beforeactivate:function(a){var b=a.target;f._data(b,"_change_data",I(b))}},setup:function(a,b){if(this.type==="file")return!1;for(var c in H)f.event.add(this,c+".specialChange",H[c]);return y.test(this.nodeName)},teardown:function(a){f.event.remove(this,".specialChange");return y.test(this.nodeName)}},H=f.event.special.change.filters,H.focus=H.beforeactivate}f.support.focusinBubbles||f.each({focus:"focusin",blur:"focusout"},function(a,b){function e(a){var c=f.event.fix(a);c.type=b,c.originalEvent={},f.event.trigger(c,null,c.target),c.isDefaultPrevented()&&a.preventDefault()}var d=0;f.event.special[b]={setup:function(){d++===0&&c.addEventListener(a,e,!0)},teardown:function(){--d===0&&c.removeEventListener(a,e,!0)}}}),f.each(["bind","one"],function(a,c){f.fn[c]=function(a,d,e){var g;if(typeof a=="object"){for(var h in a)this[c](h,d,a[h],e);return this}if(arguments.length===2||d===!1)e=d,d=b;c==="one"?(g=function(a){f(this).unbind(a,g);return e.apply(this,arguments)},g.guid=e.guid||f.guid++):g=e;if(a==="unload"&&c!=="one")this.one(a,d,e);else for(var i=0,j=this.length;i<j;i++)f.event.add(this[i],a,g,d);return this}}),f.fn.extend({unbind:function(a,b){if(typeof a=="object"&&!a.preventDefault)for(var c in a)this.unbind(c,a[c]);else for(var d=0,e=this.length;d<e;d++)f.event.remove(this[d],a,b);return this},delegate:function(a,b,c,d){return this.live(b,c,d,a)},undelegate:function(a,b,c){return arguments.length===0?this.unbind("live"):this.die(b,null,c,a)},trigger:function(a,b){return this.each(function(){f.event.trigger(a,b,this)})},triggerHandler:function(a,b){if(this[0])return f.event.trigger(a,b,this[0],!0)},toggle:function(a){var b=arguments,c=a.guid||f.guid++,d=0,e=function(c){var e=(f.data(this,"lastToggle"+a.guid)||0)%d;f.data(this,"lastToggle"+a.guid,e+1),c.preventDefault();return b[e].apply(this,arguments)||!1};e.guid=c;while(d<b.length)b[d++].guid=c;return this.click(e)},hover:function(a,b){return this.mouseenter(a).mouseleave(b||a)}});var L={focus:"focusin",blur:"focusout",mouseenter:"mouseover",mouseleave:"mouseout"};f.each(["live","die"],function(a,c){f.fn[c]=function(a,d,e,g){var h,i=0,j,k,l,m=g||this.selector,n=g?this:f(this.context);if(typeof a=="object"&&!a.preventDefault){for(var o in a)n[c](o,d,a[o],m);return this}if(c==="die"&&!a&&g&&g.charAt(0)==="."){n.unbind(g);return this}if(d===!1||f.isFunction(d))e=d||D,d=b;a=(a||"").split(" ");while((h=a[i++])!=null){j=x.exec(h),k="",j&&(k=j[0],h=h.replace(x,""));if(h==="hover"){a.push("mouseenter"+k,"mouseleave"+k);continue}l=h,L[h]?(a.push(L[h]+k),h=h+k):h=(L[h]||h)+k;if(c==="live")for(var p=0,q=n.length;p<q;p++)f.event.add(n[p],"live."+N(h,m),{data:d,selector:m,handler:e,origType:h,origHandler:e,preType:l});else n.unbind("live."+N(h,m),e)}return this}}),f.each("blur focus focusin focusout load resize scroll unload click dblclick mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave change select submit keydown keypress keyup error".split(" "),function(a,b){f.fn[b]=function(a,c){c==null&&(c=a,a=null);return arguments.length>0?this.bind(b,a,c):this.trigger(b)},f.attrFn&&(f.attrFn[b]=!0)}),function(){function u(a,b,c,d,e,f){for(var g=0,h=d.length;g<h;g++){var i=d[g];if(i){var j=!1;i=i[a];while(i){if(i.sizcache===c){j=d[i.sizset];break}if(i.nodeType===1){f||(i.sizcache=c,i.sizset=g);if(typeof b!="string"){if(i===b){j=!0;break}}else if(k.filter(b,[i]).length>0){j=i;break}}i=i[a]}d[g]=j}}}function t(a,b,c,d,e,f){for(var g=0,h=d.length;g<h;g++){var i=d[g];if(i){var j=!1;i=i[a];while(i){if(i.sizcache===c){j=d[i.sizset];break}i.nodeType===1&&!f&&(i.sizcache=c,i.sizset=g);if(i.nodeName.toLowerCase()===b){j=i;break}i=i[a]}d[g]=j}}}var a=/((?:\((?:\([^()]+\)|[^()]+)+\)|\[(?:\[[^\[\]]*\]|['"][^'"]*['"]|[^\[\]'"]+)+\]|\\.|[^ >+~,(\[\\]+)+|[>+~])(\s*,\s*)?((?:.|\r|\n)*)/g,d=0,e=Object.prototype.toString,g=!1,h=!0,i=/\\/g,j=/\W/;[0,0].sort(function(){h=!1;return 0});var k=function(b,d,f,g){f=f||[],d=d||c;var h=d;if(d.nodeType!==1&&d.nodeType!==9)return[];if(!b||typeof b!="string")return f;var i,j,n,o,q,r,s,t,u=!0,w=k.isXML(d),x=[],y=b;do{a.exec(""),i=a.exec(y);if(i){y=i[3],x.push(i[1]);if(i[2]){o=i[3];break}}}while(i);if(x.length>1&&m.exec(b))if(x.length===2&&l.relative[x[0]])j=v(x[0]+x[1],d);else{j=l.relative[x[0]]?[d]:k(x.shift(),d);while(x.length)b=x.shift(),l.relative[b]&&(b+=x.shift()),j=v(b,j)}else{!g&&x.length>1&&d.nodeType===9&&!w&&l.match.ID.test(x[0])&&!l.match.ID.test(x[x.length-1])&&(q=k.find(x.shift(),d,w),d=q.expr?k.filter(q.expr,q.set)[0]:q.set[0]);if(d){q=g?{expr:x.pop(),set:p(g)}:k.find(x.pop(),x.length===1&&(x[0]==="~"||x[0]==="+")&&d.parentNode?d.parentNode:d,w),j=q.expr?k.filter(q.expr,q.set):q.set,x.length>0?n=p(j):u=!1;while(x.length)r=x.pop(),s=r,l.relative[r]?s=x.pop():r="",s==null&&(s=d),l.relative[r](n,s,w)}else n=x=[]}n||(n=j),n||k.error(r||b);if(e.call(n)==="[object Array]")if(!u)f.push.apply(f,n);else if(d&&d.nodeType===1)for(t=0;n[t]!=null;t++)n[t]&&(n[t]===!0||n[t].nodeType===1&&k.contains(d,n[t]))&&f.push(j[t]);else for(t=0;n[t]!=null;t++)n[t]&&n[t].nodeType===1&&f.push(j[t]);else p(n,f);o&&(k(o,h,f,g),k.uniqueSort(f));return f};k.uniqueSort=function(a){if(r){g=h,a.sort(r);if(g)for(var b=1;b<a.length;b++)a[b]===a[b-1]&&a.splice(b--,1)}return a},k.matches=function(a,b){return k(a,null,null,b)},k.matchesSelector=function(a,b){return k(b,null,null,[a]).length>0},k.find=function(a,b,c){var d;if(!a)return[];for(var e=0,f=l.order.length;e<f;e++){var g,h=l.order[e];if(g=l.leftMatch[h].exec(a)){var j=g[1];g.splice(1,1);if(j.substr(j.length-1)!=="\\"){g[1]=(g[1]||"").replace(i,""),d=l.find[h](g,b,c);if(d!=null){a=a.replace(l.match[h],"");break}}}}d||(d=typeof b.getElementsByTagName!="undefined"?b.getElementsByTagName("*"):[]);return{set:d,expr:a}},k.filter=function(a,c,d,e){var f,g,h=a,i=[],j=c,m=c&&c[0]&&k.isXML(c[0]);while(a&&c.length){for(var n in l.filter)if((f=l.leftMatch[n].exec(a))!=null&&f[2]){var o,p,q=l.filter[n],r=f[1];g=!1,f.splice(1,1);if(r.substr(r.length-1)==="\\")continue;j===i&&(i=[]);if(l.preFilter[n]){f=l.preFilter[n](f,j,d,i,e,m);if(!f)g=o=!0;else if(f===!0)continue}if(f)for(var s=0;(p=j[s])!=null;s++)if(p){o=q(p,f,s,j);var t=e^!!o;d&&o!=null?t?g=!0:j[s]=!1:t&&(i.push(p),g=!0)}if(o!==b){d||(j=i),a=a.replace(l.match[n],"");if(!g)return[];break}}if(a===h)if(g==null)k.error(a);else break;h=a}return j},k.error=function(a){throw"Syntax error, unrecognized expression: "+a};var l=k.selectors={order:["ID","NAME","TAG"],match:{ID:/#((?:[\w\u00c0-\uFFFF\-]|\\.)+)/,CLASS:/\.((?:[\w\u00c0-\uFFFF\-]|\\.)+)/,NAME:/\[name=['"]*((?:[\w\u00c0-\uFFFF\-]|\\.)+)['"]*\]/,ATTR:/\[\s*((?:[\w\u00c0-\uFFFF\-]|\\.)+)\s*(?:(\S?=)\s*(?:(['"])(.*?)\3|(#?(?:[\w\u00c0-\uFFFF\-]|\\.)*)|)|)\s*\]/,TAG:/^((?:[\w\u00c0-\uFFFF\*\-]|\\.)+)/,CHILD:/:(only|nth|last|first)-child(?:\(\s*(even|odd|(?:[+\-]?\d+|(?:[+\-]?\d*)?n\s*(?:[+\-]\s*\d+)?))\s*\))?/,POS:/:(nth|eq|gt|lt|first|last|even|odd)(?:\((\d*)\))?(?=[^\-]|$)/,PSEUDO:/:((?:[\w\u00c0-\uFFFF\-]|\\.)+)(?:\((['"]?)((?:\([^\)]+\)|[^\(\)]*)+)\2\))?/},leftMatch:{},attrMap:{"class":"className","for":"htmlFor"},attrHandle:{href:function(a){return a.getAttribute("href")},type:function(a){return a.getAttribute("type")}},relative:{"+":function(a,b){var c=typeof b=="string",d=c&&!j.test(b),e=c&&!d;d&&(b=b.toLowerCase());for(var f=0,g=a.length,h;f<g;f++)if(h=a[f]){while((h=h.previousSibling)&&h.nodeType!==1);a[f]=e||h&&h.nodeName.toLowerCase()===b?h||!1:h===b}e&&k.filter(b,a,!0)},">":function(a,b){var c,d=typeof b=="string",e=0,f=a.length;if(d&&!j.test(b)){b=b.toLowerCase();for(;e<f;e++){c=a[e];if(c){var g=c.parentNode;a[e]=g.nodeName.toLowerCase()===b?g:!1}}}else{for(;e<f;e++)c=a[e],c&&(a[e]=d?c.parentNode:c.parentNode===b);d&&k.filter(b,a,!0)}},"":function(a,b,c){var e,f=d++,g=u;typeof b=="string"&&!j.test(b)&&(b=b.toLowerCase(),e=b,g=t),g("parentNode",b,f,a,e,c)},"~":function(a,b,c){var e,f=d++,g=u;typeof b=="string"&&!j.test(b)&&(b=b.toLowerCase(),e=b,g=t),g("previousSibling",b,f,a,e,c)}},find:{ID:function(a,b,c){if(typeof b.getElementById!="undefined"&&!c){var d=b.getElementById(a[1]);return d&&d.parentNode?[d]:[]}},NAME:function(a,b){if(typeof b.getElementsByName!="undefined"){var c=[],d=b.getElementsByName(a[1]);for(var e=0,f=d.length;e<f;e++)d[e].getAttribute("name")===a[1]&&c.push(d[e]);return c.length===0?null:c}},TAG:function(a,b){if(typeof b.getElementsByTagName!="undefined")return b.getElementsByTagName(a[1])}},preFilter:{CLASS:function(a,b,c,d,e,f){a=" "+a[1].replace(i,"")+" ";if(f)return a;for(var g=0,h;(h=b[g])!=null;g++)h&&(e^(h.className&&(" "+h.className+" ").replace(/[\t\n\r]/g," ").indexOf(a)>=0)?c||d.push(h):c&&(b[g]=!1));return!1},ID:function(a){return a[1].replace(i,"")},TAG:function(a,b){return a[1].replace(i,"").toLowerCase()},CHILD:function(a){if(a[1]==="nth"){a[2]||k.error(a[0]),a[2]=a[2].replace(/^\+|\s*/g,"");var b=/(-?)(\d*)(?:n([+\-]?\d*))?/.exec(a[2]==="even"&&"2n"||a[2]==="odd"&&"2n+1"||!/\D/.test(a[2])&&"0n+"+a[2]||a[2]);a[2]=b[1]+(b[2]||1)-0,a[3]=b[3]-0}else a[2]&&k.error(a[0]);a[0]=d++;return a},ATTR:function(a,b,c,d,e,f){var g=a[1]=a[1].replace(i,"");!f&&l.attrMap[g]&&(a[1]=l.attrMap[g]),a[4]=(a[4]||a[5]||"").replace(i,""),a[2]==="~="&&(a[4]=" "+a[4]+" ");return a},PSEUDO:function(b,c,d,e,f){if(b[1]==="not")if((a.exec(b[3])||"").length>1||/^\w/.test(b[3]))b[3]=k(b[3],null,null,c);else{var g=k.filter(b[3],c,d,!0^f);d||e.push.apply(e,g);return!1}else if(l.match.POS.test(b[0])||l.match.CHILD.test(b[0]))return!0;return b},POS:function(a){a.unshift(!0);return a}},filters:{enabled:function(a){return a.disabled===!1&&a.type!=="hidden"},disabled:function(a){return a.disabled===!0},checked:function(a){return a.checked===!0},selected:function(a){a.parentNode&&a.parentNode.selectedIndex;return a.selected===!0},parent:function(a){return!!a.firstChild},empty:function(a){return!a.firstChild},has:function(a,b,c){return!!k(c[3],a).length},header:function(a){return/h\d/i.test(a.nodeName)},text:function(a){var b=a.getAttribute("type"),c=a.type;return a.nodeName.toLowerCase()==="input"&&"text"===c&&(b===c||b===null)},radio:function(a){return a.nodeName.toLowerCase()==="input"&&"radio"===a.type},checkbox:function(a){return a.nodeName.toLowerCase()==="input"&&"checkbox"===a.type},file:function(a){return a.nodeName.toLowerCase()==="input"&&"file"===a.type},password:function(a){return a.nodeName.toLowerCase()==="input"&&"password"===a.type},submit:function(a){var b=a.nodeName.toLowerCase();return(b==="input"||b==="button")&&"submit"===a.type},image:function(a){return a.nodeName.toLowerCase()==="input"&&"image"===a.type},reset:function(a){var b=a.nodeName.toLowerCase();return(b==="input"||b==="button")&&"reset"===a.type},button:function(a){var b=a.nodeName.toLowerCase();return b==="input"&&"button"===a.type||b==="button"},input:function(a){return/input|select|textarea|button/i.test(a.nodeName)},focus:function(a){return a===a.ownerDocument.activeElement}},setFilters:{first:function(a,b){return b===0},last:function(a,b,c,d){return b===d.length-1},even:function(a,b){return b%2===0},odd:function(a,b){return b%2===1},lt:function(a,b,c){return b<c[3]-0},gt:function(a,b,c){return b>c[3]-0},nth:function(a,b,c){return c[3]-0===b},eq:function(a,b,c){return c[3]-0===b}},filter:{PSEUDO:function(a,b,c,d){var e=b[1],f=l.filters[e];if(f)return f(a,c,b,d);if(e==="contains")return(a.textContent||a.innerText||k.getText([a])||"").indexOf(b[3])>=0;if(e==="not"){var g=b[3];for(var h=0,i=g.length;h<i;h++)if(g[h]===a)return!1;return!0}k.error(e)},CHILD:function(a,b){var c=b[1],d=a;switch(c){case"only":case"first":while(d=d.previousSibling)if(d.nodeType===1)return!1;if(c==="first")return!0;d=a;case"last":while(d=d.nextSibling)if(d.nodeType===1)return!1;return!0;case"nth":var e=b[2],f=b[3];if(e===1&&f===0)return!0;var g=b[0],h=a.parentNode;if(h&&(h.sizcache!==g||!a.nodeIndex)){var i=0;for(d=h.firstChild;d;d=d.nextSibling)d.nodeType===1&&(d.nodeIndex=++i);h.sizcache=g}var j=a.nodeIndex-f;return e===0?j===0:j%e===0&&j/e>=0}},ID:function(a,b){return a.nodeType===1&&a.getAttribute("id")===b},TAG:function(a,b){return b==="*"&&a.nodeType===1||a.nodeName.toLowerCase()===b},CLASS:function(a,b){return(" "+(a.className||a.getAttribute("class"))+" ").indexOf(b)>-1},ATTR:function(a,b){var c=b[1],d=l.attrHandle[c]?l.attrHandle[c](a):a[c]!=null?a[c]:a.getAttribute(c),e=d+"",f=b[2],g=b[4];return d==null?f==="!=":f==="="?e===g:f==="*="?e.indexOf(g)>=0:f==="~="?(" "+e+" ").indexOf(g)>=0:g?f==="!="?e!==g:f==="^="?e.indexOf(g)===0:f==="$="?e.substr(e.length-g.length)===g:f==="|="?e===g||e.substr(0,g.length+1)===g+"-":!1:e&&d!==!1},POS:function(a,b,c,d){var e=b[2],f=l.setFilters[e];if(f)return f(a,c,b,d)}}},m=l.match.POS,n=function(a,b){return"\\"+(b-0+1)};for(var o in l.match)l.match[o]=new RegExp(l.match[o].source+/(?![^\[]*\])(?![^\(]*\))/.source),l.leftMatch[o]=new RegExp(/(^(?:.|\r|\n)*?)/.source+l.match[o].source.replace(/\\(\d+)/g,n));var p=function(a,b){a=Array.prototype.slice.call(a,0);if(b){b.push.apply(b,a);return b}return a};try{Array.prototype.slice.call(c.documentElement.childNodes,0)[0].nodeType}catch(q){p=function(a,b){var c=0,d=b||[];if(e.call(a)==="[object Array]")Array.prototype.push.apply(d,a);else if(typeof a.length=="number")for(var f=a.length;c<f;c++)d.push(a[c]);else for(;a[c];c++)d.push(a[c]);return d}}var r,s;c.documentElement.compareDocumentPosition?r=function(a,b){if(a===b){g=!0;return 0}if(!a.compareDocumentPosition||!b.compareDocumentPosition)return a.compareDocumentPosition?-1:1;return a.compareDocumentPosition(b)&4?-1:1}:(r=function(a,b){if(a===b){g=!0;return 0}if(a.sourceIndex&&b.sourceIndex)return a.sourceIndex-b.sourceIndex;var c,d,e=[],f=[],h=a.parentNode,i=b.parentNode,j=h;if(h===i)return s(a,b);if(!h)return-1;if(!i)return 1;while(j)e.unshift(j),j=j.parentNode;j=i;while(j)f.unshift(j),j=j.parentNode;c=e.length,d=f.length;for(var k=0;k<c&&k<d;k++)if(e[k]!==f[k])return s(e[k],f[k]);return k===c?s(a,f[k],-1):s(e[k],b,1)},s=function(a,b,c){if(a===b)return c;var d=a.nextSibling;while(d){if(d===b)return-1;d=d.nextSibling}return 1}),k.getText=function(a){var b="",c;for(var d=0;a[d];d++)c=a[d],c.nodeType===3||c.nodeType===4?b+=c.nodeValue:c.nodeType!==8&&(b+=k.getText(c.childNodes));return b},function(){var a=c.createElement("div"),d="script"+(new Date).getTime(),e=c.documentElement;a.innerHTML="<a name='"+d+"'/>",e.insertBefore(a,e.firstChild),c.getElementById(d)&&(l.find.ID=function(a,c,d){if(typeof c.getElementById!="undefined"&&!d){var e=c.getElementById(a[1]);return e?e.id===a[1]||typeof e.getAttributeNode!="undefined"&&e.getAttributeNode("id").nodeValue===a[1]?[e]:b:[]}},l.filter.ID=function(a,b){var c=typeof a.getAttributeNode!="undefined"&&a.getAttributeNode("id");return a.nodeType===1&&c&&c.nodeValue===b}),e.removeChild(a),e=a=null}(),function(){var a=c.createElement("div");a.appendChild(c.createComment("")),a.getElementsByTagName("*").length>0&&(l.find.TAG=function(a,b){var c=b.getElementsByTagName(a[1]);if(a[1]==="*"){var d=[];for(var e=0;c[e];e++)c[e].nodeType===1&&d.push(c[e]);c=d}return c}),a.innerHTML="<a href='#'></a>",a.firstChild&&typeof a.firstChild.getAttribute!="undefined"&&a.firstChild.getAttribute("href")!=="#"&&(l.attrHandle.href=function(a){return a.getAttribute("href",2)}),a=null}(),c.querySelectorAll&&function(){var a=k,b=c.createElement("div"),d="__sizzle__";b.innerHTML="<p class='TEST'></p>";if(!b.querySelectorAll||b.querySelectorAll(".TEST").length!==0){k=function(b,e,f,g){e=e||c;if(!g&&!k.isXML(e)){var h=/^(\w+$)|^\.([\w\-]+$)|^#([\w\-]+$)/.exec(b);if(h&&(e.nodeType===1||e.nodeType===9)){if(h[1])return p(e.getElementsByTagName(b),f);if(h[2]&&l.find.CLASS&&e.getElementsByClassName)return p(e.getElementsByClassName(h[2]),f)}if(e.nodeType===9){if(b==="body"&&e.body)return p([e.body],f);if(h&&h[3]){var i=e.getElementById(h[3]);if(!i||!i.parentNode)return p([],f);if(i.id===h[3])return p([i],f)}try{return p(e.querySelectorAll(b),f)}catch(j){}}else if(e.nodeType===1&&e.nodeName.toLowerCase()!=="object"){var m=e,n=e.getAttribute("id"),o=n||d,q=e.parentNode,r=/^\s*[+~]/.test(b);n?o=o.replace(/'/g,"\\$&"):e.setAttribute("id",o),r&&q&&(e=e.parentNode);try{if(!r||q)return p(e.querySelectorAll("[id='"+o+"'] "+b),f)}catch(s){}finally{n||m.removeAttribute("id")}}}return a(b,e,f,g)};for(var e in a)k[e]=a[e];b=null}}(),function(){var a=c.documentElement,b=a.matchesSelector||a.mozMatchesSelector||a.webkitMatchesSelector||a.msMatchesSelector;if(b){var d=!b.call(c.createElement("div"),"div"),e=!1;try{b.call(c.documentElement,"[test!='']:sizzle")}catch(f){e=!0}k.matchesSelector=function(a,c){c=c.replace(/\=\s*([^'"\]]*)\s*\]/g,"='$1']");if(!k.isXML(a))try{if(e||!l.match.PSEUDO.test(c)&&!/!=/.test(c)){var f=b.call(a,c);if(f||!d||a.document&&a.document.nodeType!==11)return f}}catch(g){}return k(c,null,null,[a]).length>0}}}(),function(){var a=c.createElement("div");a.innerHTML="<div class='test e'></div><div class='test'></div>";if(!!a.getElementsByClassName&&a.getElementsByClassName("e").length!==0){a.lastChild.className="e";if(a.getElementsByClassName("e").length===1)return;l.order.splice(1,0,"CLASS"),l.find.CLASS=function(a,b,c){if(typeof b.getElementsByClassName!="undefined"&&!c)return b.getElementsByClassName(a[1])},a=null}}(),c.documentElement.contains?k.contains=function(a,b){return a!==b&&(a.contains?a.contains(b):!0)}:c.documentElement.compareDocumentPosition?k.contains=function(a,b){return!!(a.compareDocumentPosition(b)&16)}:k.contains=function(){return!1},k.isXML=function(a){var b=(a?a.ownerDocument||a:0).documentElement;return b?b.nodeName!=="HTML":!1};var v=function(a,b){var c,d=[],e="",f=b.nodeType?[b]:b;while(c=l.match.PSEUDO.exec(a))e+=c[0],a=a.replace(l.match.PSEUDO,"");a=l.relative[a]?a+"*":a;for(var g=0,h=f.length;g<h;g++)k(a,f[g],d);return k.filter(e,d)};f.find=k,f.expr=k.selectors,f.expr[":"]=f.expr.filters,f.unique=k.uniqueSort,f.text=k.getText,f.isXMLDoc=k.isXML,f.contains=k.contains}();var O=/Until$/,P=/^(?:parents|prevUntil|prevAll)/,Q=/,/,R=/^.[^:#\[\.,]*$/,S=Array.prototype.slice,T=f.expr.match.POS,U={children:!0,contents:!0,next:!0,prev:!0};f.fn.extend({find:function(a){var b=this,c,d;if(typeof a!="string")return f(a).filter(function(){for(c=0,d=b.length;c<d;c++)if(f.contains(b[c],this))return!0});var e=this.pushStack("","find",a),g,h,i;for(c=0,d=this.length;c<d;c++){g=e.length,f.find(a,this[c],e);if(c>0)for(h=g;h<e.length;h++)for(i=0;i<g;i++)if(e[i]===e[h]){e.splice(h--,1);break}}return e},has:function(a){var b=f(a);return this.filter(function(){for(var a=0,c=b.length;a<c;a++)if(f.contains(this,b[a]))return!0})},not:function(a){return this.pushStack(W(this,a,!1),"not",a)},filter:function(a){return this.pushStack(W(this,a,!0),"filter",a)},is:function(a){return!!a&&(typeof a=="string"?f.filter(a,this).length>0:this.filter(a).length>0)},closest:function(a,b){var c=[],d,e,g=this[0];if(f.isArray(a)){var h,i,j={},k=1;if(g&&a.length){for(d=0,e=a.length;d<e;d++)i=a[d],j[i]||(j[i]=T.test(i)?f(i,b||this.context):i);while(g&&g.ownerDocument&&g!==b){for(i in j)h=j[i],(h.jquery?h.index(g)>-1:f(g).is(h))&&c.push({selector:i,elem:g,level:k});g=g.parentNode,k++}}return c}var l=T.test(a)||typeof a!="string"?f(a,b||this.context):0;for(d=0,e=this.length;d<e;d++){g=this[d];while(g){if(l?l.index(g)>-1:f.find.matchesSelector(g,a)){c.push(g);break}g=g.parentNode;if(!g||!g.ownerDocument||g===b||g.nodeType===11)break}}c=c.length>1?f.unique(c):c;return this.pushStack(c,"closest",a)},index:function(a){if(!a||typeof a=="string")return f.inArray(this[0],a?f(a):this.parent().children());return f.inArray(a.jquery?a[0]:a,this)},add:function(a,b){var c=typeof a=="string"?f(a,b):f.makeArray(a&&a.nodeType?[a]:a),d=f.merge(this.get(),c);return this.pushStack(V(c[0])||V(d[0])?d:f.unique(d))},andSelf:function(){return this.add(this.prevObject)}}),f.each({parent:function(a){var b=a.parentNode;return b&&b.nodeType!==11?b:null},parents:function(a){return f.dir(a,"parentNode")},parentsUntil:function(a,b,c){return f.dir(a,"parentNode",c)},next:function(a){return f.nth(a,2,"nextSibling")},prev:function(a){return f.nth(a,2,"previousSibling")},nextAll:function(a){return f.dir(a,"nextSibling")},prevAll:function(a){return f.dir(a,"previousSibling")},nextUntil:function(a,b,c){return f.dir(a,"nextSibling",c)},prevUntil:function(a,b,c){return f.dir(a,"previousSibling",c)},siblings:function(a){return f.sibling(a.parentNode.firstChild,a)},children:function(a){return f.sibling(a.firstChild)},contents:function(a){return f.nodeName(a,"iframe")?a.contentDocument||a.contentWindow.document:f.makeArray(a.childNodes)}},function(a,b){f.fn[a]=function(c,d){var e=f.map(this,b,c),g=S.call(arguments);O.test(a)||(d=c),d&&typeof d=="string"&&(e=f.filter(d,e)),e=this.length>1&&!U[a]?f.unique(e):e,(this.length>1||Q.test(d))&&P.test(a)&&(e=e.reverse());return this.pushStack(e,a,g.join(","))}}),f.extend({filter:function(a,b,c){c&&(a=":not("+a+")");return b.length===1?f.find.matchesSelector(b[0],a)?[b[0]]:[]:f.find.matches(a,b)},dir:function(a,c,d){var e=[],g=a[c];while(g&&g.nodeType!==9&&(d===b||g.nodeType!==1||!f(g).is(d)))g.nodeType===1&&e.push(g),g=g[c];return e},nth:function(a,b,c,d){b=b||1;var e=0;for(;a;a=a[c])if(a.nodeType===1&&++e===b)break;return a},sibling:function(a,b){var c=[];for(;a;a=a.nextSibling)a.nodeType===1&&a!==b&&c.push(a);return c}});var X=/ jQuery\d+="(?:\d+|null)"/g,Y=/^\s+/,Z=/<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/ig,$=/<([\w:]+)/,_=/<tbody/i,ba=/<|&#?\w+;/,bb=/<(?:script|object|embed|option|style)/i,bc=/checked\s*(?:[^=]|=\s*.checked.)/i,bd=/\/(java|ecma)script/i,be=/^\s*<!(?:\[CDATA\[|\-\-)/,bf={option:[1,"<select multiple='multiple'>","</select>"],legend:[1,"<fieldset>","</fieldset>"],thead:[1,"<table>","</table>"],tr:[2,"<table><tbody>","</tbody></table>"],td:[3,"<table><tbody><tr>","</tr></tbody></table>"],col:[2,"<table><tbody></tbody><colgroup>","</colgroup></table>"],area:[1,"<map>","</map>"],_default:[0,"",""]};bf.optgroup=bf.option,bf.tbody=bf.tfoot=bf.colgroup=bf.caption=bf.thead,bf.th=bf.td,f.support.htmlSerialize||(bf._default=[1,"div<div>","</div>"]),f.fn.extend({text:function(a){if(f.isFunction(a))return this.each(function(b){var c=f(this);c.text(a.call(this,b,c.text()))});if(typeof a!="object"&&a!==b)return this.empty().append((this[0]&&this[0].ownerDocument||c).createTextNode(a));return f.text(this)},wrapAll:function(a){if(f.isFunction(a))return this.each(function(b){f(this).wrapAll(a.call(this,b))});if(this[0]){var b=f(a,this[0].ownerDocument).eq(0).clone(!0);this[0].parentNode&&b.insertBefore(this[0]),b.map(function(){var a=this;while(a.firstChild&&a.firstChild.nodeType===1)a=a.firstChild;return a}).append(this)}return this},wrapInner:function(a){if(f.isFunction(a))return this.each(function(b){f(this).wrapInner(a.call(this,b))});return this.each(function(){var b=f(this),c=b.contents();c.length?c.wrapAll(a):b.append(a)})},wrap:function(a){return this.each(function(){f(this).wrapAll(a)})},unwrap:function(){return this.parent().each(function(){f.nodeName(this,"body")||f(this).replaceWith(this.childNodes)}).end()},append:function(){return this.domManip(arguments,!0,function(a){this.nodeType===1&&this.appendChild(a)})},prepend:function(){return this.domManip(arguments,!0,function(a){this.nodeType===1&&this.insertBefore(a,this.firstChild)})},before:function(){if(this[0]&&this[0].parentNode)return this.domManip(arguments,!1,function(a){this.parentNode.insertBefore(a,this)});if(arguments.length){var a=f(arguments[0]);a.push.apply(a,this.toArray());return this.pushStack(a,"before",arguments)}},after:function(){if(this[0]&&this[0].parentNode)return this.domManip(arguments,!1,function(a){this.parentNode.insertBefore(a,this.nextSibling)});if(arguments.length){var a=this.pushStack(this,"after",arguments);a.push.apply(a,f(arguments[0]).toArray());return a}},remove:function(a,b){for(var c=0,d;(d=this[c])!=null;c++)if(!a||f.filter(a,[d]).length)!b&&d.nodeType===1&&(f.cleanData(d.getElementsByTagName("*")),f.cleanData([d])),d.parentNode&&d.parentNode.removeChild(d);return this},empty:function(){for(var a=0,b;(b=this[a])!=null;a++){b.nodeType===1&&f.cleanData(b.getElementsByTagName("*"));while(b.firstChild)b.removeChild(b.firstChild)}return this},clone:function(a,b){a=a==null?!1:a,b=b==null?a:b;return this.map(function(){return f.clone(this,a,b)})},html:function(a){if(a===b)return this[0]&&this[0].nodeType===1?this[0].innerHTML.replace(X,""):null;if(typeof a=="string"&&!bb.test(a)&&(f.support.leadingWhitespace||!Y.test(a))&&!bf[($.exec(a)||["",""])[1].toLowerCase()]){a=a.replace(Z,"<$1></$2>");try{for(var c=0,d=this.length;c<d;c++)this[c].nodeType===1&&(f.cleanData(this[c].getElementsByTagName("*")),this[c].innerHTML=a)}catch(e){this.empty().append(a)}}else f.isFunction(a)?this.each(function(b){var c=f(this);c.html(a.call(this,b,c.html()))}):this.empty().append(a);return this},replaceWith:function(a){if(this[0]&&this[0].parentNode){if(f.isFunction(a))return this.each(function(b){var c=f(this),d=c.html();c.replaceWith(a.call(this,b,d))});typeof a!="string"&&(a=f(a).detach());return this.each(function(){var b=this.nextSibling,c=this.parentNode;f(this).remove(),b?f(b).before(a):f(c).append(a)})}return this.length?this.pushStack(f(f.isFunction(a)?a():a),"replaceWith",a):this},detach:function(a){return this.remove(a,!0)},domManip:function(a,c,d){var e,g,h,i,j=a[0],k=[];if(!f.support.checkClone&&arguments.length===3&&typeof j=="string"&&bc.test(j))return this.each(function(){f(this).domManip(a,c,d,!0)});if(f.isFunction(j))return this.each(function(e){var g=f(this);a[0]=j.call(this,e,c?g.html():b),g.domManip(a,c,d)});if(this[0]){i=j&&j.parentNode,f.support.parentNode&&i&&i.nodeType===11&&i.childNodes.length===this.length?e={fragment:i}:e=f.buildFragment(a,this,k),h=e.fragment,h.childNodes.length===1?g=h=h.firstChild:g=h.firstChild;if(g){c=c&&f.nodeName(g,"tr");for(var l=0,m=this.length,n=m-1;l<m;l++)d.call(c?bg(this[l],g):this[l],e.cacheable||m>1&&l<n?f.clone(h,!0,!0):h)}k.length&&f.each(k,bm)}return this}}),f.buildFragment=function(a,b,d){var e,g,h,i;b&&b[0]&&(i=b[0].ownerDocument||b[0]),i.createDocumentFragment||(i=c),a.length===1&&typeof a[0]=="string"&&a[0].length<512&&i===c&&a[0].charAt(0)==="<"&&!bb.test(a[0])&&(f.support.checkClone||!bc.test(a[0]))&&(g=!0,h=f.fragments[a[0]],h&&h!==1&&(e=h)),e||(e=i.createDocumentFragment(),f.clean(a,i,e,d)),g&&(f.fragments[a[0]]=h?e:1);return{fragment:e,cacheable:g}},f.fragments={},f.each({appendTo:"append",prependTo:"prepend",insertBefore:"before",insertAfter:"after",replaceAll:"replaceWith"},function(a,b){f.fn[a]=function(c){var d=[],e=f(c),g=this.length===1&&this[0].parentNode;if(g&&g.nodeType===11&&g.childNodes.length===1&&e.length===1){e[b](this[0]);return this}for(var h=0,i=e.length;h<i;h++){var j=(h>0?this.clone(!0):this).get();f(e[h])[b](j),d=d.concat(j )}return this.pushStack(d,a,e.selector)}}),f.extend({clone:function(a,b,c){var d=a.cloneNode(!0),e,g,h;if((!f.support.noCloneEvent||!f.support.noCloneChecked)&&(a.nodeType===1||a.nodeType===11)&&!f.isXMLDoc(a)){bi(a,d),e=bj(a),g=bj(d);for(h=0;e[h];++h)bi(e[h],g[h])}if(b){bh(a,d);if(c){e=bj(a),g=bj(d);for(h=0;e[h];++h)bh(e[h],g[h])}}e=g=null;return d},clean:function(a,b,d,e){var g;b=b||c,typeof b.createElement=="undefined"&&(b=b.ownerDocument||b[0]&&b[0].ownerDocument||c);var h=[],i;for(var j=0,k;(k=a[j])!=null;j++){typeof k=="number"&&(k+="");if(!k)continue;if(typeof k=="string")if(!ba.test(k))k=b.createTextNode(k);else{k=k.replace(Z,"<$1></$2>");var l=($.exec(k)||["",""])[1].toLowerCase(),m=bf[l]||bf._default,n=m[0],o=b.createElement("div");o.innerHTML=m[1]+k+m[2];while(n--)o=o.lastChild;if(!f.support.tbody){var p=_.test(k),q=l==="table"&&!p?o.firstChild&&o.firstChild.childNodes:m[1]==="<table>"&&!p?o.childNodes:[];for(i=q.length-1;i>=0;--i)f.nodeName(q[i],"tbody")&&!q[i].childNodes.length&&q[i].parentNode.removeChild(q[i])}!f.support.leadingWhitespace&&Y.test(k)&&o.insertBefore(b.createTextNode(Y.exec(k)[0]),o.firstChild),k=o.childNodes}var r;if(!f.support.appendChecked)if(k[0]&&typeof (r=k.length)=="number")for(i=0;i<r;i++)bl(k[i]);else bl(k);k.nodeType?h.push(k):h=f.merge(h,k)}if(d){g=function(a){return!a.type||bd.test(a.type)};for(j=0;h[j];j++)if(e&&f.nodeName(h[j],"script")&&(!h[j].type||h[j].type.toLowerCase()==="text/javascript"))e.push(h[j].parentNode?h[j].parentNode.removeChild(h[j]):h[j]);else{if(h[j].nodeType===1){var s=f.grep(h[j].getElementsByTagName("script"),g);h.splice.apply(h,[j+1,0].concat(s))}d.appendChild(h[j])}}return h},cleanData:function(a){var b,c,d=f.cache,e=f.expando,g=f.event.special,h=f.support.deleteExpando;for(var i=0,j;(j=a[i])!=null;i++){if(j.nodeName&&f.noData[j.nodeName.toLowerCase()])continue;c=j[f.expando];if(c){b=d[c]&&d[c][e];if(b&&b.events){for(var k in b.events)g[k]?f.event.remove(j,k):f.removeEvent(j,k,b.handle);b.handle&&(b.handle.elem=null)}h?delete j[f.expando]:j.removeAttribute&&j.removeAttribute(f.expando),delete d[c]}}}});var bn=/alpha\([^)]*\)/i,bo=/opacity=([^)]*)/,bp=/([A-Z]|^ms)/g,bq=/^-?\d+(?:px)?$/i,br=/^-?\d/,bs=/^[+\-]=/,bt=/[^+\-\.\de]+/g,bu={position:"absolute",visibility:"hidden",display:"block"},bv=["Left","Right"],bw=["Top","Bottom"],bx,by,bz;f.fn.css=function(a,c){if(arguments.length===2&&c===b)return this;return f.access(this,a,c,!0,function(a,c,d){return d!==b?f.style(a,c,d):f.css(a,c)})},f.extend({cssHooks:{opacity:{get:function(a,b){if(b){var c=bx(a,"opacity","opacity");return c===""?"1":c}return a.style.opacity}}},cssNumber:{fillOpacity:!0,fontWeight:!0,lineHeight:!0,opacity:!0,orphans:!0,widows:!0,zIndex:!0,zoom:!0},cssProps:{"float":f.support.cssFloat?"cssFloat":"styleFloat"},style:function(a,c,d,e){if(!!a&&a.nodeType!==3&&a.nodeType!==8&&!!a.style){var g,h,i=f.camelCase(c),j=a.style,k=f.cssHooks[i];c=f.cssProps[i]||i;if(d===b){if(k&&"get"in k&&(g=k.get(a,!1,e))!==b)return g;return j[c]}h=typeof d;if(h==="number"&&isNaN(d)||d==null)return;h==="string"&&bs.test(d)&&(d=+d.replace(bt,"")+parseFloat(f.css(a,c)),h="number"),h==="number"&&!f.cssNumber[i]&&(d+="px");if(!k||!("set"in k)||(d=k.set(a,d))!==b)try{j[c]=d}catch(l){}}},css:function(a,c,d){var e,g;c=f.camelCase(c),g=f.cssHooks[c],c=f.cssProps[c]||c,c==="cssFloat"&&(c="float");if(g&&"get"in g&&(e=g.get(a,!0,d))!==b)return e;if(bx)return bx(a,c)},swap:function(a,b,c){var d={};for(var e in b)d[e]=a.style[e],a.style[e]=b[e];c.call(a);for(e in b)a.style[e]=d[e]}}),f.curCSS=f.css,f.each(["height","width"],function(a,b){f.cssHooks[b]={get:function(a,c,d){var e;if(c){if(a.offsetWidth!==0)return bA(a,b,d);f.swap(a,bu,function(){e=bA(a,b,d)});return e}},set:function(a,b){if(!bq.test(b))return b;b=parseFloat(b);if(b>=0)return b+"px"}}}),f.support.opacity||(f.cssHooks.opacity={get:function(a,b){return bo.test((b&&a.currentStyle?a.currentStyle.filter:a.style.filter)||"")?parseFloat(RegExp.$1)/100+"":b?"1":""},set:function(a,b){var c=a.style,d=a.currentStyle;c.zoom=1;var e=f.isNaN(b)?"":"alpha(opacity="+b*100+")",g=d&&d.filter||c.filter||"";c.filter=bn.test(g)?g.replace(bn,e):g+" "+e}}),f(function(){f.support.reliableMarginRight||(f.cssHooks.marginRight={get:function(a,b){var c;f.swap(a,{display:"inline-block"},function(){b?c=bx(a,"margin-right","marginRight"):c=a.style.marginRight});return c}})}),c.defaultView&&c.defaultView.getComputedStyle&&(by=function(a,c){var d,e,g;c=c.replace(bp,"-$1").toLowerCase();if(!(e=a.ownerDocument.defaultView))return b;if(g=e.getComputedStyle(a,null))d=g.getPropertyValue(c),d===""&&!f.contains(a.ownerDocument.documentElement,a)&&(d=f.style(a,c));return d}),c.documentElement.currentStyle&&(bz=function(a,b){var c,d=a.currentStyle&&a.currentStyle[b],e=a.runtimeStyle&&a.runtimeStyle[b],f=a.style;!bq.test(d)&&br.test(d)&&(c=f.left,e&&(a.runtimeStyle.left=a.currentStyle.left),f.left=b==="fontSize"?"1em":d||0,d=f.pixelLeft+"px",f.left=c,e&&(a.runtimeStyle.left=e));return d===""?"auto":d}),bx=by||bz,f.expr&&f.expr.filters&&(f.expr.filters.hidden=function(a){var b=a.offsetWidth,c=a.offsetHeight;return b===0&&c===0||!f.support.reliableHiddenOffsets&&(a.style.display||f.css(a,"display"))==="none"},f.expr.filters.visible=function(a){return!f.expr.filters.hidden(a)});var bB=/%20/g,bC=/\[\]$/,bD=/\r?\n/g,bE=/#.*$/,bF=/^(.*?):[ \t]*([^\r\n]*)\r?$/mg,bG=/^(?:color|date|datetime|email|hidden|month|number|password|range|search|tel|text|time|url|week)$/i,bH=/^(?:about|app|app\-storage|.+\-extension|file|widget):$/,bI=/^(?:GET|HEAD)$/,bJ=/^\/\//,bK=/\?/,bL=/<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi,bM=/^(?:select|textarea)/i,bN=/\s+/,bO=/([?&])_=[^&]*/,bP=/^([\w\+\.\-]+:)(?:\/\/([^\/?#:]*)(?::(\d+))?)?/,bQ=f.fn.load,bR={},bS={},bT,bU;try{bT=e.href}catch(bV){bT=c.createElement("a"),bT.href="",bT=bT.href}bU=bP.exec(bT.toLowerCase())||[],f.fn.extend({load:function(a,c,d){if(typeof a!="string"&&bQ)return bQ.apply(this,arguments);if(!this.length)return this;var e=a.indexOf(" ");if(e>=0){var g=a.slice(e,a.length);a=a.slice(0,e)}var h="GET";c&&(f.isFunction(c)?(d=c,c=b):typeof c=="object"&&(c=f.param(c,f.ajaxSettings.traditional),h="POST"));var i=this;f.ajax({url:a,type:h,dataType:"html",data:c,complete:function(a,b,c){c=a.responseText,a.isResolved()&&(a.done(function(a){c=a}),i.html(g?f("<div>").append(c.replace(bL,"")).find(g):c)),d&&i.each(d,[c,b,a])}});return this},serialize:function(){return f.param(this.serializeArray())},serializeArray:function(){return this.map(function(){return this.elements?f.makeArray(this.elements):this}).filter(function(){return this.name&&!this.disabled&&(this.checked||bM.test(this.nodeName)||bG.test(this.type))}).map(function(a,b){var c=f(this).val();return c==null?null:f.isArray(c)?f.map(c,function(a,c){return{name:b.name,value:a.replace(bD,"\r\n")}}):{name:b.name,value:c.replace(bD,"\r\n")}}).get()}}),f.each("ajaxStart ajaxStop ajaxComplete ajaxError ajaxSuccess ajaxSend".split(" "),function(a,b){f.fn[b]=function(a){return this.bind(b,a)}}),f.each(["get","post"],function(a,c){f[c]=function(a,d,e,g){f.isFunction(d)&&(g=g||e,e=d,d=b);return f.ajax({type:c,url:a,data:d,success:e,dataType:g})}}),f.extend({getScript:function(a,c){return f.get(a,b,c,"script")},getJSON:function(a,b,c){return f.get(a,b,c,"json")},ajaxSetup:function(a,b){b?f.extend(!0,a,f.ajaxSettings,b):(b=a,a=f.extend(!0,f.ajaxSettings,b));for(var c in{context:1,url:1})c in b?a[c]=b[c]:c in f.ajaxSettings&&(a[c]=f.ajaxSettings[c]);return a},ajaxSettings:{url:bT,isLocal:bH.test(bU[1]),global:!0,type:"GET",contentType:"application/x-www-form-urlencoded",processData:!0,async:!0,accepts:{xml:"application/xml, text/xml",html:"text/html",text:"text/plain",json:"application/json, text/javascript","*":"*/*"},contents:{xml:/xml/,html:/html/,json:/json/},responseFields:{xml:"responseXML",text:"responseText"},converters:{"* text":a.String,"text html":!0,"text json":f.parseJSON,"text xml":f.parseXML}},ajaxPrefilter:bW(bR),ajaxTransport:bW(bS),ajax:function(a,c){function w(a,c,l,m){if(s!==2){s=2,q&&clearTimeout(q),p=b,n=m||"",v.readyState=a?4:0;var o,r,u,w=l?bZ(d,v,l):b,x,y;if(a>=200&&a<300||a===304){if(d.ifModified){if(x=v.getResponseHeader("Last-Modified"))f.lastModified[k]=x;if(y=v.getResponseHeader("Etag"))f.etag[k]=y}if(a===304)c="notmodified",o=!0;else try{r=b$(d,w),c="success",o=!0}catch(z){c="parsererror",u=z}}else{u=c;if(!c||a)c="error",a<0&&(a=0)}v.status=a,v.statusText=c,o?h.resolveWith(e,[r,c,v]):h.rejectWith(e,[v,c,u]),v.statusCode(j),j=b,t&&g.trigger("ajax"+(o?"Success":"Error"),[v,d,o?r:u]),i.resolveWith(e,[v,c]),t&&(g.trigger("ajaxComplete",[v,d]),--f.active||f.event.trigger("ajaxStop"))}}typeof a=="object"&&(c=a,a=b),c=c||{};var d=f.ajaxSetup({},c),e=d.context||d,g=e!==d&&(e.nodeType||e instanceof f)?f(e):f.event,h=f.Deferred(),i=f._Deferred(),j=d.statusCode||{},k,l={},m={},n,o,p,q,r,s=0,t,u,v={readyState:0,setRequestHeader:function(a,b){if(!s){var c=a.toLowerCase();a=m[c]=m[c]||a,l[a]=b}return this},getAllResponseHeaders:function(){return s===2?n:null},getResponseHeader:function(a){var c;if(s===2){if(!o){o={};while(c=bF.exec(n))o[c[1].toLowerCase()]=c[2]}c=o[a.toLowerCase()]}return c===b?null:c},overrideMimeType:function(a){s||(d.mimeType=a);return this},abort:function(a){a=a||"abort",p&&p.abort(a),w(0,a);return this}};h.promise(v),v.success=v.done,v.error=v.fail,v.complete=i.done,v.statusCode=function(a){if(a){var b;if(s<2)for(b in a)j[b]=[j[b],a[b]];else b=a[v.status],v.then(b,b)}return this},d.url=((a||d.url)+"").replace(bE,"").replace(bJ,bU[1]+"//"),d.dataTypes=f.trim(d.dataType||"*").toLowerCase().split(bN),d.crossDomain==null&&(r=bP.exec(d.url.toLowerCase()),d.crossDomain=!(!r||r[1]==bU[1]&&r[2]==bU[2]&&(r[3]||(r[1]==="http:"?80:443))==(bU[3]||(bU[1]==="http:"?80:443)))),d.data&&d.processData&&typeof d.data!="string"&&(d.data=f.param(d.data,d.traditional)),bX(bR,d,c,v);if(s===2)return!1;t=d.global,d.type=d.type.toUpperCase(),d.hasContent=!bI.test(d.type),t&&f.active++===0&&f.event.trigger("ajaxStart");if(!d.hasContent){d.data&&(d.url+=(bK.test(d.url)?"&":"?")+d.data),k=d.url;if(d.cache===!1){var x=f.now(),y=d.url.replace(bO,"$1_="+x);d.url=y+(y===d.url?(bK.test(d.url)?"&":"?")+"_="+x:"")}}(d.data&&d.hasContent&&d.contentType!==!1||c.contentType)&&v.setRequestHeader("Content-Type",d.contentType),d.ifModified&&(k=k||d.url,f.lastModified[k]&&v.setRequestHeader("If-Modified-Since",f.lastModified[k]),f.etag[k]&&v.setRequestHeader("If-None-Match",f.etag[k])),v.setRequestHeader("Accept",d.dataTypes[0]&&d.accepts[d.dataTypes[0]]?d.accepts[d.dataTypes[0]]+(d.dataTypes[0]!=="*"?", */*; q=0.01":""):d.accepts["*"]);for(u in d.headers)v.setRequestHeader(u,d.headers[u]);if(d.beforeSend&&(d.beforeSend.call(e,v,d)===!1||s===2)){v.abort();return!1}for(u in{success:1,error:1,complete:1})v[u](d[u]);p=bX(bS,d,c,v);if(!p)w(-1,"No Transport");else{v.readyState=1,t&&g.trigger("ajaxSend",[v,d]),d.async&&d.timeout>0&&(q=setTimeout(function(){v.abort("timeout")},d.timeout));try{s=1,p.send(l,w)}catch(z){status<2?w(-1,z):f.error(z)}}return v},param:function(a,c){var d=[],e=function(a,b){b=f.isFunction(b)?b():b,d[d.length]=encodeURIComponent(a)+"="+encodeURIComponent(b)};c===b&&(c=f.ajaxSettings.traditional);if(f.isArray(a)||a.jquery&&!f.isPlainObject(a))f.each(a,function(){e(this.name,this.value)});else for(var g in a)bY(g,a[g],c,e);return d.join("&").replace(bB,"+")}}),f.extend({active:0,lastModified:{},etag:{}});var b_=f.now(),ca=/(\=)\?(&|$)|\?\?/i;f.ajaxSetup({jsonp:"callback",jsonpCallback:function(){return f.expando+"_"+b_++}}),f.ajaxPrefilter("json jsonp",function(b,c,d){var e=b.contentType==="application/x-www-form-urlencoded"&&typeof b.data=="string";if(b.dataTypes[0]==="jsonp"||b.jsonp!==!1&&(ca.test(b.url)||e&&ca.test(b.data))){var g,h=b.jsonpCallback=f.isFunction(b.jsonpCallback)?b.jsonpCallback():b.jsonpCallback,i=a[h],j=b.url,k=b.data,l="$1"+h+"$2";b.jsonp!==!1&&(j=j.replace(ca,l),b.url===j&&(e&&(k=k.replace(ca,l)),b.data===k&&(j+=(/\?/.test(j)?"&":"?")+b.jsonp+"="+h))),b.url=j,b.data=k,a[h]=function(a){g=[a]},d.always(function(){a[h]=i,g&&f.isFunction(i)&&a[h](g[0])}),b.converters["script json"]=function(){g||f.error(h+" was not called");return g[0]},b.dataTypes[0]="json";return"script"}}),f.ajaxSetup({accepts:{script:"text/javascript, application/javascript, application/ecmascript, application/x-ecmascript"},contents:{script:/javascript|ecmascript/},converters:{"text script":function(a){f.globalEval(a);return a}}}),f.ajaxPrefilter("script",function(a){a.cache===b&&(a.cache=!1),a.crossDomain&&(a.type="GET",a.global=!1)}),f.ajaxTransport("script",function(a){if(a.crossDomain){var d,e=c.head||c.getElementsByTagName("head")[0]||c.documentElement;return{send:function(f,g){d=c.createElement("script"),d.async="async",a.scriptCharset&&(d.charset=a.scriptCharset),d.src=a.url,d.onload=d.onreadystatechange=function(a,c){if(c||!d.readyState||/loaded|complete/.test(d.readyState))d.onload=d.onreadystatechange=null,e&&d.parentNode&&e.removeChild(d),d=b,c||g(200,"success")},e.insertBefore(d,e.firstChild)},abort:function(){d&&d.onload(0,1)}}}});var cb=a.ActiveXObject?function(){for(var a in cd)cd[a](0,1)}:!1,cc=0,cd;f.ajaxSettings.xhr=a.ActiveXObject?function(){return!this.isLocal&&ce()||cf()}:ce,function(a){f.extend(f.support,{ajax:!!a,cors:!!a&&"withCredentials"in a})}(f.ajaxSettings.xhr()),f.support.ajax&&f.ajaxTransport(function(c){if(!c.crossDomain||f.support.cors){var d;return{send:function(e,g){var h=c.xhr(),i,j;c.username?h.open(c.type,c.url,c.async,c.username,c.password):h.open(c.type,c.url,c.async);if(c.xhrFields)for(j in c.xhrFields)h[j]=c.xhrFields[j];c.mimeType&&h.overrideMimeType&&h.overrideMimeType(c.mimeType),!c.crossDomain&&!e["X-Requested-With"]&&(e["X-Requested-With"]="XMLHttpRequest");try{for(j in e)h.setRequestHeader(j,e[j])}catch(k){}h.send(c.hasContent&&c.data||null),d=function(a,e){var j,k,l,m,n;try{if(d&&(e||h.readyState===4)){d=b,i&&(h.onreadystatechange=f.noop,cb&&delete cd[i]);if(e)h.readyState!==4&&h.abort();else{j=h.status,l=h.getAllResponseHeaders(),m={},n=h.responseXML,n&&n.documentElement&&(m.xml=n),m.text=h.responseText;try{k=h.statusText}catch(o){k=""}!j&&c.isLocal&&!c.crossDomain?j=m.text?200:404:j===1223&&(j=204)}}}catch(p){e||g(-1,p)}m&&g(j,k,m,l)},!c.async||h.readyState===4?d():(i=++cc,cb&&(cd||(cd={},f(a).unload(cb)),cd[i]=d),h.onreadystatechange=d)},abort:function(){d&&d(0,1)}}}});var cg={},ch,ci,cj=/^(?:toggle|show|hide)$/,ck=/^([+\-]=)?([\d+.\-]+)([a-z%]*)$/i,cl,cm=[["height","marginTop","marginBottom","paddingTop","paddingBottom"],["width","marginLeft","marginRight","paddingLeft","paddingRight"],["opacity"]],cn,co=a.webkitRequestAnimationFrame||a.mozRequestAnimationFrame||a.oRequestAnimationFrame;f.fn.extend({show:function(a,b,c){var d,e;if(a||a===0)return this.animate(cr("show",3),a,b,c);for(var g=0,h=this.length;g<h;g++)d=this[g],d.style&&(e=d.style.display,!f._data(d,"olddisplay")&&e==="none"&&(e=d.style.display=""),e===""&&f.css(d,"display")==="none"&&f._data(d,"olddisplay",cs(d.nodeName)));for(g=0;g<h;g++){d=this[g];if(d.style){e=d.style.display;if(e===""||e==="none")d.style.display=f._data(d,"olddisplay")||""}}return this},hide:function(a,b,c){if(a||a===0)return this.animate(cr("hide",3),a,b,c);for(var d=0,e=this.length;d<e;d++)if(this[d].style){var g=f.css(this[d],"display");g!=="none"&&!f._data(this[d],"olddisplay")&&f._data(this[d],"olddisplay",g)}for(d=0;d<e;d++)this[d].style&&(this[d].style.display="none");return this},_toggle:f.fn.toggle,toggle:function(a,b,c){var d=typeof a=="boolean";f.isFunction(a)&&f.isFunction(b)?this._toggle.apply(this,arguments):a==null||d?this.each(function(){var b=d?a:f(this).is(":hidden");f(this)[b?"show":"hide"]()}):this.animate(cr("toggle",3),a,b,c);return this},fadeTo:function(a,b,c,d){return this.filter(":hidden").css("opacity",0).show().end().animate({opacity:b},a,c,d)},animate:function(a,b,c,d){var e=f.speed(b,c,d);if(f.isEmptyObject(a))return this.each(e.complete,[!1]);a=f.extend({},a);return this[e.queue===!1?"each":"queue"](function(){e.queue===!1&&f._mark(this);var b=f.extend({},e),c=this.nodeType===1,d=c&&f(this).is(":hidden"),g,h,i,j,k,l,m,n,o;b.animatedProperties={};for(i in a){g=f.camelCase(i),i!==g&&(a[g]=a[i],delete a[i]),h=a[g],f.isArray(h)?(b.animatedProperties[g]=h[1],h=a[g]=h[0]):b.animatedProperties[g]=b.specialEasing&&b.specialEasing[g]||b.easing||"swing";if(h==="hide"&&d||h==="show"&&!d)return b.complete.call(this);c&&(g==="height"||g==="width")&&(b.overflow=[this.style.overflow,this.style.overflowX,this.style.overflowY],f.css(this,"display")==="inline"&&f.css(this,"float")==="none"&&(f.support.inlineBlockNeedsLayout?(j=cs(this.nodeName),j==="inline"?this.style.display="inline-block":(this.style.display="inline",this.style.zoom=1)):this.style.display="inline-block"))}b.overflow!=null&&(this.style.overflow="hidden");for(i in a)k=new f.fx(this,b,i),h=a[i],cj.test(h)?k[h==="toggle"?d?"show":"hide":h]():(l=ck.exec(h),m=k.cur(),l?(n=parseFloat(l[2]),o=l[3]||(f.cssNumber[i]?"":"px"),o!=="px"&&(f.style(this,i,(n||1)+o),m=(n||1)/k.cur()*m,f.style(this,i,m+o)),l[1]&&(n=(l[1]==="-="?-1:1)*n+m),k.custom(m,n,o)):k.custom(m,h,""));return!0})},stop:function(a,b){a&&this.queue([]),this.each(function(){var a=f.timers,c=a.length;b||f._unmark(!0,this);while(c--)a[c].elem===this&&(b&&a[c](!0),a.splice(c,1))}),b||this.dequeue();return this}}),f.each({slideDown:cr("show",1),slideUp:cr("hide",1),slideToggle:cr("toggle",1),fadeIn:{opacity:"show"},fadeOut:{opacity:"hide"},fadeToggle:{opacity:"toggle"}},function(a,b){f.fn[a]=function(a,c,d){return this.animate(b,a,c,d)}}),f.extend({speed:function(a,b,c){var d=a&&typeof a=="object"?f.extend({},a):{complete:c||!c&&b||f.isFunction(a)&&a,duration:a,easing:c&&b||b&&!f.isFunction(b)&&b};d.duration=f.fx.off?0:typeof d.duration=="number"?d.duration:d.duration in f.fx.speeds?f.fx.speeds[d.duration]:f.fx.speeds._default,d.old=d.complete,d.complete=function(a){f.isFunction(d.old)&&d.old.call(this),d.queue!==!1?f.dequeue(this):a!==!1&&f._unmark(this)};return d},easing:{linear:function(a,b,c,d){return c+d*a},swing:function(a,b,c,d){return(-Math.cos(a*Math.PI)/2+.5)*d+c}},timers:[],fx:function(a,b,c){this.options=b,this.elem=a,this.prop=c,b.orig=b.orig||{}}}),f.fx.prototype={update:function(){this.options.step&&this.options.step.call(this.elem,this.now,this),(f.fx.step[this.prop]||f.fx.step._default)(this)},cur:function(){if(this.elem[this.prop]!=null&&(!this.elem.style||this.elem.style[this.prop]==null))return this.elem[this.prop];var a,b=f.css(this.elem,this.prop);return isNaN(a=parseFloat(b))?!b||b==="auto"?0:b:a},custom:function(a,b,c){function h(a){return d.step(a)}var d=this,e=f.fx,g;this.startTime=cn||cp(),this.start=a,this.end=b,this.unit=c||this.unit||(f.cssNumber[this.prop]?"":"px"),this.now=this.start,this.pos=this.state=0,h.elem=this.elem,h()&&f.timers.push(h)&&!cl&&(co?(cl=!0,g=function(){cl&&(co(g),e.tick())},co(g)):cl=setInterval(e.tick,e.interval))},show:function(){this.options.orig[this.prop]=f.style(this.elem,this.prop),this.options.show=!0,this.custom(this.prop==="width"||this.prop==="height"?1:0,this.cur()),f(this.elem).show()},hide:function(){this.options.orig[this.prop]=f.style(this.elem,this.prop),this.options.hide=!0,this.custom(this.cur(),0)},step:function(a){var b=cn||cp(),c=!0,d=this.elem,e=this.options,g,h;if(a||b>=e.duration+this.startTime){this.now=this.end,this.pos=this.state=1,this.update(),e.animatedProperties[this.prop]=!0;for(g in e.animatedProperties)e.animatedProperties[g]!==!0&&(c=!1);if(c){e.overflow!=null&&!f.support.shrinkWrapBlocks&&f.each(["","X","Y"],function(a,b){d.style["overflow"+b]=e.overflow[a]}),e.hide&&f(d).hide();if(e.hide||e.show)for(var i in e.animatedProperties)f.style(d,i,e.orig[i]);e.complete.call(d)}return!1}e.duration==Infinity?this.now=b:(h=b-this.startTime,this.state=h/e.duration,this.pos=f.easing[e.animatedProperties[this.prop]](this.state,h,0,1,e.duration),this.now=this.start+(this.end-this.start)*this.pos),this.update();return!0}},f.extend(f.fx,{tick:function(){for(var a=f.timers,b=0;b<a.length;++b)a[b]()||a.splice(b--,1);a.length||f.fx.stop()},interval:13,stop:function(){clearInterval(cl),cl=null},speeds:{slow:600,fast:200,_default:400},step:{opacity:function(a){f.style(a.elem,"opacity",a.now)},_default:function(a){a.elem.style&&a.elem.style[a.prop]!=null?a.elem.style[a.prop]=(a.prop==="width"||a.prop==="height"?Math.max(0,a.now):a.now)+a.unit:a.elem[a.prop]=a.now}}}),f.expr&&f.expr.filters&&(f.expr.filters.animated=function(a){return f.grep(f.timers,function(b){return a===b.elem}).length});var ct=/^t(?:able|d|h)$/i,cu=/^(?:body|html)$/i;"getBoundingClientRect"in c.documentElement?f.fn.offset=function(a){var b=this[0],c;if(a)return this.each(function(b){f.offset.setOffset(this,a,b)});if(!b||!b.ownerDocument)return null;if(b===b.ownerDocument.body)return f.offset.bodyOffset(b);try{c=b.getBoundingClientRect()}catch(d){}var e=b.ownerDocument,g=e.documentElement;if(!c||!f.contains(g,b))return c?{top:c.top,left:c.left}:{top:0,left:0};var h=e.body,i=cv(e),j=g.clientTop||h.clientTop||0,k=g.clientLeft||h.clientLeft||0,l=i.pageYOffset||f.support.boxModel&&g.scrollTop||h.scrollTop,m=i.pageXOffset||f.support.boxModel&&g.scrollLeft||h.scrollLeft,n=c.top+l-j,o=c.left+m-k;return{top:n,left:o}}:f.fn.offset=function(a){var b=this[0];if(a)return this.each(function(b){f.offset.setOffset(this,a,b)});if(!b||!b.ownerDocument)return null;if(b===b.ownerDocument.body)return f.offset.bodyOffset(b);f.offset.initialize();var c,d=b.offsetParent,e=b,g=b.ownerDocument,h=g.documentElement,i=g.body,j=g.defaultView,k=j?j.getComputedStyle(b,null):b.currentStyle,l=b.offsetTop,m=b.offsetLeft;while((b=b.parentNode)&&b!==i&&b!==h){if(f.offset.supportsFixedPosition&&k.position==="fixed")break;c=j?j.getComputedStyle(b,null):b.currentStyle,l-=b.scrollTop,m-=b.scrollLeft,b===d&&(l+=b.offsetTop,m+=b.offsetLeft,f.offset.doesNotAddBorder&&(!f.offset.doesAddBorderForTableAndCells||!ct.test(b.nodeName))&&(l+=parseFloat(c.borderTopWidth)||0,m+=parseFloat(c.borderLeftWidth)||0),e=d,d=b.offsetParent),f.offset.subtractsBorderForOverflowNotVisible&&c.overflow!=="visible"&&(l+=parseFloat(c.borderTopWidth)||0,m+=parseFloat(c.borderLeftWidth)||0),k=c}if(k.position==="relative"||k.position==="static")l+=i.offsetTop,m+=i.offsetLeft;f.offset.supportsFixedPosition&&k.position==="fixed"&&(l+=Math.max(h.scrollTop,i.scrollTop),m+=Math.max(h.scrollLeft,i.scrollLeft));return{top:l,left:m}},f.offset={initialize:function(){var a=c.body,b=c.createElement("div"),d,e,g,h,i=parseFloat(f.css(a,"marginTop"))||0,j="<div style='position:absolute;top:0;left:0;margin:0;border:5px solid #000;padding:0;width:1px;height:1px;'><div></div></div><table style='position:absolute;top:0;left:0;margin:0;border:5px solid #000;padding:0;width:1px;height:1px;' cellpadding='0' cellspacing='0'><tr><td></td></tr></table>";f.extend(b.style,{position:"absolute",top:0,left:0,margin:0,border:0,width:"1px",height:"1px",visibility:"hidden"}),b.innerHTML=j,a.insertBefore(b,a.firstChild),d=b.firstChild,e=d.firstChild,h=d.nextSibling.firstChild.firstChild,this.doesNotAddBorder=e.offsetTop!==5,this.doesAddBorderForTableAndCells=h.offsetTop===5,e.style.position="fixed",e.style.top="20px",this.supportsFixedPosition=e.offsetTop===20||e.offsetTop===15,e.style.position=e.style.top="",d.style.overflow="hidden",d.style.position="relative",this.subtractsBorderForOverflowNotVisible=e.offsetTop===-5,this.doesNotIncludeMarginInBodyOffset=a.offsetTop!==i,a.removeChild(b),f.offset.initialize=f.noop},bodyOffset:function(a){var b=a.offsetTop,c=a.offsetLeft;f.offset.initialize(),f.offset.doesNotIncludeMarginInBodyOffset&&(b+=parseFloat(f.css(a,"marginTop"))||0,c+=parseFloat(f.css(a,"marginLeft"))||0);return{top:b,left:c}},setOffset:function(a,b,c){var d=f.css(a,"position");d==="static"&&(a.style.position="relative");var e=f(a),g=e.offset(),h=f.css(a,"top"),i=f.css(a,"left"),j=(d==="absolute"||d==="fixed")&&f.inArray("auto",[h,i])>-1,k={},l={},m,n;j?(l=e.position(),m=l.top,n=l.left):(m=parseFloat(h)||0,n=parseFloat(i)||0),f.isFunction(b)&&(b=b.call(a,c,g)),b.top!=null&&(k.top=b.top-g.top+m),b.left!=null&&(k.left=b.left-g.left+n),"using"in b?b.using.call(a,k):e.css(k)}},f.fn.extend({position:function(){if(!this[0])return null;var a=this[0],b=this.offsetParent(),c=this.offset(),d=cu.test(b[0].nodeName)?{top:0,left:0}:b.offset();c.top-=parseFloat(f.css(a,"marginTop"))||0,c.left-=parseFloat(f.css(a,"marginLeft"))||0,d.top+=parseFloat(f.css(b[0],"borderTopWidth"))||0,d.left+=parseFloat(f.css(b[0],"borderLeftWidth"))||0;return{top:c.top-d.top,left:c.left-d.left}},offsetParent:function(){return this.map(function(){var a=this.offsetParent||c.body;while(a&&!cu.test(a.nodeName)&&f.css(a,"position")==="static")a=a.offsetParent;return a})}}),f.each(["Left","Top"],function(a,c){var d="scroll"+c;f.fn[d]=function(c){var e,g;if(c===b){e=this[0];if(!e)return null;g=cv(e);return g?"pageXOffset"in g?g[a?"pageYOffset":"pageXOffset"]:f.support.boxModel&&g.document.documentElement[d]||g.document.body[d]:e[d]}return this.each(function(){g=cv(this),g?g.scrollTo(a?f(g).scrollLeft():c,a?c:f(g).scrollTop()):this[d]=c})}}),f.each(["Height","Width"],function(a,c){var d=c.toLowerCase();f.fn["inner"+c]=function(){var a=this[0];return a&&a.style?parseFloat(f.css(a,d,"padding")):null},f.fn["outer"+c]=function(a){var b=this[0];return b&&b.style?parseFloat(f.css(b,d,a?"margin":"border")):null},f.fn[d]=function(a){var e=this[0];if(!e)return a==null?null:this;if(f.isFunction(a))return this.each(function(b){var c=f(this);c[d](a.call(this,b,c[d]()))});if(f.isWindow(e)){var g=e.document.documentElement["client"+c];return e.document.compatMode==="CSS1Compat"&&g||e.document.body["client"+c]||g}if(e.nodeType===9)return Math.max(e.documentElement["client"+c],e.body["scroll"+c],e.documentElement["scroll"+c],e.body["offset"+c],e.documentElement["offset"+c]);if(a===b){var h=f.css(e,d),i=parseFloat(h);return f.isNaN(i)?h:i}return this.css(d,typeof a=="string"?a:a+"px")}}),a.jQuery=a.$=f})(window);
components/ListPage/ListPres/ListPres.js
yodairish/pres-view
'use strict'; import React from 'react'; import PresListStore from '../../../js/stores/PresListStore.js'; import PresListActions from '../../../js/actions/PresListActions.js'; import ListPresItem from './ListPresItem/ListPresItem.js'; import LoadMore from './LoadMore/LoadMore.js'; export default React.createClass({ /** * Set default state */ getInitialState() { if (!PresListStore.getCount()) { PresListActions.loadMore(); } return { items: PresListStore.getAll() }; }, /** * When component into the DOM * Start listening updating list of items */ componentDidMount() { PresListStore.addChangeListener(this.onChange); }, /** * When component remove from DOM * Stop listening updating list of items */ componentWillUnmount() { PresListStore.removeChangeListener(this.onChange); }, /** * After changing presentation list update items list */ onChange() { this.setState({ items: PresListStore.getAll() }); }, /** * Rendering component to html */ render() { var items = this.state.items.map((item, index) => { return <ListPresItem key={item.id + '-' + index} id={item.id} title={item.title} img={item.img} favorite={item.favorite} />; }), emptyMessage = <p className="listPres-empty"> No any presentation </p>; if (items.length) { emptyMessage = ''; } return ( <div className="listPres"> <div className="listPres-list"> {items} </div> {emptyMessage} <LoadMore /> </div> ); } });
site/src/components/App.js
livesmoking/livesmoking
import React from 'react' import ConnectionSelector from './ConnectionSelector' import Room from './Room' class App extends React.Component { constructor(props) { super(props) this.state = {} this.onJoinClicked = this.onJoinClicked.bind(this) } componentDidMount() { this.context.history.listen(() => { this.forceUpdate() }) } onJoinClicked(connection) { if (connection.username === 'webkiit') { return alert('GTFO!!!') } const { room, username } = connection return this.context.history.push(`/room/${room}/${username}`) } renderPage() { const urlSegments = this.context.history.location.pathname.split('/') urlSegments.shift() if (urlSegments[0] === '') { return <ConnectionSelector onJoinClicked={this.onJoinClicked} /> } switch (urlSegments.shift()) { case 'room': { const [room, username] = urlSegments if (!username) { return <ConnectionSelector room={room} onJoinClicked={this.onJoinClicked} /> } if (room && username) { return <Room room={room} username={username} /> } break } default: return null } return null } render() { return ( <div className="app"> { this.renderPage() } </div> ) } } App.contextTypes = { history: React.PropTypes.object } export default App
node_modules/react-icons/ti/social-google-plus-circular.js
bairrada97/festival
import React from 'react' import Icon from 'react-icon-base' const TiSocialGooglePlusCircular = props => ( <Icon viewBox="0 0 40 40" {...props}> <g><path d="m21.3 21.8l-0.6-0.5c-0.2-0.1-0.5-0.3-0.5-0.8l0.5-1c0.8-0.7 1.6-1.3 1.6-2.8s-1-2.4-1.3-2.7h1.2l1.1-0.7h-4c-1 0-2.3 0.2-3.5 1-0.8 0.7-1.3 1.7-1.3 2.7 0 1.5 1.2 3.2 3.3 3.2h0.7c-0.2 0.1-0.2 0.3-0.2 0.6 0 0.7 0.4 1 0.7 1.4-0.8 0-2.5 0.1-3.8 0.8-1.2 0.7-1.5 1.7-1.5 2.3 0 1.5 1.3 2.9 4.1 2.9 3.4 0 5.2-1.9 5.2-3.7 0-1.2-0.8-1.8-1.7-2.7z m-2.6-2.1c-1.7 0-2.5-2.2-2.5-3.5 0.1-0.7 0.1-1.2 0.5-1.5s0.8-0.7 1.3-0.7c1.7 0 2.5 2.2 2.5 3.7 0 0.3 0 1-0.5 1.5-0.2 0.1-0.8 0.5-1.3 0.5z m0.1 7.8c-2.1 0-3.5-1-3.5-2.3 0-1.4 1.4-1.9 1.7-2 0.8-0.4 1.8-0.4 2-0.4h0.5c1.5 1 2.2 1.7 2.2 2.7 0 1.2-1 2-2.9 2z m6.2-7.5h-1.7v-1.7h1.7v-1.6h1.7v1.6h1.6v1.7h-1.6v1.7h-1.7z m-5 15c-8.3 0-15-6.7-15-15s6.7-15 15-15 15 6.7 15 15-6.7 15-15 15z m0-26.7c-6.5 0-11.7 5.2-11.7 11.7s5.2 11.7 11.7 11.7 11.7-5.2 11.7-11.7-5.2-11.7-11.7-11.7z"/></g> </Icon> ) export default TiSocialGooglePlusCircular
jenkins-design-language/src/js/components/material-ui/svg-icons/communication/ring-volume.js
alvarolobato/blueocean-plugin
import React from 'react'; import SvgIcon from '../../SvgIcon'; const CommunicationRingVolume = (props) => ( <SvgIcon {...props}> <path d="M23.71 16.67C20.66 13.78 16.54 12 12 12 7.46 12 3.34 13.78.29 16.67c-.18.18-.29.43-.29.71 0 .28.11.53.29.71l2.48 2.48c.18.18.43.29.71.29.27 0 .52-.11.7-.28.79-.74 1.69-1.36 2.66-1.85.33-.16.56-.5.56-.9v-3.1c1.45-.48 3-.73 4.6-.73s3.15.25 4.6.72v3.1c0 .39.23.74.56.9.98.49 1.87 1.12 2.66 1.85.18.18.43.28.7.28.28 0 .53-.11.71-.29l2.48-2.48c.18-.18.29-.43.29-.71 0-.27-.11-.52-.29-.7zM21.16 6.26l-1.41-1.41-3.56 3.55 1.41 1.41s3.45-3.52 3.56-3.55zM13 2h-2v5h2V2zM6.4 9.81L7.81 8.4 4.26 4.84 2.84 6.26c.11.03 3.56 3.55 3.56 3.55z"/> </SvgIcon> ); CommunicationRingVolume.displayName = 'CommunicationRingVolume'; CommunicationRingVolume.muiName = 'SvgIcon'; export default CommunicationRingVolume;
renderer/components/TextEditorPane.js
reactide/reactide
import React from 'react'; import TextEditor from './TextEditor'; import TabContainer from './TabContainer'; import PropTypes from 'prop-types'; const TextEditorPane = ({ appState, setActiveTab, closeTab, onEditorValueChange, cbOpenSimulator_Main, cbOpenSimulator_Ext }) => { // const editorArr = []; // if (Object.keys(appState.openTabs).length > 0) { // //console.log(appState.previousPaths[appState.previousPaths.length-1]); // editorArr.push( // <TextEditor // path={appState.previousPaths[appState.previousPaths.length-1]} // onValueChange={onEditorValueChange} // />); // } return ( <ride-pane> {Object.keys(appState.openTabs).length > 0 && <React.Fragment> <TextEditor path={appState.previousPaths[appState.previousPaths.length - 1]} onValueChange={onEditorValueChange} /> </React.Fragment> } </ride-pane> ); }; TextEditorPane.propTypes = { appState: PropTypes.object.isRequired, setActiveTab: PropTypes.func.isRequired, closeTab: PropTypes.func.isRequired }; export default TextEditorPane;
scripts/templates/stateless-functional-component.js
fpoumian/react-devicon
module.exports = `import React from 'react' import PropTypes from 'prop-types' import SVGDeviconInline from '../../_base/SVGDeviconInline' import iconSVG from './{{ componentName }}.svg' /** {{ componentName }} */ function {{ componentName }}({ width, height, className }) { return ( <SVGDeviconInline className={ '{{ componentName }}' + ' ' + className } iconSVG={iconSVG} width={width} height={height} /> ) } {{ componentName }}.propTypes = { className: PropTypes.string, width: PropTypes.oneOfType([PropTypes.string, PropTypes.number]), height: PropTypes.oneOfType([PropTypes.string, PropTypes.number]) } export default {{ componentName }} `
src/components/action-menu/components/ActionMenuSetup.js
mailvelope/mailvelope-styleguide
/** * Copyright (C) 2017 Mailvelope GmbH * Licensed under the GNU Affero General Public License version 3 */ import React from 'react'; import PropTypes from 'prop-types'; function ActionMenuSetup(props) { return ( <div className="primary"> <ul className="action-menu" role="menu" aria-label="Mailvelope setup menu"> <li className="item-big" role="menuitem"> <a className="clearfix" id="setup-keys" onClick={props.onMenuItemClickHandler} role="button"> <p><strong>Configure Mailvelope</strong> to get started!</p> <i className="fa fa-gear" role="presentation"></i> </a> </li> </ul> <div className="footer"> <a id="options" onClick={props.onMenuItemClickHandler} role="button">More options</a> </div> </div> ); } ActionMenuSetup.propTypes = { onMenuItemClickHandler: PropTypes.func }; export default ActionMenuSetup;
client/containers/Annotate.js
exacs/liqen-face
import React from 'react' import { connect } from 'react-redux' import zipWith from 'lodash/fp/zipWith' import fetch from 'isomorphic-fetch' import Article from '../components/annotator/article' import MultiList from '../components/annotator-drawer/multi-list' import LiqenCreator from '../components/annotator-drawer/liqen-creator' import { createAnnotation, createLiqen } from '../actions/index' const article = window.__ARTICLE__ export class Annotate extends React.Component { constructor (props) { super(props) this.state = { articleBody: { name: 'div', attrs: {}, children: [] } } } componentDidMount () { fetch(`/parseArticle?uri=${article.source.uri}`) .then(response => response.json()) .then(obj => { this.setState({articleBody: obj.body.object}) }) } render () { const { question, answer, annotations, liqens, tags, onCreateAnnotation, onCreateLiqen } = this.props return ( <div className='row'> <aside className='hidden-md-down col-lg-4 flex-last'> <h3 className='h6 text-uppercase text-muted'>Create your Liqen (your Answer)</h3> <LiqenCreator question={question} answer={answer} onSubmit={onCreateLiqen} /> <MultiList annotations={annotations} liqens={liqens} /> </aside> <div className='col-lg-8 col-xl-7'> <header> <h1 className="article-title">{article.title}</h1> </header> <main className='article-body'> <Article body={this.state.articleBody} tags={tags} onCreateAnnotation={onCreateAnnotation} /> </main> </div> </div> ) } } const mapStateToAnswer = (state) => { const questionAnswer = state.question.answer.map( ({tag, required}) => ({ tag: state.tags[tag].title, required }) ) const liqenAnswer = state.newLiqen.answer.map( a => state.annotations[a] || null ) const zipper = (qa, la) => ({ title: qa.tag, exact: (la && la.target && la.target.exact) || '' }) return zipWith(zipper, questionAnswer, liqenAnswer) } const mapStateToAnnotations = (state) => { const ret = [] for (let ref in state.annotations) { const {tag, checked, pending, target} = state.annotations[ref] ret.push({ tag: state.tags[tag].title, ref, target, checked, pending }) } return ret } const mapStateToLiqens = (state) => { const ret = [] for (let ref in state.liqens) { const {answer, pending} = state.liqens[ref] ret.push({ answer: answer .map(a => { if (!state.annotations[a]) { return null } const {tag, target} = state.annotations[a] return { target, ref: a, tag: state.tags[tag] } }) .filter(a => a !== null), ref, pending }) } return ret } const mapStateToProps = (state) => ({ question: state.question.title, answer: mapStateToAnswer(state), annotations: mapStateToAnnotations(state), liqens: mapStateToLiqens(state), tags: state.question.answer.map( ({tag}) => ({ref: tag, title: state.tags[tag].title}) ), enableCreateLiqen: state.newLiqen.answer.every( a => state.annotations[a] && !state.annotations[a].pending ) }) const mapDispatchToProps = (dispatch) => ({ onCreateAnnotation: ({target, tag}) => dispatch(createAnnotation(target, tag)), onCreateLiqen: () => dispatch(createLiqen()) }) const mergeProps = (stateProps, dispatchProps) => Object.assign({}, stateProps, dispatchProps, { onCreateLiqen: stateProps.enableCreateLiqen && dispatchProps.onCreateLiqen }) export default connect( mapStateToProps, mapDispatchToProps, mergeProps )(Annotate)
ajax/libs/yui/3.2.0/event-custom/event-custom-base-debug.js
jacobq/cdnjs
YUI.add('event-custom-base', function(Y) { /** * Custom event engine, DOM event listener abstraction layer, synthetic DOM * events. * @module event-custom */ Y.Env.evt = { handles: {}, plugins: {} }; /** * Custom event engine, DOM event listener abstraction layer, synthetic DOM * events. * @module event-custom * @submodule event-custom-base */ (function() { /** * Allows for the insertion of methods that are executed before or after * a specified method * @class Do * @static */ var BEFORE = 0, AFTER = 1; Y.Do = { /** * Cache of objects touched by the utility * @property objs * @static */ objs: {}, /** * Execute the supplied method before the specified function * @method before * @param fn {Function} the function to execute * @param obj the object hosting the method to displace * @param sFn {string} the name of the method to displace * @param c The execution context for fn * @param arg* {mixed} 0..n additional arguments to supply to the subscriber * when the event fires. * @return {string} handle for the subscription * @static */ before: function(fn, obj, sFn, c) { // Y.log('Do before: ' + sFn, 'info', 'event'); var f = fn, a; if (c) { a = [fn, c].concat(Y.Array(arguments, 4, true)); f = Y.rbind.apply(Y, a); } return this._inject(BEFORE, f, obj, sFn); }, /** * Execute the supplied method after the specified function * @method after * @param fn {Function} the function to execute * @param obj the object hosting the method to displace * @param sFn {string} the name of the method to displace * @param c The execution context for fn * @param arg* {mixed} 0..n additional arguments to supply to the subscriber * @return {string} handle for the subscription * @static */ after: function(fn, obj, sFn, c) { var f = fn, a; if (c) { a = [fn, c].concat(Y.Array(arguments, 4, true)); f = Y.rbind.apply(Y, a); } return this._inject(AFTER, f, obj, sFn); }, /** * Execute the supplied method after the specified function * @method _inject * @param when {string} before or after * @param fn {Function} the function to execute * @param obj the object hosting the method to displace * @param sFn {string} the name of the method to displace * @param c The execution context for fn * @return {string} handle for the subscription * @private * @static */ _inject: function(when, fn, obj, sFn) { // object id var id = Y.stamp(obj), o, sid; if (! this.objs[id]) { // create a map entry for the obj if it doesn't exist this.objs[id] = {}; } o = this.objs[id]; if (! o[sFn]) { // create a map entry for the method if it doesn't exist o[sFn] = new Y.Do.Method(obj, sFn); // re-route the method to our wrapper obj[sFn] = function() { return o[sFn].exec.apply(o[sFn], arguments); }; } // subscriber id sid = id + Y.stamp(fn) + sFn; // register the callback o[sFn].register(sid, fn, when); return new Y.EventHandle(o[sFn], sid); }, /** * Detach a before or after subscription * @method detach * @param handle {string} the subscription handle */ detach: function(handle) { if (handle.detach) { handle.detach(); } }, _unload: function(e, me) { } }; ////////////////////////////////////////////////////////////////////////// /** * Wrapper for a displaced method with aop enabled * @class Do.Method * @constructor * @param obj The object to operate on * @param sFn The name of the method to displace */ Y.Do.Method = function(obj, sFn) { this.obj = obj; this.methodName = sFn; this.method = obj[sFn]; this.before = {}; this.after = {}; }; /** * Register a aop subscriber * @method register * @param sid {string} the subscriber id * @param fn {Function} the function to execute * @param when {string} when to execute the function */ Y.Do.Method.prototype.register = function (sid, fn, when) { if (when) { this.after[sid] = fn; } else { this.before[sid] = fn; } }; /** * Unregister a aop subscriber * @method delete * @param sid {string} the subscriber id * @param fn {Function} the function to execute * @param when {string} when to execute the function */ Y.Do.Method.prototype._delete = function (sid) { // Y.log('Y.Do._delete: ' + sid, 'info', 'Event'); delete this.before[sid]; delete this.after[sid]; }; /** * Execute the wrapped method * @method exec */ Y.Do.Method.prototype.exec = function () { var args = Y.Array(arguments, 0, true), i, ret, newRet, bf = this.before, af = this.after, prevented = false; // execute before for (i in bf) { if (bf.hasOwnProperty(i)) { ret = bf[i].apply(this.obj, args); if (ret) { switch (ret.constructor) { case Y.Do.Halt: return ret.retVal; case Y.Do.AlterArgs: args = ret.newArgs; break; case Y.Do.Prevent: prevented = true; break; default: } } } } // execute method if (!prevented) { ret = this.method.apply(this.obj, args); } // execute after methods. for (i in af) { if (af.hasOwnProperty(i)) { newRet = af[i].apply(this.obj, args); // Stop processing if a Halt object is returned if (newRet && newRet.constructor == Y.Do.Halt) { return newRet.retVal; // Check for a new return value } else if (newRet && newRet.constructor == Y.Do.AlterReturn) { ret = newRet.newRetVal; } } } return ret; }; ////////////////////////////////////////////////////////////////////////// /** * Return an AlterArgs object when you want to change the arguments that * were passed into the function. An example would be a service that scrubs * out illegal characters prior to executing the core business logic. * @class Do.AlterArgs */ Y.Do.AlterArgs = function(msg, newArgs) { this.msg = msg; this.newArgs = newArgs; }; /** * Return an AlterReturn object when you want to change the result returned * from the core method to the caller * @class Do.AlterReturn */ Y.Do.AlterReturn = function(msg, newRetVal) { this.msg = msg; this.newRetVal = newRetVal; }; /** * Return a Halt object when you want to terminate the execution * of all subsequent subscribers as well as the wrapped method * if it has not exectued yet. * @class Do.Halt */ Y.Do.Halt = function(msg, retVal) { this.msg = msg; this.retVal = retVal; }; /** * Return a Prevent object when you want to prevent the wrapped function * from executing, but want the remaining listeners to execute * @class Do.Prevent */ Y.Do.Prevent = function(msg) { this.msg = msg; }; /** * Return an Error object when you want to terminate the execution * of all subsequent method calls. * @class Do.Error * @deprecated use Y.Do.Halt or Y.Do.Prevent */ Y.Do.Error = Y.Do.Halt; ////////////////////////////////////////////////////////////////////////// // Y["Event"] && Y.Event.addListener(window, "unload", Y.Do._unload, Y.Do); })(); /** * Custom event engine, DOM event listener abstraction layer, synthetic DOM * events. * @module event-custom * @submodule event-custom-base */ /** * Return value from all subscribe operations * @class EventHandle * @constructor * @param evt {CustomEvent} the custom event * @param sub {Subscriber} the subscriber */ // var onsubscribeType = "_event:onsub", var AFTER = 'after', CONFIGS = [ 'broadcast', 'monitored', 'bubbles', 'context', 'contextFn', 'currentTarget', 'defaultFn', 'defaultTargetOnly', 'details', 'emitFacade', 'fireOnce', 'async', 'host', 'preventable', 'preventedFn', 'queuable', 'silent', 'stoppedFn', 'target', 'type' ], YUI3_SIGNATURE = 9, YUI_LOG = 'yui:log'; Y.EventHandle = function(evt, sub) { /** * The custom event * @type CustomEvent */ this.evt = evt; /** * The subscriber object * @type Subscriber */ this.sub = sub; }; Y.EventHandle.prototype = { each: function(f) { f(this); if (Y.Lang.isArray(this.evt)) { Y.Array.each(this.evt, function(h) { h.each(f); }); } }, /** * Detaches this subscriber * @method detach */ detach: function() { var evt = this.evt, detached = 0, i; if (evt) { // Y.log('EventHandle.detach: ' + this.sub, 'info', 'Event'); if (Y.Lang.isArray(evt)) { for (i=0; i<evt.length; i++) { detached += evt[i].detach(); } } else { evt._delete(this.sub); detached = 1; } } return detached; }, /** * Monitor the event state for the subscribed event. The first parameter * is what should be monitored, the rest are the normal parameters when * subscribing to an event. * @method monitor * @param what {string} what to monitor ('attach', 'detach', 'publish') * @return {EventHandle} return value from the monitor event subscription */ monitor: function(what) { return this.evt.monitor.apply(this.evt, arguments); } }; /** * The CustomEvent class lets you define events for your application * that can be subscribed to by one or more independent component. * * @param {String} type The type of event, which is passed to the callback * when the event fires * @param o configuration object * @class CustomEvent * @constructor */ Y.CustomEvent = function(type, o) { // if (arguments.length > 2) { // this.log('CustomEvent context and silent are now in the config', 'warn', 'Event'); // } o = o || {}; this.id = Y.stamp(this); /** * The type of event, returned to subscribers when the event fires * @property type * @type string */ this.type = type; /** * The context the the event will fire from by default. Defaults to the YUI * instance. * @property context * @type object */ this.context = Y; /** * Monitor when an event is attached or detached. * * @property monitored * @type boolean */ // this.monitored = false; this.logSystem = (type == YUI_LOG); /** * If 0, this event does not broadcast. If 1, the YUI instance is notified * every time this event fires. If 2, the YUI instance and the YUI global * (if event is enabled on the global) are notified every time this event * fires. * @property broadcast * @type int */ // this.broadcast = 0; /** * By default all custom events are logged in the debug build, set silent * to true to disable debug outpu for this event. * @property silent * @type boolean */ this.silent = this.logSystem; /** * Specifies whether this event should be queued when the host is actively * processing an event. This will effect exectution order of the callbacks * for the various events. * @property queuable * @type boolean * @default false */ // this.queuable = false; /** * The subscribers to this event * @property subscribers * @type Subscriber{} */ this.subscribers = {}; /** * 'After' subscribers * @property afters * @type Subscriber{} */ this.afters = {}; /** * This event has fired if true * * @property fired * @type boolean * @default false; */ // this.fired = false; /** * An array containing the arguments the custom event * was last fired with. * @property firedWith * @type Array */ // this.firedWith; /** * This event should only fire one time if true, and if * it has fired, any new subscribers should be notified * immediately. * * @property fireOnce * @type boolean * @default false; */ // this.fireOnce = false; /** * fireOnce listeners will fire syncronously unless async * is set to true * @property async * @type boolean * @default false */ //this.async = false; /** * Flag for stopPropagation that is modified during fire() * 1 means to stop propagation to bubble targets. 2 means * to also stop additional subscribers on this target. * @property stopped * @type int */ // this.stopped = 0; /** * Flag for preventDefault that is modified during fire(). * if it is not 0, the default behavior for this event * @property prevented * @type int */ // this.prevented = 0; /** * Specifies the host for this custom event. This is used * to enable event bubbling * @property host * @type EventTarget */ // this.host = null; /** * The default function to execute after event listeners * have fire, but only if the default action was not * prevented. * @property defaultFn * @type Function */ // this.defaultFn = null; /** * The function to execute if a subscriber calls * stopPropagation or stopImmediatePropagation * @property stoppedFn * @type Function */ // this.stoppedFn = null; /** * The function to execute if a subscriber calls * preventDefault * @property preventedFn * @type Function */ // this.preventedFn = null; /** * Specifies whether or not this event's default function * can be cancelled by a subscriber by executing preventDefault() * on the event facade * @property preventable * @type boolean * @default true */ this.preventable = true; /** * Specifies whether or not a subscriber can stop the event propagation * via stopPropagation(), stopImmediatePropagation(), or halt() * * Events can only bubble if emitFacade is true. * * @property bubbles * @type boolean * @default true */ this.bubbles = true; /** * Supports multiple options for listener signatures in order to * port YUI 2 apps. * @property signature * @type int * @default 9 */ this.signature = YUI3_SIGNATURE; this.subCount = 0; this.afterCount = 0; // this.hasSubscribers = false; // this.hasAfters = false; /** * If set to true, the custom event will deliver an EventFacade object * that is similar to a DOM event object. * @property emitFacade * @type boolean * @default false */ // this.emitFacade = false; this.applyConfig(o, true); // this.log("Creating " + this.type); }; Y.CustomEvent.prototype = { hasSubs: function(when) { var s = this.subCount, a = this.afterCount, sib = this.sibling; if (sib) { s += sib.subCount; a += sib.afterCount; } if (when) { return (when == 'after') ? a : s; } return (s + a); }, /** * Monitor the event state for the subscribed event. The first parameter * is what should be monitored, the rest are the normal parameters when * subscribing to an event. * @method monitor * @param what {string} what to monitor ('detach', 'attach', 'publish') * @return {EventHandle} return value from the monitor event subscription */ monitor: function(what) { this.monitored = true; var type = this.id + '|' + this.type + '_' + what, args = Y.Array(arguments, 0, true); args[0] = type; return this.host.on.apply(this.host, args); }, /** * Get all of the subscribers to this event and any sibling event * @return {Array} first item is the on subscribers, second the after */ getSubs: function() { var s = Y.merge(this.subscribers), a = Y.merge(this.afters), sib = this.sibling; if (sib) { Y.mix(s, sib.subscribers); Y.mix(a, sib.afters); } return [s, a]; }, /** * Apply configuration properties. Only applies the CONFIG whitelist * @method applyConfig * @param o hash of properties to apply * @param force {boolean} if true, properties that exist on the event * will be overwritten. */ applyConfig: function(o, force) { if (o) { Y.mix(this, o, force, CONFIGS); } }, _on: function(fn, context, args, when) { if (!fn) { this.log("Invalid callback for CE: " + this.type); } var s = new Y.Subscriber(fn, context, args, when); if (this.fireOnce && this.fired) { if (this.async) { setTimeout(Y.bind(this._notify, this, s, this.firedWith), 0); } else { this._notify(s, this.firedWith); } } if (when == AFTER) { this.afters[s.id] = s; this.afterCount++; } else { this.subscribers[s.id] = s; this.subCount++; } return new Y.EventHandle(this, s); }, /** * Listen for this event * @method subscribe * @param {Function} fn The function to execute * @return {EventHandle} Unsubscribe handle * @deprecated use on */ subscribe: function(fn, context) { Y.log('ce.subscribe deprecated, use "on"', 'warn', 'deprecated'); var a = (arguments.length > 2) ? Y.Array(arguments, 2, true): null; return this._on(fn, context, a, true); }, /** * Listen for this event * @method on * @param {Function} fn The function to execute * @param context {object} optional execution context. * @param arg* {mixed} 0..n additional arguments to supply to the subscriber * when the event fires. * @return {EventHandle} An object with a detach method to detch the handler(s) */ on: function(fn, context) { var a = (arguments.length > 2) ? Y.Array(arguments, 2, true): null; if (this.host) { this.host._monitor('attach', this.type, { args: arguments }); } return this._on(fn, context, a, true); }, /** * Listen for this event after the normal subscribers have been notified and * the default behavior has been applied. If a normal subscriber prevents the * default behavior, it also prevents after listeners from firing. * @method after * @param {Function} fn The function to execute * @param context {object} optional execution context. * @param arg* {mixed} 0..n additional arguments to supply to the subscriber * when the event fires. * @return {EventHandle} handle Unsubscribe handle */ after: function(fn, context) { var a = (arguments.length > 2) ? Y.Array(arguments, 2, true): null; return this._on(fn, context, a, AFTER); }, /** * Detach listeners. * @method detach * @param {Function} fn The subscribed function to remove, if not supplied * all will be removed * @param {Object} context The context object passed to subscribe. * @return {int} returns the number of subscribers unsubscribed */ detach: function(fn, context) { // unsubscribe handle if (fn && fn.detach) { return fn.detach(); } var i, s, found = 0, subs = Y.merge(this.subscribers, this.afters); for (i in subs) { if (subs.hasOwnProperty(i)) { s = subs[i]; if (s && (!fn || fn === s.fn)) { this._delete(s); found++; } } } return found; }, /** * Detach listeners. * @method unsubscribe * @param {Function} fn The subscribed function to remove, if not supplied * all will be removed * @param {Object} context The context object passed to subscribe. * @return {int|undefined} returns the number of subscribers unsubscribed * @deprecated use detach */ unsubscribe: function() { return this.detach.apply(this, arguments); }, /** * Notify a single subscriber * @method _notify * @param s {Subscriber} the subscriber * @param args {Array} the arguments array to apply to the listener * @private */ _notify: function(s, args, ef) { this.log(this.type + "->" + "sub: " + s.id); var ret; ret = s.notify(args, this); if (false === ret || this.stopped > 1) { this.log(this.type + " cancelled by subscriber"); return false; } return true; }, /** * Logger abstraction to centralize the application of the silent flag * @method log * @param msg {string} message to log * @param cat {string} log category */ log: function(msg, cat) { if (!this.silent) { Y.log(this.id + ': ' + msg, cat || "info", "event"); } }, /** * Notifies the subscribers. The callback functions will be executed * from the context specified when the event was created, and with the * following parameters: * <ul> * <li>The type of event</li> * <li>All of the arguments fire() was executed with as an array</li> * <li>The custom object (if any) that was passed into the subscribe() * method</li> * </ul> * @method fire * @param {Object*} arguments an arbitrary set of parameters to pass to * the handler. * @return {boolean} false if one of the subscribers returned false, * true otherwise * */ fire: function() { if (this.fireOnce && this.fired) { this.log('fireOnce event: ' + this.type + ' already fired'); return true; } else { var args = Y.Array(arguments, 0, true); // this doesn't happen if the event isn't published // this.host._monitor('fire', this.type, args); this.fired = true; this.firedWith = args; if (this.emitFacade) { return this.fireComplex(args); } else { return this.fireSimple(args); } } }, fireSimple: function(args) { this.stopped = 0; this.prevented = 0; if (this.hasSubs()) { // this._procSubs(Y.merge(this.subscribers, this.afters), args); var subs = this.getSubs(); this._procSubs(subs[0], args); this._procSubs(subs[1], args); } this._broadcast(args); return this.stopped ? false : true; }, // Requires the event-custom-complex module for full funcitonality. fireComplex: function(args) { Y.log('Missing event-custom-complex needed to emit a facade for: ' + this.type); args[0] = args[0] || {}; return this.fireSimple(args); }, _procSubs: function(subs, args, ef) { var s, i; for (i in subs) { if (subs.hasOwnProperty(i)) { s = subs[i]; if (s && s.fn) { if (false === this._notify(s, args, ef)) { this.stopped = 2; } if (this.stopped == 2) { return false; } } } } return true; }, _broadcast: function(args) { if (!this.stopped && this.broadcast) { var a = Y.Array(args); a.unshift(this.type); if (this.host !== Y) { Y.fire.apply(Y, a); } if (this.broadcast == 2) { Y.Global.fire.apply(Y.Global, a); } } }, /** * Removes all listeners * @method unsubscribeAll * @return {int} The number of listeners unsubscribed * @deprecated use detachAll */ unsubscribeAll: function() { return this.detachAll.apply(this, arguments); }, /** * Removes all listeners * @method detachAll * @return {int} The number of listeners unsubscribed */ detachAll: function() { return this.detach(); }, /** * @method _delete * @param subscriber object * @private */ _delete: function(s) { if (s) { if (this.subscribers[s.id]) { delete this.subscribers[s.id]; this.subCount--; } if (this.afters[s.id]) { delete this.afters[s.id]; this.afterCount--; } } if (this.host) { this.host._monitor('detach', this.type, { ce: this, sub: s }); } if (s) { delete s.fn; delete s.context; } } }; ///////////////////////////////////////////////////////////////////// /** * Stores the subscriber information to be used when the event fires. * @param {Function} fn The wrapped function to execute * @param {Object} context The value of the keyword 'this' in the listener * @param {Array} args* 0..n additional arguments to supply the listener * * @class Subscriber * @constructor */ Y.Subscriber = function(fn, context, args) { /** * The callback that will be execute when the event fires * This is wrapped by Y.rbind if obj was supplied. * @property fn * @type Function */ this.fn = fn; /** * Optional 'this' keyword for the listener * @property context * @type Object */ this.context = context; /** * Unique subscriber id * @property id * @type String */ this.id = Y.stamp(this); /** * Additional arguments to propagate to the subscriber * @property args * @type Array */ this.args = args; /** * Custom events for a given fire transaction. * @property events * @type {EventTarget} */ // this.events = null; /** * This listener only reacts to the event once * @property once */ // this.once = false; }; Y.Subscriber.prototype = { _notify: function(c, args, ce) { var a = this.args, ret; switch (ce.signature) { case 0: ret = this.fn.call(c, ce.type, args, c); break; case 1: ret = this.fn.call(c, args[0] || null, c); break; default: if (a || args) { args = args || []; a = (a) ? args.concat(a) : args; ret = this.fn.apply(c, a); } else { ret = this.fn.call(c); } } if (this.once) { ce._delete(this); } return ret; }, /** * Executes the subscriber. * @method notify * @param args {Array} Arguments array for the subscriber * @param ce {CustomEvent} The custom event that sent the notification */ notify: function(args, ce) { var c = this.context, ret = true; if (!c) { c = (ce.contextFn) ? ce.contextFn() : ce.context; } // only catch errors if we will not re-throw them. if (Y.config.throwFail) { ret = this._notify(c, args, ce); } else { try { ret = this._notify(c, args, ce); } catch(e) { Y.error(this + ' failed: ' + e.message, e); } } return ret; }, /** * Returns true if the fn and obj match this objects properties. * Used by the unsubscribe method to match the right subscriber. * * @method contains * @param {Function} fn the function to execute * @param {Object} context optional 'this' keyword for the listener * @return {boolean} true if the supplied arguments match this * subscriber's signature. */ contains: function(fn, context) { if (context) { return ((this.fn == fn) && this.context == context); } else { return (this.fn == fn); } } }; /** * Custom event engine, DOM event listener abstraction layer, synthetic DOM * events. * @module event-custom * @submodule event-custom-base */ (function() { /** * EventTarget provides the implementation for any object to * publish, subscribe and fire to custom events, and also * alows other EventTargets to target the object with events * sourced from the other object. * EventTarget is designed to be used with Y.augment to wrap * EventCustom in an interface that allows events to be listened to * and fired by name. This makes it possible for implementing code to * subscribe to an event that either has not been created yet, or will * not be created at all. * @class EventTarget * @param opts a configuration object * @config emitFacade {boolean} if true, all events will emit event * facade payloads by default (default false) * @config prefix {string} the prefix to apply to non-prefixed event names * @config chain {boolean} if true, on/after/detach return the host to allow * chaining, otherwise they return an EventHandle (default false) */ var L = Y.Lang, PREFIX_DELIMITER = ':', CATEGORY_DELIMITER = '|', AFTER_PREFIX = '~AFTER~', YArray = Y.Array, _wildType = Y.cached(function(type) { return type.replace(/(.*)(:)(.*)/, "*$2$3"); }), /** * If the instance has a prefix attribute and the * event type is not prefixed, the instance prefix is * applied to the supplied type. * @method _getType * @private */ _getType = Y.cached(function(type, pre) { if (!pre || !L.isString(type) || type.indexOf(PREFIX_DELIMITER) > -1) { return type; } return pre + PREFIX_DELIMITER + type; }), /** * Returns an array with the detach key (if provided), * and the prefixed event name from _getType * Y.on('detachcategory| menu:click', fn) * @method _parseType * @private */ _parseType = Y.cached(function(type, pre) { var t = type, detachcategory, after, i; if (!L.isString(t)) { return t; } i = t.indexOf(AFTER_PREFIX); if (i > -1) { after = true; t = t.substr(AFTER_PREFIX.length); // Y.log(t); } i = t.indexOf(CATEGORY_DELIMITER); if (i > -1) { detachcategory = t.substr(0, (i)); t = t.substr(i+1); if (t == '*') { t = null; } } // detach category, full type with instance prefix, is this an after listener, short type return [detachcategory, (pre) ? _getType(t, pre) : t, after, t]; }), ET = function(opts) { // Y.log('EventTarget constructor executed: ' + this._yuid); var o = (L.isObject(opts)) ? opts : {}; this._yuievt = this._yuievt || { id: Y.guid(), events: {}, targets: {}, config: o, chain: ('chain' in o) ? o.chain : Y.config.chain, bubbling: false, defaults: { context: o.context || this, host: this, emitFacade: o.emitFacade, fireOnce: o.fireOnce, queuable: o.queuable, monitored: o.monitored, broadcast: o.broadcast, defaultTargetOnly: o.defaultTargetOnly, bubbles: ('bubbles' in o) ? o.bubbles : true } }; }; ET.prototype = { /** * Listen to a custom event hosted by this object one time. * This is the equivalent to <code>on</code> except the * listener is immediatelly detached when it is executed. * @method once * @param type {string} The type of the event * @param fn {Function} The callback * @param context {object} optional execution context. * @param arg* {mixed} 0..n additional arguments to supply to the subscriber * @return the event target or a detach handle per 'chain' config */ once: function() { var handle = this.on.apply(this, arguments); handle.each(function(hand) { if (hand.sub) { hand.sub.once = true; } }); return handle; }, /** * Subscribe to a custom event hosted by this object * @method on * @param type {string} The type of the event * @param fn {Function} The callback * @param context {object} optional execution context. * @param arg* {mixed} 0..n additional arguments to supply to the subscriber * @return the event target or a detach handle per 'chain' config */ on: function(type, fn, context) { var parts = _parseType(type, this._yuievt.config.prefix), f, c, args, ret, ce, detachcategory, handle, store = Y.Env.evt.handles, after, adapt, shorttype, Node = Y.Node, n, domevent, isArr; // full name, args, detachcategory, after this._monitor('attach', parts[1], { args: arguments, category: parts[0], after: parts[2] }); if (L.isObject(type)) { if (L.isFunction(type)) { return Y.Do.before.apply(Y.Do, arguments); } f = fn; c = context; args = YArray(arguments, 0, true); ret = []; if (L.isArray(type)) { isArr = true; } after = type._after; delete type._after; Y.each(type, function(v, k) { if (L.isObject(v)) { f = v.fn || ((L.isFunction(v)) ? v : f); c = v.context || c; } var nv = (after) ? AFTER_PREFIX : ''; args[0] = nv + ((isArr) ? v : k); args[1] = f; args[2] = c; ret.push(this.on.apply(this, args)); }, this); return (this._yuievt.chain) ? this : new Y.EventHandle(ret); } detachcategory = parts[0]; after = parts[2]; shorttype = parts[3]; // extra redirection so we catch adaptor events too. take a look at this. if (Node && (this instanceof Node) && (shorttype in Node.DOM_EVENTS)) { args = YArray(arguments, 0, true); args.splice(2, 0, Node.getDOMNode(this)); // Y.log("Node detected, redirecting with these args: " + args); return Y.on.apply(Y, args); } type = parts[1]; if (this instanceof YUI) { adapt = Y.Env.evt.plugins[type]; args = YArray(arguments, 0, true); args[0] = shorttype; if (Node) { n = args[2]; if (n instanceof Y.NodeList) { n = Y.NodeList.getDOMNodes(n); } else if (n instanceof Node) { n = Node.getDOMNode(n); } domevent = (shorttype in Node.DOM_EVENTS); // Captures both DOM events and event plugins. if (domevent) { args[2] = n; } } // check for the existance of an event adaptor if (adapt) { Y.log('Using adaptor for ' + shorttype + ', ' + n, 'info', 'event'); handle = adapt.on.apply(Y, args); } else if ((!type) || domevent) { handle = Y.Event._attach(args); } } if (!handle) { ce = this._yuievt.events[type] || this.publish(type); handle = ce._on(fn, context, (arguments.length > 3) ? YArray(arguments, 3, true) : null, (after) ? 'after' : true); } if (detachcategory) { store[detachcategory] = store[detachcategory] || {}; store[detachcategory][type] = store[detachcategory][type] || []; store[detachcategory][type].push(handle); } return (this._yuievt.chain) ? this : handle; }, /** * subscribe to an event * @method subscribe * @deprecated use on */ subscribe: function() { Y.log('EventTarget subscribe() is deprecated, use on()', 'warn', 'deprecated'); return this.on.apply(this, arguments); }, /** * Detach one or more listeners the from the specified event * @method detach * @param type {string|Object} Either the handle to the subscriber or the * type of event. If the type * is not specified, it will attempt to remove * the listener from all hosted events. * @param fn {Function} The subscribed function to unsubscribe, if not * supplied, all subscribers will be removed. * @param context {Object} The custom object passed to subscribe. This is * optional, but if supplied will be used to * disambiguate multiple listeners that are the same * (e.g., you subscribe many object using a function * that lives on the prototype) * @return {EventTarget} the host */ detach: function(type, fn, context) { var evts = this._yuievt.events, i, Node = Y.Node, isNode = Node && (this instanceof Node); // detachAll disabled on the Y instance. if (!type && (this !== Y)) { for (i in evts) { if (evts.hasOwnProperty(i)) { evts[i].detach(fn, context); } } if (isNode) { Y.Event.purgeElement(Node.getDOMNode(this)); } return this; } var parts = _parseType(type, this._yuievt.config.prefix), detachcategory = L.isArray(parts) ? parts[0] : null, shorttype = (parts) ? parts[3] : null, adapt, store = Y.Env.evt.handles, detachhost, cat, args, ce, keyDetacher = function(lcat, ltype, host) { var handles = lcat[ltype], ce, i; if (handles) { for (i = handles.length - 1; i >= 0; --i) { ce = handles[i].evt; if (ce.host === host || ce.el === host) { handles[i].detach(); } } } }; if (detachcategory) { cat = store[detachcategory]; type = parts[1]; detachhost = (isNode) ? Y.Node.getDOMNode(this) : this; if (cat) { if (type) { keyDetacher(cat, type, detachhost); } else { for (i in cat) { if (cat.hasOwnProperty(i)) { keyDetacher(cat, i, detachhost); } } } return this; } // If this is an event handle, use it to detach } else if (L.isObject(type) && type.detach) { type.detach(); return this; // extra redirection so we catch adaptor events too. take a look at this. } else if (isNode && ((!shorttype) || (shorttype in Node.DOM_EVENTS))) { args = YArray(arguments, 0, true); args[2] = Node.getDOMNode(this); Y.detach.apply(Y, args); return this; } adapt = Y.Env.evt.plugins[shorttype]; // The YUI instance handles DOM events and adaptors if (this instanceof YUI) { args = YArray(arguments, 0, true); // use the adaptor specific detach code if if (adapt && adapt.detach) { adapt.detach.apply(Y, args); return this; // DOM event fork } else if (!type || (!adapt && Node && (type in Node.DOM_EVENTS))) { args[0] = type; Y.Event.detach.apply(Y.Event, args); return this; } } // ce = evts[type]; ce = evts[parts[1]]; if (ce) { ce.detach(fn, context); } return this; }, /** * detach a listener * @method unsubscribe * @deprecated use detach */ unsubscribe: function() { Y.log('EventTarget unsubscribe() is deprecated, use detach()', 'warn', 'deprecated'); return this.detach.apply(this, arguments); }, /** * Removes all listeners from the specified event. If the event type * is not specified, all listeners from all hosted custom events will * be removed. * @method detachAll * @param type {string} The type, or name of the event */ detachAll: function(type) { return this.detach(type); }, /** * Removes all listeners from the specified event. If the event type * is not specified, all listeners from all hosted custom events will * be removed. * @method unsubscribeAll * @param type {string} The type, or name of the event * @deprecated use detachAll */ unsubscribeAll: function() { Y.log('EventTarget unsubscribeAll() is deprecated, use detachAll()', 'warn', 'deprecated'); return this.detachAll.apply(this, arguments); }, /** * Creates a new custom event of the specified type. If a custom event * by that name already exists, it will not be re-created. In either * case the custom event is returned. * * @method publish * * @param type {string} the type, or name of the event * @param opts {object} optional config params. Valid properties are: * * <ul> * <li> * 'broadcast': whether or not the YUI instance and YUI global are notified when the event is fired (false) * </li> * <li> * 'bubbles': whether or not this event bubbles (true) * Events can only bubble if emitFacade is true. * </li> * <li> * 'context': the default execution context for the listeners (this) * </li> * <li> * 'defaultFn': the default function to execute when this event fires if preventDefault was not called * </li> * <li> * 'emitFacade': whether or not this event emits a facade (false) * </li> * <li> * 'prefix': the prefix for this targets events, e.g., 'menu' in 'menu:click' * </li> * <li> * 'fireOnce': if an event is configured to fire once, new subscribers after * the fire will be notified immediately. * </li> * <li> * 'async': fireOnce event listeners will fire synchronously if the event has already * fired unless async is true. * </li> * <li> * 'preventable': whether or not preventDefault() has an effect (true) * </li> * <li> * 'preventedFn': a function that is executed when preventDefault is called * </li> * <li> * 'queuable': whether or not this event can be queued during bubbling (false) * </li> * <li> * 'silent': if silent is true, debug messages are not provided for this event. * </li> * <li> * 'stoppedFn': a function that is executed when stopPropagation is called * </li> * * <li> * 'monitored': specifies whether or not this event should send notifications about * when the event has been attached, detached, or published. * </li> * <li> * 'type': the event type (valid option if not provided as the first parameter to publish) * </li> * </ul> * * @return {CustomEvent} the custom event * */ publish: function(type, opts) { var events, ce, ret, defaults, edata = this._yuievt, pre = edata.config.prefix; type = (pre) ? _getType(type, pre) : type; this._monitor('publish', type, { args: arguments }); if (L.isObject(type)) { ret = {}; Y.each(type, function(v, k) { ret[k] = this.publish(k, v || opts); }, this); return ret; } events = edata.events; ce = events[type]; if (ce) { // ce.log("publish applying new config to published event: '"+type+"' exists", 'info', 'event'); if (opts) { ce.applyConfig(opts, true); } } else { defaults = edata.defaults; // apply defaults ce = new Y.CustomEvent(type, (opts) ? Y.merge(defaults, opts) : defaults); events[type] = ce; } // make sure we turn the broadcast flag off if this // event was published as a result of bubbling // if (opts instanceof Y.CustomEvent) { // events[type].broadcast = false; // } return events[type]; }, /** * This is the entry point for the event monitoring system. * You can monitor 'attach', 'detach', 'fire', and 'publish'. * When configured, these events generate an event. click -> * click_attach, click_detach, click_publish -- these can * be subscribed to like other events to monitor the event * system. Inividual published events can have monitoring * turned on or off (publish can't be turned off before it * it published) by setting the events 'monitor' config. * * @private */ _monitor: function(what, type, o) { var monitorevt, ce = this.getEvent(type); if ((this._yuievt.config.monitored && (!ce || ce.monitored)) || (ce && ce.monitored)) { monitorevt = type + '_' + what; // Y.log('monitoring: ' + monitorevt); o.monitored = what; this.fire.call(this, monitorevt, o); } }, /** * Fire a custom event by name. The callback functions will be executed * from the context specified when the event was created, and with the * following parameters. * * If the custom event object hasn't been created, then the event hasn't * been published and it has no subscribers. For performance sake, we * immediate exit in this case. This means the event won't bubble, so * if the intention is that a bubble target be notified, the event must * be published on this object first. * * The first argument is the event type, and any additional arguments are * passed to the listeners as parameters. If the first of these is an * object literal, and the event is configured to emit an event facade, * that object is mixed into the event facade and the facade is provided * in place of the original object. * * @method fire * @param type {String|Object} The type of the event, or an object that contains * a 'type' property. * @param arguments {Object*} an arbitrary set of parameters to pass to * the handler. If the first of these is an object literal and the event is * configured to emit an event facade, the event facade will replace that * parameter after the properties the object literal contains are copied to * the event facade. * @return {EventTarget} the event host * */ fire: function(type) { var typeIncluded = L.isString(type), t = (typeIncluded) ? type : (type && type.type), ce, ret, pre = this._yuievt.config.prefix, ce2, args = (typeIncluded) ? YArray(arguments, 1, true) : arguments; t = (pre) ? _getType(t, pre) : t; this._monitor('fire', t, { args: args }); ce = this.getEvent(t, true); ce2 = this.getSibling(t, ce); if (ce2 && !ce) { ce = this.publish(t); } // this event has not been published or subscribed to if (!ce) { if (this._yuievt.hasTargets) { return this.bubble({ type: t }, args, this); } // otherwise there is nothing to be done ret = true; } else { ce.sibling = ce2; ret = ce.fire.apply(ce, args); } return (this._yuievt.chain) ? this : ret; }, getSibling: function(type, ce) { var ce2; // delegate to *:type events if there are subscribers if (type.indexOf(PREFIX_DELIMITER) > -1) { type = _wildType(type); // console.log(type); ce2 = this.getEvent(type, true); if (ce2) { // console.log("GOT ONE: " + type); ce2.applyConfig(ce); ce2.bubbles = false; ce2.broadcast = 0; // ret = ce2.fire.apply(ce2, a); } } return ce2; }, /** * Returns the custom event of the provided type has been created, a * falsy value otherwise * @method getEvent * @param type {string} the type, or name of the event * @param prefixed {string} if true, the type is prefixed already * @return {CustomEvent} the custom event or null */ getEvent: function(type, prefixed) { var pre, e; if (!prefixed) { pre = this._yuievt.config.prefix; type = (pre) ? _getType(type, pre) : type; } e = this._yuievt.events; return e[type] || null; }, /** * Subscribe to a custom event hosted by this object. The * supplied callback will execute after any listeners add * via the subscribe method, and after the default function, * if configured for the event, has executed. * @method after * @param type {string} The type of the event * @param fn {Function} The callback * @param context {object} optional execution context. * @param arg* {mixed} 0..n additional arguments to supply to the subscriber * @return the event target or a detach handle per 'chain' config */ after: function(type, fn) { var a = YArray(arguments, 0, true); switch (L.type(type)) { case 'function': return Y.Do.after.apply(Y.Do, arguments); case 'array': // YArray.each(a[0], function(v) { // v = AFTER_PREFIX + v; // }); // break; case 'object': a[0]._after = true; break; default: a[0] = AFTER_PREFIX + type; } return this.on.apply(this, a); }, /** * Executes the callback before a DOM event, custom event * or method. If the first argument is a function, it * is assumed the target is a method. For DOM and custom * events, this is an alias for Y.on. * * For DOM and custom events: * type, callback, context, 0-n arguments * * For methods: * callback, object (method host), methodName, context, 0-n arguments * * @method before * @return detach handle */ before: function() { return this.on.apply(this, arguments); } }; Y.EventTarget = ET; // make Y an event target Y.mix(Y, ET.prototype, false, false, { bubbles: false }); ET.call(Y); YUI.Env.globalEvents = YUI.Env.globalEvents || new ET(); /** * Hosts YUI page level events. This is where events bubble to * when the broadcast config is set to 2. This property is * only available if the custom event module is loaded. * @property Global * @type EventTarget * @for YUI */ Y.Global = YUI.Env.globalEvents; // @TODO implement a global namespace function on Y.Global? })(); /** * <code>YUI</code>'s <code>on</code> method is a unified interface for subscribing to * most events exposed by YUI. This includes custom events, DOM events, and * function events. <code>detach</code> is also provided to remove listeners * serviced by this function. * * The signature that <code>on</code> accepts varies depending on the type * of event being consumed. Refer to the specific methods that will * service a specific request for additional information about subscribing * to that type of event. * * <ul> * <li>Custom events. These events are defined by various * modules in the library. This type of event is delegated to * <code>EventTarget</code>'s <code>on</code> method. * <ul> * <li>The type of the event</li> * <li>The callback to execute</li> * <li>An optional context object</li> * <li>0..n additional arguments to supply the callback.</li> * </ul> * Example: * <code>Y.on('drag:drophit', function() { // start work });</code> * </li> * <li>DOM events. These are moments reported by the browser related * to browser functionality and user interaction. * This type of event is delegated to <code>Event</code>'s * <code>attach</code> method. * <ul> * <li>The type of the event</li> * <li>The callback to execute</li> * <li>The specification for the Node(s) to attach the listener * to. This can be a selector, collections, or Node/Element * refereces.</li> * <li>An optional context object</li> * <li>0..n additional arguments to supply the callback.</li> * </ul> * Example: * <code>Y.on('click', function(e) { // something was clicked }, '#someelement');</code> * </li> * <li>Function events. These events can be used to react before or after a * function is executed. This type of event is delegated to <code>Event.Do</code>'s * <code>before</code> method. * <ul> * <li>The callback to execute</li> * <li>The object that has the function that will be listened for.</li> * <li>The name of the function to listen for.</li> * <li>An optional context object</li> * <li>0..n additional arguments to supply the callback.</li> * </ul> * Example <code>Y.on(function(arg1, arg2, etc) { // obj.methodname was executed }, obj 'methodname');</code> * </li> * </ul> * * <code>on</code> corresponds to the moment before any default behavior of * the event. <code>after</code> works the same way, but these listeners * execute after the event's default behavior. <code>before</code> is an * alias for <code>on</code>. * * @method on * @param type event type (this parameter does not apply for function events) * @param fn the callback * @param context optionally change the value of 'this' in the callback * @param args* 0..n additional arguments to pass to the callback. * @return the event target or a detach handle per 'chain' config * @for YUI */ /** * Listen for an event one time. Equivalent to <code>on</code>, except that * the listener is immediately detached when executed. * @see on * @method once * @param type event type (this parameter does not apply for function events) * @param fn the callback * @param context optionally change the value of 'this' in the callback * @param args* 0..n additional arguments to pass to the callback. * @return the event target or a detach handle per 'chain' config * @for YUI */ /** * after() is a unified interface for subscribing to * most events exposed by YUI. This includes custom events, * DOM events, and AOP events. This works the same way as * the on() function, only it operates after any default * behavior for the event has executed. @see <code>on</code> for more * information. * @method after * @param type event type (this parameter does not apply for function events) * @param fn the callback * @param context optionally change the value of 'this' in the callback * @param args* 0..n additional arguments to pass to the callback. * @return the event target or a detach handle per 'chain' config * @for YUI */ }, '@VERSION@' ,{requires:['oop']});
src/containers/StandalonePostEditor.js
Hylozoic/hylo-redux
import React from 'react' import { prefetch } from 'react-fetcher' import { connect } from 'react-redux' import { capitalize } from 'lodash' import { navigate, fetchCommunity, fetchPost, startPostEdit } from '../actions' import { CREATE_POST, UPDATE_POST } from '../actions/constants' import { getCommunities, getPost } from '../models/post' import { getCommunity } from '../models/community' import { PostEditor, newPostId } from '../components/PostEditor' import { browserHistory } from 'react-router' const { func, object, bool } = React.PropTypes export const editorUrl = (slug, type) => { const start = `${slug ? `/c/${slug}` : '/p'}` const end = `${type ? `/${type}s` : ''}/new` return start + end } @prefetch(({ store, routes, dispatch, params: { id } }) => (routes.slice(-1)[0].community ? dispatch(fetchCommunity(id)) : id && dispatch(fetchPost(id)) .then(() => { const post = getPost(id, store.getState()) return dispatch(startPostEdit(post)) }))) @connect((state, { route, params: { id } }) => { const saving = state.pending[CREATE_POST] || state.pending[UPDATE_POST] if (route.community) { return { postEdit: state.postEdits[newPostId] || {}, community: getCommunity(id, state), saving } } else { const post = getPost(id, state) return { post, postEdit: state.postEdits[id || newPostId], communities: post ? getCommunities(post, state) : null, saving } } }) export default class StandalonePostEditor extends React.Component { static propTypes = { post: object, postEdit: object, dispatch: func, community: object, route: object, saving: bool, params: object } render () { const { post, postEdit, dispatch, community, route: { type }, saving, params: { id } } = this.props const { editor } = this.refs if (!postEdit && id) return <div className='loading'>Loading...</div> const goBack = () => { if (window.history && window.history.length > 2) { browserHistory.goBack() } else { dispatch(navigate(post ? `/p/${post.id}` : '/app')) } } return <div className='standalone-post-editor'> <div id='mobile-top-bar'> {saving ? <a className='right'>Saving...</a> : <a className='right' onClick={() => editor.saveIfValid()}>Create Post</a>} <a className='back' onClick={() => editor.cancel()}> <span className='left-angle-bracket'>&#x3008;</span> Back </a> <div className='title'> {post ? 'Editing' : 'New'} {capitalize(type || 'post')} </div> </div> <PostEditor post={post} community={community} type={type} ref='editor' onCancel={goBack} /> </div> } }
ajax/libs/mediaelement/2.23.1/jquery.js
holtkamp/cdnjs
/*! * jQuery JavaScript Library v1.9.1 * http://jquery.com/ * * Includes Sizzle.js * http://sizzlejs.com/ * * Copyright 2005, 2012 jQuery Foundation, Inc. and other contributors * Released under the MIT license * http://jquery.org/license * * Date: 2013-2-4 */ (function( window, undefined ) { // Can't do this because several apps including ASP.NET trace // the stack via arguments.caller.callee and Firefox dies if // you try to trace through "use strict" call chains. (#13335) // Support: Firefox 18+ //"use strict"; var // The deferred used on DOM ready readyList, // A central reference to the root jQuery(document) rootjQuery, // Support: IE<9 // For `typeof node.method` instead of `node.method !== undefined` core_strundefined = typeof undefined, // Use the correct document accordingly with window argument (sandbox) document = window.document, location = window.location, // Map over jQuery in case of overwrite _jQuery = window.jQuery, // Map over the $ in case of overwrite _$ = window.$, // [[Class]] -> type pairs class2type = {}, // List of deleted data cache ids, so we can reuse them core_deletedIds = [], core_version = "1.9.1", // Save a reference to some core methods core_concat = core_deletedIds.concat, core_push = core_deletedIds.push, core_slice = core_deletedIds.slice, core_indexOf = core_deletedIds.indexOf, core_toString = class2type.toString, core_hasOwn = class2type.hasOwnProperty, core_trim = core_version.trim, // Define a local copy of jQuery jQuery = function( selector, context ) { // The jQuery object is actually just the init constructor 'enhanced' return new jQuery.fn.init( selector, context, rootjQuery ); }, // Used for matching numbers core_pnum = /[+-]?(?:\d*\.|)\d+(?:[eE][+-]?\d+|)/.source, // Used for splitting on whitespace core_rnotwhite = /\S+/g, // Make sure we trim BOM and NBSP (here's looking at you, Safari 5.0 and IE) rtrim = /^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, // A simple way to check for HTML strings // Prioritize #id over <tag> to avoid XSS via location.hash (#9521) // Strict HTML recognition (#11290: must start with <) rquickExpr = /^(?:(<[\w\W]+>)[^>]*|#([\w-]*))$/, // Match a standalone tag rsingleTag = /^<(\w+)\s*\/?>(?:<\/\1>|)$/, // JSON RegExp rvalidchars = /^[\],:{}\s]*$/, rvalidbraces = /(?:^|:|,)(?:\s*\[)+/g, rvalidescape = /\\(?:["\\\/bfnrt]|u[\da-fA-F]{4})/g, rvalidtokens = /"[^"\\\r\n]*"|true|false|null|-?(?:\d+\.|)\d+(?:[eE][+-]?\d+|)/g, // Matches dashed string for camelizing rmsPrefix = /^-ms-/, rdashAlpha = /-([\da-z])/gi, // Used by jQuery.camelCase as callback to replace() fcamelCase = function( all, letter ) { return letter.toUpperCase(); }, // The ready event handler completed = function( event ) { // readyState === "complete" is good enough for us to call the dom ready in oldIE if ( document.addEventListener || event.type === "load" || document.readyState === "complete" ) { detach(); jQuery.ready(); } }, // Clean-up method for dom ready events detach = function() { if ( document.addEventListener ) { document.removeEventListener( "DOMContentLoaded", completed, false ); window.removeEventListener( "load", completed, false ); } else { document.detachEvent( "onreadystatechange", completed ); window.detachEvent( "onload", completed ); } }; jQuery.fn = jQuery.prototype = { // The current version of jQuery being used jquery: core_version, constructor: jQuery, init: function( selector, context, rootjQuery ) { var match, elem; // HANDLE: $(""), $(null), $(undefined), $(false) if ( !selector ) { return this; } // Handle HTML strings if ( typeof selector === "string" ) { if ( selector.charAt(0) === "<" && selector.charAt( selector.length - 1 ) === ">" && selector.length >= 3 ) { // Assume that strings that start and end with <> are HTML and skip the regex check match = [ null, selector, null ]; } else { match = rquickExpr.exec( selector ); } // Match html or make sure no context is specified for #id if ( match && (match[1] || !context) ) { // HANDLE: $(html) -> $(array) if ( match[1] ) { context = context instanceof jQuery ? context[0] : context; // scripts is true for back-compat jQuery.merge( this, jQuery.parseHTML( match[1], context && context.nodeType ? context.ownerDocument || context : document, true ) ); // HANDLE: $(html, props) if ( rsingleTag.test( match[1] ) && jQuery.isPlainObject( context ) ) { for ( match in context ) { // Properties of context are called as methods if possible if ( jQuery.isFunction( this[ match ] ) ) { this[ match ]( context[ match ] ); // ...and otherwise set as attributes } else { this.attr( match, context[ match ] ); } } } return this; // HANDLE: $(#id) } else { elem = document.getElementById( match[2] ); // Check parentNode to catch when Blackberry 4.6 returns // nodes that are no longer in the document #6963 if ( elem && elem.parentNode ) { // Handle the case where IE and Opera return items // by name instead of ID if ( elem.id !== match[2] ) { return rootjQuery.find( selector ); } // Otherwise, we inject the element directly into the jQuery object this.length = 1; this[0] = elem; } this.context = document; this.selector = selector; return this; } // HANDLE: $(expr, $(...)) } else if ( !context || context.jquery ) { return ( context || rootjQuery ).find( selector ); // HANDLE: $(expr, context) // (which is just equivalent to: $(context).find(expr) } else { return this.constructor( context ).find( selector ); } // HANDLE: $(DOMElement) } else if ( selector.nodeType ) { this.context = this[0] = selector; this.length = 1; return this; // HANDLE: $(function) // Shortcut for document ready } else if ( jQuery.isFunction( selector ) ) { return rootjQuery.ready( selector ); } if ( selector.selector !== undefined ) { this.selector = selector.selector; this.context = selector.context; } return jQuery.makeArray( selector, this ); }, // Start with an empty selector selector: "", // The default length of a jQuery object is 0 length: 0, // The number of elements contained in the matched element set size: function() { return this.length; }, toArray: function() { return core_slice.call( this ); }, // Get the Nth element in the matched element set OR // Get the whole matched element set as a clean array get: function( num ) { return num == null ? // Return a 'clean' array this.toArray() : // Return just the object ( num < 0 ? this[ this.length + num ] : this[ num ] ); }, // Take an array of elements and push it onto the stack // (returning the new matched element set) pushStack: function( elems ) { // Build a new jQuery matched element set var ret = jQuery.merge( this.constructor(), elems ); // Add the old object onto the stack (as a reference) ret.prevObject = this; ret.context = this.context; // Return the newly-formed element set return ret; }, // Execute a callback for every element in the matched set. // (You can seed the arguments with an array of args, but this is // only used internally.) each: function( callback, args ) { return jQuery.each( this, callback, args ); }, ready: function( fn ) { // Add the callback jQuery.ready.promise().done( fn ); return this; }, slice: function() { return this.pushStack( core_slice.apply( this, arguments ) ); }, first: function() { return this.eq( 0 ); }, last: function() { return this.eq( -1 ); }, eq: function( i ) { var len = this.length, j = +i + ( i < 0 ? len : 0 ); return this.pushStack( j >= 0 && j < len ? [ this[j] ] : [] ); }, map: function( callback ) { return this.pushStack( jQuery.map(this, function( elem, i ) { return callback.call( elem, i, elem ); })); }, end: function() { return this.prevObject || this.constructor(null); }, // For internal use only. // Behaves like an Array's method, not like a jQuery method. push: core_push, sort: [].sort, splice: [].splice }; // Give the init function the jQuery prototype for later instantiation jQuery.fn.init.prototype = jQuery.fn; jQuery.extend = jQuery.fn.extend = function() { var src, copyIsArray, copy, name, options, clone, target = arguments[0] || {}, i = 1, length = arguments.length, deep = false; // Handle a deep copy situation if ( typeof target === "boolean" ) { deep = target; target = arguments[1] || {}; // skip the boolean and the target i = 2; } // Handle case when target is a string or something (possible in deep copy) if ( typeof target !== "object" && !jQuery.isFunction(target) ) { target = {}; } // extend jQuery itself if only one argument is passed if ( length === i ) { target = this; --i; } for ( ; i < length; i++ ) { // Only deal with non-null/undefined values if ( (options = arguments[ i ]) != null ) { // Extend the base object for ( name in options ) { src = target[ name ]; copy = options[ name ]; // Prevent never-ending loop if ( target === copy ) { continue; } // Recurse if we're merging plain objects or arrays if ( deep && copy && ( jQuery.isPlainObject(copy) || (copyIsArray = jQuery.isArray(copy)) ) ) { if ( copyIsArray ) { copyIsArray = false; clone = src && jQuery.isArray(src) ? src : []; } else { clone = src && jQuery.isPlainObject(src) ? src : {}; } // Never move original objects, clone them target[ name ] = jQuery.extend( deep, clone, copy ); // Don't bring in undefined values } else if ( copy !== undefined ) { target[ name ] = copy; } } } } // Return the modified object return target; }; jQuery.extend({ noConflict: function( deep ) { if ( window.$ === jQuery ) { window.$ = _$; } if ( deep && window.jQuery === jQuery ) { window.jQuery = _jQuery; } return jQuery; }, // Is the DOM ready to be used? Set to true once it occurs. isReady: false, // A counter to track how many items to wait for before // the ready event fires. See #6781 readyWait: 1, // Hold (or release) the ready event holdReady: function( hold ) { if ( hold ) { jQuery.readyWait++; } else { jQuery.ready( true ); } }, // Handle when the DOM is ready ready: function( wait ) { // Abort if there are pending holds or we're already ready if ( wait === true ? --jQuery.readyWait : jQuery.isReady ) { return; } // Make sure body exists, at least, in case IE gets a little overzealous (ticket #5443). if ( !document.body ) { return setTimeout( jQuery.ready ); } // Remember that the DOM is ready jQuery.isReady = true; // If a normal DOM Ready event fired, decrement, and wait if need be if ( wait !== true && --jQuery.readyWait > 0 ) { return; } // If there are functions bound, to execute readyList.resolveWith( document, [ jQuery ] ); // Trigger any bound ready events if ( jQuery.fn.trigger ) { jQuery( document ).trigger("ready").off("ready"); } }, // See test/unit/core.js for details concerning isFunction. // Since version 1.3, DOM methods and functions like alert // aren't supported. They return false on IE (#2968). isFunction: function( obj ) { return jQuery.type(obj) === "function"; }, isArray: Array.isArray || function( obj ) { return jQuery.type(obj) === "array"; }, isWindow: function( obj ) { return obj != null && obj == obj.window; }, isNumeric: function( obj ) { return !isNaN( parseFloat(obj) ) && isFinite( obj ); }, type: function( obj ) { if ( obj == null ) { return String( obj ); } return typeof obj === "object" || typeof obj === "function" ? class2type[ core_toString.call(obj) ] || "object" : typeof obj; }, isPlainObject: function( obj ) { // Must be an Object. // Because of IE, we also have to check the presence of the constructor property. // Make sure that DOM nodes and window objects don't pass through, as well if ( !obj || jQuery.type(obj) !== "object" || obj.nodeType || jQuery.isWindow( obj ) ) { return false; } try { // Not own constructor property must be Object if ( obj.constructor && !core_hasOwn.call(obj, "constructor") && !core_hasOwn.call(obj.constructor.prototype, "isPrototypeOf") ) { return false; } } catch ( e ) { // IE8,9 Will throw exceptions on certain host objects #9897 return false; } // Own properties are enumerated firstly, so to speed up, // if last one is own, then all properties are own. var key; for ( key in obj ) {} return key === undefined || core_hasOwn.call( obj, key ); }, isEmptyObject: function( obj ) { var name; for ( name in obj ) { return false; } return true; }, error: function( msg ) { throw new Error( msg ); }, // data: string of html // context (optional): If specified, the fragment will be created in this context, defaults to document // keepScripts (optional): If true, will include scripts passed in the html string parseHTML: function( data, context, keepScripts ) { if ( !data || typeof data !== "string" ) { return null; } if ( typeof context === "boolean" ) { keepScripts = context; context = false; } context = context || document; var parsed = rsingleTag.exec( data ), scripts = !keepScripts && []; // Single tag if ( parsed ) { return [ context.createElement( parsed[1] ) ]; } parsed = jQuery.buildFragment( [ data ], context, scripts ); if ( scripts ) { jQuery( scripts ).remove(); } return jQuery.merge( [], parsed.childNodes ); }, parseJSON: function( data ) { // Attempt to parse using the native JSON parser first if ( window.JSON && window.JSON.parse ) { return window.JSON.parse( data ); } if ( data === null ) { return data; } if ( typeof data === "string" ) { // Make sure leading/trailing whitespace is removed (IE can't handle it) data = jQuery.trim( data ); if ( data ) { // Make sure the incoming data is actual JSON // Logic borrowed from http://json.org/json2.js if ( rvalidchars.test( data.replace( rvalidescape, "@" ) .replace( rvalidtokens, "]" ) .replace( rvalidbraces, "")) ) { return ( new Function( "return " + data ) )(); } } } jQuery.error( "Invalid JSON: " + data ); }, // Cross-browser xml parsing parseXML: function( data ) { var xml, tmp; if ( !data || typeof data !== "string" ) { return null; } try { if ( window.DOMParser ) { // Standard tmp = new DOMParser(); xml = tmp.parseFromString( data , "text/xml" ); } else { // IE xml = new ActiveXObject( "Microsoft.XMLDOM" ); xml.async = "false"; xml.loadXML( data ); } } catch( e ) { xml = undefined; } if ( !xml || !xml.documentElement || xml.getElementsByTagName( "parsererror" ).length ) { jQuery.error( "Invalid XML: " + data ); } return xml; }, noop: function() {}, // Evaluates a script in a global context // Workarounds based on findings by Jim Driscoll // http://weblogs.java.net/blog/driscoll/archive/2009/09/08/eval-javascript-global-context globalEval: function( data ) { if ( data && jQuery.trim( data ) ) { // We use execScript on Internet Explorer // We use an anonymous function so that context is window // rather than jQuery in Firefox ( window.execScript || function( data ) { window[ "eval" ].call( window, data ); } )( data ); } }, // Convert dashed to camelCase; used by the css and data modules // Microsoft forgot to hump their vendor prefix (#9572) camelCase: function( string ) { return string.replace( rmsPrefix, "ms-" ).replace( rdashAlpha, fcamelCase ); }, nodeName: function( elem, name ) { return elem.nodeName && elem.nodeName.toLowerCase() === name.toLowerCase(); }, // args is for internal usage only each: function( obj, callback, args ) { var value, i = 0, length = obj.length, isArray = isArraylike( obj ); if ( args ) { if ( isArray ) { for ( ; i < length; i++ ) { value = callback.apply( obj[ i ], args ); if ( value === false ) { break; } } } else { for ( i in obj ) { value = callback.apply( obj[ i ], args ); if ( value === false ) { break; } } } // A special, fast, case for the most common use of each } else { if ( isArray ) { for ( ; i < length; i++ ) { value = callback.call( obj[ i ], i, obj[ i ] ); if ( value === false ) { break; } } } else { for ( i in obj ) { value = callback.call( obj[ i ], i, obj[ i ] ); if ( value === false ) { break; } } } } return obj; }, // Use native String.trim function wherever possible trim: core_trim && !core_trim.call("\uFEFF\xA0") ? function( text ) { return text == null ? "" : core_trim.call( text ); } : // Otherwise use our own trimming functionality function( text ) { return text == null ? "" : ( text + "" ).replace( rtrim, "" ); }, // results is for internal usage only makeArray: function( arr, results ) { var ret = results || []; if ( arr != null ) { if ( isArraylike( Object(arr) ) ) { jQuery.merge( ret, typeof arr === "string" ? [ arr ] : arr ); } else { core_push.call( ret, arr ); } } return ret; }, inArray: function( elem, arr, i ) { var len; if ( arr ) { if ( core_indexOf ) { return core_indexOf.call( arr, elem, i ); } len = arr.length; i = i ? i < 0 ? Math.max( 0, len + i ) : i : 0; for ( ; i < len; i++ ) { // Skip accessing in sparse arrays if ( i in arr && arr[ i ] === elem ) { return i; } } } return -1; }, merge: function( first, second ) { var l = second.length, i = first.length, j = 0; if ( typeof l === "number" ) { for ( ; j < l; j++ ) { first[ i++ ] = second[ j ]; } } else { while ( second[j] !== undefined ) { first[ i++ ] = second[ j++ ]; } } first.length = i; return first; }, grep: function( elems, callback, inv ) { var retVal, ret = [], i = 0, length = elems.length; inv = !!inv; // Go through the array, only saving the items // that pass the validator function for ( ; i < length; i++ ) { retVal = !!callback( elems[ i ], i ); if ( inv !== retVal ) { ret.push( elems[ i ] ); } } return ret; }, // arg is for internal usage only map: function( elems, callback, arg ) { var value, i = 0, length = elems.length, isArray = isArraylike( elems ), ret = []; // Go through the array, translating each of the items to their if ( isArray ) { for ( ; i < length; i++ ) { value = callback( elems[ i ], i, arg ); if ( value != null ) { ret[ ret.length ] = value; } } // Go through every key on the object, } else { for ( i in elems ) { value = callback( elems[ i ], i, arg ); if ( value != null ) { ret[ ret.length ] = value; } } } // Flatten any nested arrays return core_concat.apply( [], ret ); }, // A global GUID counter for objects guid: 1, // Bind a function to a context, optionally partially applying any // arguments. proxy: function( fn, context ) { var args, proxy, tmp; if ( typeof context === "string" ) { tmp = fn[ context ]; context = fn; fn = tmp; } // Quick check to determine if target is callable, in the spec // this throws a TypeError, but we will just return undefined. if ( !jQuery.isFunction( fn ) ) { return undefined; } // Simulated bind args = core_slice.call( arguments, 2 ); proxy = function() { return fn.apply( context || this, args.concat( core_slice.call( arguments ) ) ); }; // Set the guid of unique handler to the same of original handler, so it can be removed proxy.guid = fn.guid = fn.guid || jQuery.guid++; return proxy; }, // Multifunctional method to get and set values of a collection // The value/s can optionally be executed if it's a function access: function( elems, fn, key, value, chainable, emptyGet, raw ) { var i = 0, length = elems.length, bulk = key == null; // Sets many values if ( jQuery.type( key ) === "object" ) { chainable = true; for ( i in key ) { jQuery.access( elems, fn, i, key[i], true, emptyGet, raw ); } // Sets one value } else if ( value !== undefined ) { chainable = true; if ( !jQuery.isFunction( value ) ) { raw = true; } if ( bulk ) { // Bulk operations run against the entire set if ( raw ) { fn.call( elems, value ); fn = null; // ...except when executing function values } else { bulk = fn; fn = function( elem, key, value ) { return bulk.call( jQuery( elem ), value ); }; } } if ( fn ) { for ( ; i < length; i++ ) { fn( elems[i], key, raw ? value : value.call( elems[i], i, fn( elems[i], key ) ) ); } } } return chainable ? elems : // Gets bulk ? fn.call( elems ) : length ? fn( elems[0], key ) : emptyGet; }, now: function() { return ( new Date() ).getTime(); } }); jQuery.ready.promise = function( obj ) { if ( !readyList ) { readyList = jQuery.Deferred(); // Catch cases where $(document).ready() is called after the browser event has already occurred. // we once tried to use readyState "interactive" here, but it caused issues like the one // discovered by ChrisS here: http://bugs.jquery.com/ticket/12282#comment:15 if ( document.readyState === "complete" ) { // Handle it asynchronously to allow scripts the opportunity to delay ready setTimeout( jQuery.ready ); // Standards-based browsers support DOMContentLoaded } else if ( document.addEventListener ) { // Use the handy event callback document.addEventListener( "DOMContentLoaded", completed, false ); // A fallback to window.onload, that will always work window.addEventListener( "load", completed, false ); // If IE event model is used } else { // Ensure firing before onload, maybe late but safe also for iframes document.attachEvent( "onreadystatechange", completed ); // A fallback to window.onload, that will always work window.attachEvent( "onload", completed ); // If IE and not a frame // continually check to see if the document is ready var top = false; try { top = window.frameElement == null && document.documentElement; } catch(e) {} if ( top && top.doScroll ) { (function doScrollCheck() { if ( !jQuery.isReady ) { try { // Use the trick by Diego Perini // http://javascript.nwbox.com/IEContentLoaded/ top.doScroll("left"); } catch(e) { return setTimeout( doScrollCheck, 50 ); } // detach all dom ready events detach(); // and execute any waiting functions jQuery.ready(); } })(); } } } return readyList.promise( obj ); }; // Populate the class2type map jQuery.each("Boolean Number String Function Array Date RegExp Object Error".split(" "), function(i, name) { class2type[ "[object " + name + "]" ] = name.toLowerCase(); }); function isArraylike( obj ) { var length = obj.length, type = jQuery.type( obj ); if ( jQuery.isWindow( obj ) ) { return false; } if ( obj.nodeType === 1 && length ) { return true; } return type === "array" || type !== "function" && ( length === 0 || typeof length === "number" && length > 0 && ( length - 1 ) in obj ); } // All jQuery objects should point back to these rootjQuery = jQuery(document); // String to Object options format cache var optionsCache = {}; // Convert String-formatted options into Object-formatted ones and store in cache function createOptions( options ) { var object = optionsCache[ options ] = {}; jQuery.each( options.match( core_rnotwhite ) || [], function( _, flag ) { object[ flag ] = true; }); return object; } /* * Create a callback list using the following parameters: * * options: an optional list of space-separated options that will change how * the callback list behaves or a more traditional option object * * By default a callback list will act like an event callback list and can be * "fired" multiple times. * * Possible options: * * once: will ensure the callback list can only be fired once (like a Deferred) * * memory: will keep track of previous values and will call any callback added * after the list has been fired right away with the latest "memorized" * values (like a Deferred) * * unique: will ensure a callback can only be added once (no duplicate in the list) * * stopOnFalse: interrupt callings when a callback returns false * */ jQuery.Callbacks = function( options ) { // Convert options from String-formatted to Object-formatted if needed // (we check in cache first) options = typeof options === "string" ? ( optionsCache[ options ] || createOptions( options ) ) : jQuery.extend( {}, options ); var // Flag to know if list is currently firing firing, // Last fire value (for non-forgettable lists) memory, // Flag to know if list was already fired fired, // End of the loop when firing firingLength, // Index of currently firing callback (modified by remove if needed) firingIndex, // First callback to fire (used internally by add and fireWith) firingStart, // Actual callback list list = [], // Stack of fire calls for repeatable lists stack = !options.once && [], // Fire callbacks fire = function( data ) { memory = options.memory && data; fired = true; firingIndex = firingStart || 0; firingStart = 0; firingLength = list.length; firing = true; for ( ; list && firingIndex < firingLength; firingIndex++ ) { if ( list[ firingIndex ].apply( data[ 0 ], data[ 1 ] ) === false && options.stopOnFalse ) { memory = false; // To prevent further calls using add break; } } firing = false; if ( list ) { if ( stack ) { if ( stack.length ) { fire( stack.shift() ); } } else if ( memory ) { list = []; } else { self.disable(); } } }, // Actual Callbacks object self = { // Add a callback or a collection of callbacks to the list add: function() { if ( list ) { // First, we save the current length var start = list.length; (function add( args ) { jQuery.each( args, function( _, arg ) { var type = jQuery.type( arg ); if ( type === "function" ) { if ( !options.unique || !self.has( arg ) ) { list.push( arg ); } } else if ( arg && arg.length && type !== "string" ) { // Inspect recursively add( arg ); } }); })( arguments ); // Do we need to add the callbacks to the // current firing batch? if ( firing ) { firingLength = list.length; // With memory, if we're not firing then // we should call right away } else if ( memory ) { firingStart = start; fire( memory ); } } return this; }, // Remove a callback from the list remove: function() { if ( list ) { jQuery.each( arguments, function( _, arg ) { var index; while( ( index = jQuery.inArray( arg, list, index ) ) > -1 ) { list.splice( index, 1 ); // Handle firing indexes if ( firing ) { if ( index <= firingLength ) { firingLength--; } if ( index <= firingIndex ) { firingIndex--; } } } }); } return this; }, // Check if a given callback is in the list. // If no argument is given, return whether or not list has callbacks attached. has: function( fn ) { return fn ? jQuery.inArray( fn, list ) > -1 : !!( list && list.length ); }, // Remove all callbacks from the list empty: function() { list = []; return this; }, // Have the list do nothing anymore disable: function() { list = stack = memory = undefined; return this; }, // Is it disabled? disabled: function() { return !list; }, // Lock the list in its current state lock: function() { stack = undefined; if ( !memory ) { self.disable(); } return this; }, // Is it locked? locked: function() { return !stack; }, // Call all callbacks with the given context and arguments fireWith: function( context, args ) { args = args || []; args = [ context, args.slice ? args.slice() : args ]; if ( list && ( !fired || stack ) ) { if ( firing ) { stack.push( args ); } else { fire( args ); } } return this; }, // Call all the callbacks with the given arguments fire: function() { self.fireWith( this, arguments ); return this; }, // To know if the callbacks have already been called at least once fired: function() { return !!fired; } }; return self; }; jQuery.extend({ Deferred: function( func ) { var tuples = [ // action, add listener, listener list, final state [ "resolve", "done", jQuery.Callbacks("once memory"), "resolved" ], [ "reject", "fail", jQuery.Callbacks("once memory"), "rejected" ], [ "notify", "progress", jQuery.Callbacks("memory") ] ], state = "pending", promise = { state: function() { return state; }, always: function() { deferred.done( arguments ).fail( arguments ); return this; }, then: function( /* fnDone, fnFail, fnProgress */ ) { var fns = arguments; return jQuery.Deferred(function( newDefer ) { jQuery.each( tuples, function( i, tuple ) { var action = tuple[ 0 ], fn = jQuery.isFunction( fns[ i ] ) && fns[ i ]; // deferred[ done | fail | progress ] for forwarding actions to newDefer deferred[ tuple[1] ](function() { var returned = fn && fn.apply( this, arguments ); if ( returned && jQuery.isFunction( returned.promise ) ) { returned.promise() .done( newDefer.resolve ) .fail( newDefer.reject ) .progress( newDefer.notify ); } else { newDefer[ action + "With" ]( this === promise ? newDefer.promise() : this, fn ? [ returned ] : arguments ); } }); }); fns = null; }).promise(); }, // Get a promise for this deferred // If obj is provided, the promise aspect is added to the object promise: function( obj ) { return obj != null ? jQuery.extend( obj, promise ) : promise; } }, deferred = {}; // Keep pipe for back-compat promise.pipe = promise.then; // Add list-specific methods jQuery.each( tuples, function( i, tuple ) { var list = tuple[ 2 ], stateString = tuple[ 3 ]; // promise[ done | fail | progress ] = list.add promise[ tuple[1] ] = list.add; // Handle state if ( stateString ) { list.add(function() { // state = [ resolved | rejected ] state = stateString; // [ reject_list | resolve_list ].disable; progress_list.lock }, tuples[ i ^ 1 ][ 2 ].disable, tuples[ 2 ][ 2 ].lock ); } // deferred[ resolve | reject | notify ] deferred[ tuple[0] ] = function() { deferred[ tuple[0] + "With" ]( this === deferred ? promise : this, arguments ); return this; }; deferred[ tuple[0] + "With" ] = list.fireWith; }); // Make the deferred a promise promise.promise( deferred ); // Call given func if any if ( func ) { func.call( deferred, deferred ); } // All done! return deferred; }, // Deferred helper when: function( subordinate /* , ..., subordinateN */ ) { var i = 0, resolveValues = core_slice.call( arguments ), length = resolveValues.length, // the count of uncompleted subordinates remaining = length !== 1 || ( subordinate && jQuery.isFunction( subordinate.promise ) ) ? length : 0, // the master Deferred. If resolveValues consist of only a single Deferred, just use that. deferred = remaining === 1 ? subordinate : jQuery.Deferred(), // Update function for both resolve and progress values updateFunc = function( i, contexts, values ) { return function( value ) { contexts[ i ] = this; values[ i ] = arguments.length > 1 ? core_slice.call( arguments ) : value; if( values === progressValues ) { deferred.notifyWith( contexts, values ); } else if ( !( --remaining ) ) { deferred.resolveWith( contexts, values ); } }; }, progressValues, progressContexts, resolveContexts; // add listeners to Deferred subordinates; treat others as resolved if ( length > 1 ) { progressValues = new Array( length ); progressContexts = new Array( length ); resolveContexts = new Array( length ); for ( ; i < length; i++ ) { if ( resolveValues[ i ] && jQuery.isFunction( resolveValues[ i ].promise ) ) { resolveValues[ i ].promise() .done( updateFunc( i, resolveContexts, resolveValues ) ) .fail( deferred.reject ) .progress( updateFunc( i, progressContexts, progressValues ) ); } else { --remaining; } } } // if we're not waiting on anything, resolve the master if ( !remaining ) { deferred.resolveWith( resolveContexts, resolveValues ); } return deferred.promise(); } }); jQuery.support = (function() { var support, all, a, input, select, fragment, opt, eventName, isSupported, i, div = document.createElement("div"); // Setup div.setAttribute( "className", "t" ); div.innerHTML = " <link/><table></table><a href='/a'>a</a><input type='checkbox'/>"; // Support tests won't run in some limited or non-browser environments all = div.getElementsByTagName("*"); a = div.getElementsByTagName("a")[ 0 ]; if ( !all || !a || !all.length ) { return {}; } // First batch of tests select = document.createElement("select"); opt = select.appendChild( document.createElement("option") ); input = div.getElementsByTagName("input")[ 0 ]; a.style.cssText = "top:1px;float:left;opacity:.5"; support = { // Test setAttribute on camelCase class. If it works, we need attrFixes when doing get/setAttribute (ie6/7) getSetAttribute: div.className !== "t", // IE strips leading whitespace when .innerHTML is used leadingWhitespace: div.firstChild.nodeType === 3, // Make sure that tbody elements aren't automatically inserted // IE will insert them into empty tables tbody: !div.getElementsByTagName("tbody").length, // Make sure that link elements get serialized correctly by innerHTML // This requires a wrapper element in IE htmlSerialize: !!div.getElementsByTagName("link").length, // Get the style information from getAttribute // (IE uses .cssText instead) style: /top/.test( a.getAttribute("style") ), // Make sure that URLs aren't manipulated // (IE normalizes it by default) hrefNormalized: a.getAttribute("href") === "/a", // Make sure that element opacity exists // (IE uses filter instead) // Use a regex to work around a WebKit issue. See #5145 opacity: /^0.5/.test( a.style.opacity ), // Verify style float existence // (IE uses styleFloat instead of cssFloat) cssFloat: !!a.style.cssFloat, // Check the default checkbox/radio value ("" on WebKit; "on" elsewhere) checkOn: !!input.value, // Make sure that a selected-by-default option has a working selected property. // (WebKit defaults to false instead of true, IE too, if it's in an optgroup) optSelected: opt.selected, // Tests for enctype support on a form (#6743) enctype: !!document.createElement("form").enctype, // Makes sure cloning an html5 element does not cause problems // Where outerHTML is undefined, this still works html5Clone: document.createElement("nav").cloneNode( true ).outerHTML !== "<:nav></:nav>", // jQuery.support.boxModel DEPRECATED in 1.8 since we don't support Quirks Mode boxModel: document.compatMode === "CSS1Compat", // Will be defined later deleteExpando: true, noCloneEvent: true, inlineBlockNeedsLayout: false, shrinkWrapBlocks: false, reliableMarginRight: true, boxSizingReliable: true, pixelPosition: false }; // Make sure checked status is properly cloned input.checked = true; support.noCloneChecked = input.cloneNode( true ).checked; // Make sure that the options inside disabled selects aren't marked as disabled // (WebKit marks them as disabled) select.disabled = true; support.optDisabled = !opt.disabled; // Support: IE<9 try { delete div.test; } catch( e ) { support.deleteExpando = false; } // Check if we can trust getAttribute("value") input = document.createElement("input"); input.setAttribute( "value", "" ); support.input = input.getAttribute( "value" ) === ""; // Check if an input maintains its value after becoming a radio input.value = "t"; input.setAttribute( "type", "radio" ); support.radioValue = input.value === "t"; // #11217 - WebKit loses check when the name is after the checked attribute input.setAttribute( "checked", "t" ); input.setAttribute( "name", "t" ); fragment = document.createDocumentFragment(); fragment.appendChild( input ); // Check if a disconnected checkbox will retain its checked // value of true after appended to the DOM (IE6/7) support.appendChecked = input.checked; // WebKit doesn't clone checked state correctly in fragments support.checkClone = fragment.cloneNode( true ).cloneNode( true ).lastChild.checked; // Support: IE<9 // Opera does not clone events (and typeof div.attachEvent === undefined). // IE9-10 clones events bound via attachEvent, but they don't trigger with .click() if ( div.attachEvent ) { div.attachEvent( "onclick", function() { support.noCloneEvent = false; }); div.cloneNode( true ).click(); } // Support: IE<9 (lack submit/change bubble), Firefox 17+ (lack focusin event) // Beware of CSP restrictions (https://developer.mozilla.org/en/Security/CSP), test/csp.php for ( i in { submit: true, change: true, focusin: true }) { div.setAttribute( eventName = "on" + i, "t" ); support[ i + "Bubbles" ] = eventName in window || div.attributes[ eventName ].expando === false; } div.style.backgroundClip = "content-box"; div.cloneNode( true ).style.backgroundClip = ""; support.clearCloneStyle = div.style.backgroundClip === "content-box"; // Run tests that need a body at doc ready jQuery(function() { var container, marginDiv, tds, divReset = "padding:0;margin:0;border:0;display:block;box-sizing:content-box;-moz-box-sizing:content-box;-webkit-box-sizing:content-box;", body = document.getElementsByTagName("body")[0]; if ( !body ) { // Return for frameset docs that don't have a body return; } container = document.createElement("div"); container.style.cssText = "border:0;width:0;height:0;position:absolute;top:0;left:-9999px;margin-top:1px"; body.appendChild( container ).appendChild( div ); // Support: IE8 // Check if table cells still have offsetWidth/Height when they are set // to display:none and there are still other visible table cells in a // table row; if so, offsetWidth/Height are not reliable for use when // determining if an element has been hidden directly using // display:none (it is still safe to use offsets if a parent element is // hidden; don safety goggles and see bug #4512 for more information). div.innerHTML = "<table><tr><td></td><td>t</td></tr></table>"; tds = div.getElementsByTagName("td"); tds[ 0 ].style.cssText = "padding:0;margin:0;border:0;display:none"; isSupported = ( tds[ 0 ].offsetHeight === 0 ); tds[ 0 ].style.display = ""; tds[ 1 ].style.display = "none"; // Support: IE8 // Check if empty table cells still have offsetWidth/Height support.reliableHiddenOffsets = isSupported && ( tds[ 0 ].offsetHeight === 0 ); // Check box-sizing and margin behavior div.innerHTML = ""; div.style.cssText = "box-sizing:border-box;-moz-box-sizing:border-box;-webkit-box-sizing:border-box;padding:1px;border:1px;display:block;width:4px;margin-top:1%;position:absolute;top:1%;"; support.boxSizing = ( div.offsetWidth === 4 ); support.doesNotIncludeMarginInBodyOffset = ( body.offsetTop !== 1 ); // Use window.getComputedStyle because jsdom on node.js will break without it. if ( window.getComputedStyle ) { support.pixelPosition = ( window.getComputedStyle( div, null ) || {} ).top !== "1%"; support.boxSizingReliable = ( window.getComputedStyle( div, null ) || { width: "4px" } ).width === "4px"; // Check if div with explicit width and no margin-right incorrectly // gets computed margin-right based on width of container. (#3333) // Fails in WebKit before Feb 2011 nightlies // WebKit Bug 13343 - getComputedStyle returns wrong value for margin-right marginDiv = div.appendChild( document.createElement("div") ); marginDiv.style.cssText = div.style.cssText = divReset; marginDiv.style.marginRight = marginDiv.style.width = "0"; div.style.width = "1px"; support.reliableMarginRight = !parseFloat( ( window.getComputedStyle( marginDiv, null ) || {} ).marginRight ); } if ( typeof div.style.zoom !== core_strundefined ) { // Support: IE<8 // Check if natively block-level elements act like inline-block // elements when setting their display to 'inline' and giving // them layout div.innerHTML = ""; div.style.cssText = divReset + "width:1px;padding:1px;display:inline;zoom:1"; support.inlineBlockNeedsLayout = ( div.offsetWidth === 3 ); // Support: IE6 // Check if elements with layout shrink-wrap their children div.style.display = "block"; div.innerHTML = "<div></div>"; div.firstChild.style.width = "5px"; support.shrinkWrapBlocks = ( div.offsetWidth !== 3 ); if ( support.inlineBlockNeedsLayout ) { // Prevent IE 6 from affecting layout for positioned elements #11048 // Prevent IE from shrinking the body in IE 7 mode #12869 // Support: IE<8 body.style.zoom = 1; } } body.removeChild( container ); // Null elements to avoid leaks in IE container = div = tds = marginDiv = null; }); // Null elements to avoid leaks in IE all = select = fragment = opt = a = input = null; return support; })(); var rbrace = /(?:\{[\s\S]*\}|\[[\s\S]*\])$/, rmultiDash = /([A-Z])/g; function internalData( elem, name, data, pvt /* Internal Use Only */ ){ if ( !jQuery.acceptData( elem ) ) { return; } var thisCache, ret, internalKey = jQuery.expando, getByName = typeof name === "string", // We have to handle DOM nodes and JS objects differently because IE6-7 // can't GC object references properly across the DOM-JS boundary isNode = elem.nodeType, // Only DOM nodes need the global jQuery cache; JS object data is // attached directly to the object so GC can occur automatically cache = isNode ? jQuery.cache : elem, // Only defining an ID for JS objects if its cache already exists allows // the code to shortcut on the same path as a DOM node with no cache id = isNode ? elem[ internalKey ] : elem[ internalKey ] && internalKey; // Avoid doing any more work than we need to when trying to get data on an // object that has no data at all if ( (!id || !cache[id] || (!pvt && !cache[id].data)) && getByName && data === undefined ) { return; } if ( !id ) { // Only DOM nodes need a new unique ID for each element since their data // ends up in the global cache if ( isNode ) { elem[ internalKey ] = id = core_deletedIds.pop() || jQuery.guid++; } else { id = internalKey; } } if ( !cache[ id ] ) { cache[ id ] = {}; // Avoids exposing jQuery metadata on plain JS objects when the object // is serialized using JSON.stringify if ( !isNode ) { cache[ id ].toJSON = jQuery.noop; } } // An object can be passed to jQuery.data instead of a key/value pair; this gets // shallow copied over onto the existing cache if ( typeof name === "object" || typeof name === "function" ) { if ( pvt ) { cache[ id ] = jQuery.extend( cache[ id ], name ); } else { cache[ id ].data = jQuery.extend( cache[ id ].data, name ); } } thisCache = cache[ id ]; // jQuery data() is stored in a separate object inside the object's internal data // cache in order to avoid key collisions between internal data and user-defined // data. if ( !pvt ) { if ( !thisCache.data ) { thisCache.data = {}; } thisCache = thisCache.data; } if ( data !== undefined ) { thisCache[ jQuery.camelCase( name ) ] = data; } // Check for both converted-to-camel and non-converted data property names // If a data property was specified if ( getByName ) { // First Try to find as-is property data ret = thisCache[ name ]; // Test for null|undefined property data if ( ret == null ) { // Try to find the camelCased property ret = thisCache[ jQuery.camelCase( name ) ]; } } else { ret = thisCache; } return ret; } function internalRemoveData( elem, name, pvt ) { if ( !jQuery.acceptData( elem ) ) { return; } var i, l, thisCache, isNode = elem.nodeType, // See jQuery.data for more information cache = isNode ? jQuery.cache : elem, id = isNode ? elem[ jQuery.expando ] : jQuery.expando; // If there is already no cache entry for this object, there is no // purpose in continuing if ( !cache[ id ] ) { return; } if ( name ) { thisCache = pvt ? cache[ id ] : cache[ id ].data; if ( thisCache ) { // Support array or space separated string names for data keys if ( !jQuery.isArray( name ) ) { // try the string as a key before any manipulation if ( name in thisCache ) { name = [ name ]; } else { // split the camel cased version by spaces unless a key with the spaces exists name = jQuery.camelCase( name ); if ( name in thisCache ) { name = [ name ]; } else { name = name.split(" "); } } } else { // If "name" is an array of keys... // When data is initially created, via ("key", "val") signature, // keys will be converted to camelCase. // Since there is no way to tell _how_ a key was added, remove // both plain key and camelCase key. #12786 // This will only penalize the array argument path. name = name.concat( jQuery.map( name, jQuery.camelCase ) ); } for ( i = 0, l = name.length; i < l; i++ ) { delete thisCache[ name[i] ]; } // If there is no data left in the cache, we want to continue // and let the cache object itself get destroyed if ( !( pvt ? isEmptyDataObject : jQuery.isEmptyObject )( thisCache ) ) { return; } } } // See jQuery.data for more information if ( !pvt ) { delete cache[ id ].data; // Don't destroy the parent cache unless the internal data object // had been the only thing left in it if ( !isEmptyDataObject( cache[ id ] ) ) { return; } } // Destroy the cache if ( isNode ) { jQuery.cleanData( [ elem ], true ); // Use delete when supported for expandos or `cache` is not a window per isWindow (#10080) } else if ( jQuery.support.deleteExpando || cache != cache.window ) { delete cache[ id ]; // When all else fails, null } else { cache[ id ] = null; } } jQuery.extend({ cache: {}, // Unique for each copy of jQuery on the page // Non-digits removed to match rinlinejQuery expando: "jQuery" + ( core_version + Math.random() ).replace( /\D/g, "" ), // The following elements throw uncatchable exceptions if you // attempt to add expando properties to them. noData: { "embed": true, // Ban all objects except for Flash (which handle expandos) "object": "clsid:D27CDB6E-AE6D-11cf-96B8-444553540000", "applet": true }, hasData: function( elem ) { elem = elem.nodeType ? jQuery.cache[ elem[jQuery.expando] ] : elem[ jQuery.expando ]; return !!elem && !isEmptyDataObject( elem ); }, data: function( elem, name, data ) { return internalData( elem, name, data ); }, removeData: function( elem, name ) { return internalRemoveData( elem, name ); }, // For internal use only. _data: function( elem, name, data ) { return internalData( elem, name, data, true ); }, _removeData: function( elem, name ) { return internalRemoveData( elem, name, true ); }, // A method for determining if a DOM node can handle the data expando acceptData: function( elem ) { // Do not set data on non-element because it will not be cleared (#8335). if ( elem.nodeType && elem.nodeType !== 1 && elem.nodeType !== 9 ) { return false; } var noData = elem.nodeName && jQuery.noData[ elem.nodeName.toLowerCase() ]; // nodes accept data unless otherwise specified; rejection can be conditional return !noData || noData !== true && elem.getAttribute("classid") === noData; } }); jQuery.fn.extend({ data: function( key, value ) { var attrs, name, elem = this[0], i = 0, data = null; // Gets all values if ( key === undefined ) { if ( this.length ) { data = jQuery.data( elem ); if ( elem.nodeType === 1 && !jQuery._data( elem, "parsedAttrs" ) ) { attrs = elem.attributes; for ( ; i < attrs.length; i++ ) { name = attrs[i].name; if ( !name.indexOf( "data-" ) ) { name = jQuery.camelCase( name.slice(5) ); dataAttr( elem, name, data[ name ] ); } } jQuery._data( elem, "parsedAttrs", true ); } } return data; } // Sets multiple values if ( typeof key === "object" ) { return this.each(function() { jQuery.data( this, key ); }); } return jQuery.access( this, function( value ) { if ( value === undefined ) { // Try to fetch any internally stored data first return elem ? dataAttr( elem, key, jQuery.data( elem, key ) ) : null; } this.each(function() { jQuery.data( this, key, value ); }); }, null, value, arguments.length > 1, null, true ); }, removeData: function( key ) { return this.each(function() { jQuery.removeData( this, key ); }); } }); function dataAttr( elem, key, data ) { // If nothing was found internally, try to fetch any // data from the HTML5 data-* attribute if ( data === undefined && elem.nodeType === 1 ) { var name = "data-" + key.replace( rmultiDash, "-$1" ).toLowerCase(); data = elem.getAttribute( name ); if ( typeof data === "string" ) { try { data = data === "true" ? true : data === "false" ? false : data === "null" ? null : // Only convert to a number if it doesn't change the string +data + "" === data ? +data : rbrace.test( data ) ? jQuery.parseJSON( data ) : data; } catch( e ) {} // Make sure we set the data so it isn't changed later jQuery.data( elem, key, data ); } else { data = undefined; } } return data; } // checks a cache object for emptiness function isEmptyDataObject( obj ) { var name; for ( name in obj ) { // if the public data object is empty, the private is still empty if ( name === "data" && jQuery.isEmptyObject( obj[name] ) ) { continue; } if ( name !== "toJSON" ) { return false; } } return true; } jQuery.extend({ queue: function( elem, type, data ) { var queue; if ( elem ) { type = ( type || "fx" ) + "queue"; queue = jQuery._data( elem, type ); // Speed up dequeue by getting out quickly if this is just a lookup if ( data ) { if ( !queue || jQuery.isArray(data) ) { queue = jQuery._data( elem, type, jQuery.makeArray(data) ); } else { queue.push( data ); } } return queue || []; } }, dequeue: function( elem, type ) { type = type || "fx"; var queue = jQuery.queue( elem, type ), startLength = queue.length, fn = queue.shift(), hooks = jQuery._queueHooks( elem, type ), next = function() { jQuery.dequeue( elem, type ); }; // If the fx queue is dequeued, always remove the progress sentinel if ( fn === "inprogress" ) { fn = queue.shift(); startLength--; } hooks.cur = fn; if ( fn ) { // Add a progress sentinel to prevent the fx queue from being // automatically dequeued if ( type === "fx" ) { queue.unshift( "inprogress" ); } // clear up the last queue stop function delete hooks.stop; fn.call( elem, next, hooks ); } if ( !startLength && hooks ) { hooks.empty.fire(); } }, // not intended for public consumption - generates a queueHooks object, or returns the current one _queueHooks: function( elem, type ) { var key = type + "queueHooks"; return jQuery._data( elem, key ) || jQuery._data( elem, key, { empty: jQuery.Callbacks("once memory").add(function() { jQuery._removeData( elem, type + "queue" ); jQuery._removeData( elem, key ); }) }); } }); jQuery.fn.extend({ queue: function( type, data ) { var setter = 2; if ( typeof type !== "string" ) { data = type; type = "fx"; setter--; } if ( arguments.length < setter ) { return jQuery.queue( this[0], type ); } return data === undefined ? this : this.each(function() { var queue = jQuery.queue( this, type, data ); // ensure a hooks for this queue jQuery._queueHooks( this, type ); if ( type === "fx" && queue[0] !== "inprogress" ) { jQuery.dequeue( this, type ); } }); }, dequeue: function( type ) { return this.each(function() { jQuery.dequeue( this, type ); }); }, // Based off of the plugin by Clint Helfers, with permission. // http://blindsignals.com/index.php/2009/07/jquery-delay/ delay: function( time, type ) { time = jQuery.fx ? jQuery.fx.speeds[ time ] || time : time; type = type || "fx"; return this.queue( type, function( next, hooks ) { var timeout = setTimeout( next, time ); hooks.stop = function() { clearTimeout( timeout ); }; }); }, clearQueue: function( type ) { return this.queue( type || "fx", [] ); }, // Get a promise resolved when queues of a certain type // are emptied (fx is the type by default) promise: function( type, obj ) { var tmp, count = 1, defer = jQuery.Deferred(), elements = this, i = this.length, resolve = function() { if ( !( --count ) ) { defer.resolveWith( elements, [ elements ] ); } }; if ( typeof type !== "string" ) { obj = type; type = undefined; } type = type || "fx"; while( i-- ) { tmp = jQuery._data( elements[ i ], type + "queueHooks" ); if ( tmp && tmp.empty ) { count++; tmp.empty.add( resolve ); } } resolve(); return defer.promise( obj ); } }); var nodeHook, boolHook, rclass = /[\t\r\n]/g, rreturn = /\r/g, rfocusable = /^(?:input|select|textarea|button|object)$/i, rclickable = /^(?:a|area)$/i, rboolean = /^(?:checked|selected|autofocus|autoplay|async|controls|defer|disabled|hidden|loop|multiple|open|readonly|required|scoped)$/i, ruseDefault = /^(?:checked|selected)$/i, getSetAttribute = jQuery.support.getSetAttribute, getSetInput = jQuery.support.input; jQuery.fn.extend({ attr: function( name, value ) { return jQuery.access( this, jQuery.attr, name, value, arguments.length > 1 ); }, removeAttr: function( name ) { return this.each(function() { jQuery.removeAttr( this, name ); }); }, prop: function( name, value ) { return jQuery.access( this, jQuery.prop, name, value, arguments.length > 1 ); }, removeProp: function( name ) { name = jQuery.propFix[ name ] || name; return this.each(function() { // try/catch handles cases where IE balks (such as removing a property on window) try { this[ name ] = undefined; delete this[ name ]; } catch( e ) {} }); }, addClass: function( value ) { var classes, elem, cur, clazz, j, i = 0, len = this.length, proceed = typeof value === "string" && value; if ( jQuery.isFunction( value ) ) { return this.each(function( j ) { jQuery( this ).addClass( value.call( this, j, this.className ) ); }); } if ( proceed ) { // The disjunction here is for better compressibility (see removeClass) classes = ( value || "" ).match( core_rnotwhite ) || []; for ( ; i < len; i++ ) { elem = this[ i ]; cur = elem.nodeType === 1 && ( elem.className ? ( " " + elem.className + " " ).replace( rclass, " " ) : " " ); if ( cur ) { j = 0; while ( (clazz = classes[j++]) ) { if ( cur.indexOf( " " + clazz + " " ) < 0 ) { cur += clazz + " "; } } elem.className = jQuery.trim( cur ); } } } return this; }, removeClass: function( value ) { var classes, elem, cur, clazz, j, i = 0, len = this.length, proceed = arguments.length === 0 || typeof value === "string" && value; if ( jQuery.isFunction( value ) ) { return this.each(function( j ) { jQuery( this ).removeClass( value.call( this, j, this.className ) ); }); } if ( proceed ) { classes = ( value || "" ).match( core_rnotwhite ) || []; for ( ; i < len; i++ ) { elem = this[ i ]; // This expression is here for better compressibility (see addClass) cur = elem.nodeType === 1 && ( elem.className ? ( " " + elem.className + " " ).replace( rclass, " " ) : "" ); if ( cur ) { j = 0; while ( (clazz = classes[j++]) ) { // Remove *all* instances while ( cur.indexOf( " " + clazz + " " ) >= 0 ) { cur = cur.replace( " " + clazz + " ", " " ); } } elem.className = value ? jQuery.trim( cur ) : ""; } } } return this; }, toggleClass: function( value, stateVal ) { var type = typeof value, isBool = typeof stateVal === "boolean"; if ( jQuery.isFunction( value ) ) { return this.each(function( i ) { jQuery( this ).toggleClass( value.call(this, i, this.className, stateVal), stateVal ); }); } return this.each(function() { if ( type === "string" ) { // toggle individual class names var className, i = 0, self = jQuery( this ), state = stateVal, classNames = value.match( core_rnotwhite ) || []; while ( (className = classNames[ i++ ]) ) { // check each className given, space separated list state = isBool ? state : !self.hasClass( className ); self[ state ? "addClass" : "removeClass" ]( className ); } // Toggle whole class name } else if ( type === core_strundefined || type === "boolean" ) { if ( this.className ) { // store className if set jQuery._data( this, "__className__", this.className ); } // If the element has a class name or if we're passed "false", // then remove the whole classname (if there was one, the above saved it). // Otherwise bring back whatever was previously saved (if anything), // falling back to the empty string if nothing was stored. this.className = this.className || value === false ? "" : jQuery._data( this, "__className__" ) || ""; } }); }, hasClass: function( selector ) { var className = " " + selector + " ", i = 0, l = this.length; for ( ; i < l; i++ ) { if ( this[i].nodeType === 1 && (" " + this[i].className + " ").replace(rclass, " ").indexOf( className ) >= 0 ) { return true; } } return false; }, val: function( value ) { var ret, hooks, isFunction, elem = this[0]; if ( !arguments.length ) { if ( elem ) { hooks = jQuery.valHooks[ elem.type ] || jQuery.valHooks[ elem.nodeName.toLowerCase() ]; if ( hooks && "get" in hooks && (ret = hooks.get( elem, "value" )) !== undefined ) { return ret; } ret = elem.value; return typeof ret === "string" ? // handle most common string cases ret.replace(rreturn, "") : // handle cases where value is null/undef or number ret == null ? "" : ret; } return; } isFunction = jQuery.isFunction( value ); return this.each(function( i ) { var val, self = jQuery(this); if ( this.nodeType !== 1 ) { return; } if ( isFunction ) { val = value.call( this, i, self.val() ); } else { val = value; } // Treat null/undefined as ""; convert numbers to string if ( val == null ) { val = ""; } else if ( typeof val === "number" ) { val += ""; } else if ( jQuery.isArray( val ) ) { val = jQuery.map(val, function ( value ) { return value == null ? "" : value + ""; }); } hooks = jQuery.valHooks[ this.type ] || jQuery.valHooks[ this.nodeName.toLowerCase() ]; // If set returns undefined, fall back to normal setting if ( !hooks || !("set" in hooks) || hooks.set( this, val, "value" ) === undefined ) { this.value = val; } }); } }); jQuery.extend({ valHooks: { option: { get: function( elem ) { // attributes.value is undefined in Blackberry 4.7 but // uses .value. See #6932 var val = elem.attributes.value; return !val || val.specified ? elem.value : elem.text; } }, select: { get: function( elem ) { var value, option, options = elem.options, index = elem.selectedIndex, one = elem.type === "select-one" || index < 0, values = one ? null : [], max = one ? index + 1 : options.length, i = index < 0 ? max : one ? index : 0; // Loop through all the selected options for ( ; i < max; i++ ) { option = options[ i ]; // oldIE doesn't update selected after form reset (#2551) if ( ( option.selected || i === index ) && // Don't return options that are disabled or in a disabled optgroup ( jQuery.support.optDisabled ? !option.disabled : option.getAttribute("disabled") === null ) && ( !option.parentNode.disabled || !jQuery.nodeName( option.parentNode, "optgroup" ) ) ) { // Get the specific value for the option value = jQuery( option ).val(); // We don't need an array for one selects if ( one ) { return value; } // Multi-Selects return an array values.push( value ); } } return values; }, set: function( elem, value ) { var values = jQuery.makeArray( value ); jQuery(elem).find("option").each(function() { this.selected = jQuery.inArray( jQuery(this).val(), values ) >= 0; }); if ( !values.length ) { elem.selectedIndex = -1; } return values; } } }, attr: function( elem, name, value ) { var hooks, notxml, ret, nType = elem.nodeType; // don't get/set attributes on text, comment and attribute nodes if ( !elem || nType === 3 || nType === 8 || nType === 2 ) { return; } // Fallback to prop when attributes are not supported if ( typeof elem.getAttribute === core_strundefined ) { return jQuery.prop( elem, name, value ); } notxml = nType !== 1 || !jQuery.isXMLDoc( elem ); // All attributes are lowercase // Grab necessary hook if one is defined if ( notxml ) { name = name.toLowerCase(); hooks = jQuery.attrHooks[ name ] || ( rboolean.test( name ) ? boolHook : nodeHook ); } if ( value !== undefined ) { if ( value === null ) { jQuery.removeAttr( elem, name ); } else if ( hooks && notxml && "set" in hooks && (ret = hooks.set( elem, value, name )) !== undefined ) { return ret; } else { elem.setAttribute( name, value + "" ); return value; } } else if ( hooks && notxml && "get" in hooks && (ret = hooks.get( elem, name )) !== null ) { return ret; } else { // In IE9+, Flash objects don't have .getAttribute (#12945) // Support: IE9+ if ( typeof elem.getAttribute !== core_strundefined ) { ret = elem.getAttribute( name ); } // Non-existent attributes return null, we normalize to undefined return ret == null ? undefined : ret; } }, removeAttr: function( elem, value ) { var name, propName, i = 0, attrNames = value && value.match( core_rnotwhite ); if ( attrNames && elem.nodeType === 1 ) { while ( (name = attrNames[i++]) ) { propName = jQuery.propFix[ name ] || name; // Boolean attributes get special treatment (#10870) if ( rboolean.test( name ) ) { // Set corresponding property to false for boolean attributes // Also clear defaultChecked/defaultSelected (if appropriate) for IE<8 if ( !getSetAttribute && ruseDefault.test( name ) ) { elem[ jQuery.camelCase( "default-" + name ) ] = elem[ propName ] = false; } else { elem[ propName ] = false; } // See #9699 for explanation of this approach (setting first, then removal) } else { jQuery.attr( elem, name, "" ); } elem.removeAttribute( getSetAttribute ? name : propName ); } } }, attrHooks: { type: { set: function( elem, value ) { if ( !jQuery.support.radioValue && value === "radio" && jQuery.nodeName(elem, "input") ) { // Setting the type on a radio button after the value resets the value in IE6-9 // Reset value to default in case type is set after value during creation var val = elem.value; elem.setAttribute( "type", value ); if ( val ) { elem.value = val; } return value; } } } }, propFix: { tabindex: "tabIndex", readonly: "readOnly", "for": "htmlFor", "class": "className", maxlength: "maxLength", cellspacing: "cellSpacing", cellpadding: "cellPadding", rowspan: "rowSpan", colspan: "colSpan", usemap: "useMap", frameborder: "frameBorder", contenteditable: "contentEditable" }, prop: function( elem, name, value ) { var ret, hooks, notxml, nType = elem.nodeType; // don't get/set properties on text, comment and attribute nodes if ( !elem || nType === 3 || nType === 8 || nType === 2 ) { return; } notxml = nType !== 1 || !jQuery.isXMLDoc( elem ); if ( notxml ) { // Fix name and attach hooks name = jQuery.propFix[ name ] || name; hooks = jQuery.propHooks[ name ]; } if ( value !== undefined ) { if ( hooks && "set" in hooks && (ret = hooks.set( elem, value, name )) !== undefined ) { return ret; } else { return ( elem[ name ] = value ); } } else { if ( hooks && "get" in hooks && (ret = hooks.get( elem, name )) !== null ) { return ret; } else { return elem[ name ]; } } }, propHooks: { tabIndex: { get: function( elem ) { // elem.tabIndex doesn't always return the correct value when it hasn't been explicitly set // http://fluidproject.org/blog/2008/01/09/getting-setting-and-removing-tabindex-values-with-javascript/ var attributeNode = elem.getAttributeNode("tabindex"); return attributeNode && attributeNode.specified ? parseInt( attributeNode.value, 10 ) : rfocusable.test( elem.nodeName ) || rclickable.test( elem.nodeName ) && elem.href ? 0 : undefined; } } } }); // Hook for boolean attributes boolHook = { get: function( elem, name ) { var // Use .prop to determine if this attribute is understood as boolean prop = jQuery.prop( elem, name ), // Fetch it accordingly attr = typeof prop === "boolean" && elem.getAttribute( name ), detail = typeof prop === "boolean" ? getSetInput && getSetAttribute ? attr != null : // oldIE fabricates an empty string for missing boolean attributes // and conflates checked/selected into attroperties ruseDefault.test( name ) ? elem[ jQuery.camelCase( "default-" + name ) ] : !!attr : // fetch an attribute node for properties not recognized as boolean elem.getAttributeNode( name ); return detail && detail.value !== false ? name.toLowerCase() : undefined; }, set: function( elem, value, name ) { if ( value === false ) { // Remove boolean attributes when set to false jQuery.removeAttr( elem, name ); } else if ( getSetInput && getSetAttribute || !ruseDefault.test( name ) ) { // IE<8 needs the *property* name elem.setAttribute( !getSetAttribute && jQuery.propFix[ name ] || name, name ); // Use defaultChecked and defaultSelected for oldIE } else { elem[ jQuery.camelCase( "default-" + name ) ] = elem[ name ] = true; } return name; } }; // fix oldIE value attroperty if ( !getSetInput || !getSetAttribute ) { jQuery.attrHooks.value = { get: function( elem, name ) { var ret = elem.getAttributeNode( name ); return jQuery.nodeName( elem, "input" ) ? // Ignore the value *property* by using defaultValue elem.defaultValue : ret && ret.specified ? ret.value : undefined; }, set: function( elem, value, name ) { if ( jQuery.nodeName( elem, "input" ) ) { // Does not return so that setAttribute is also used elem.defaultValue = value; } else { // Use nodeHook if defined (#1954); otherwise setAttribute is fine return nodeHook && nodeHook.set( elem, value, name ); } } }; } // IE6/7 do not support getting/setting some attributes with get/setAttribute if ( !getSetAttribute ) { // Use this for any attribute in IE6/7 // This fixes almost every IE6/7 issue nodeHook = jQuery.valHooks.button = { get: function( elem, name ) { var ret = elem.getAttributeNode( name ); return ret && ( name === "id" || name === "name" || name === "coords" ? ret.value !== "" : ret.specified ) ? ret.value : undefined; }, set: function( elem, value, name ) { // Set the existing or create a new attribute node var ret = elem.getAttributeNode( name ); if ( !ret ) { elem.setAttributeNode( (ret = elem.ownerDocument.createAttribute( name )) ); } ret.value = value += ""; // Break association with cloned elements by also using setAttribute (#9646) return name === "value" || value === elem.getAttribute( name ) ? value : undefined; } }; // Set contenteditable to false on removals(#10429) // Setting to empty string throws an error as an invalid value jQuery.attrHooks.contenteditable = { get: nodeHook.get, set: function( elem, value, name ) { nodeHook.set( elem, value === "" ? false : value, name ); } }; // Set width and height to auto instead of 0 on empty string( Bug #8150 ) // This is for removals jQuery.each([ "width", "height" ], function( i, name ) { jQuery.attrHooks[ name ] = jQuery.extend( jQuery.attrHooks[ name ], { set: function( elem, value ) { if ( value === "" ) { elem.setAttribute( name, "auto" ); return value; } } }); }); } // Some attributes require a special call on IE // http://msdn.microsoft.com/en-us/library/ms536429%28VS.85%29.aspx if ( !jQuery.support.hrefNormalized ) { jQuery.each([ "href", "src", "width", "height" ], function( i, name ) { jQuery.attrHooks[ name ] = jQuery.extend( jQuery.attrHooks[ name ], { get: function( elem ) { var ret = elem.getAttribute( name, 2 ); return ret == null ? undefined : ret; } }); }); // href/src property should get the full normalized URL (#10299/#12915) jQuery.each([ "href", "src" ], function( i, name ) { jQuery.propHooks[ name ] = { get: function( elem ) { return elem.getAttribute( name, 4 ); } }; }); } if ( !jQuery.support.style ) { jQuery.attrHooks.style = { get: function( elem ) { // Return undefined in the case of empty string // Note: IE uppercases css property names, but if we were to .toLowerCase() // .cssText, that would destroy case senstitivity in URL's, like in "background" return elem.style.cssText || undefined; }, set: function( elem, value ) { return ( elem.style.cssText = value + "" ); } }; } // Safari mis-reports the default selected property of an option // Accessing the parent's selectedIndex property fixes it if ( !jQuery.support.optSelected ) { jQuery.propHooks.selected = jQuery.extend( jQuery.propHooks.selected, { get: function( elem ) { var parent = elem.parentNode; if ( parent ) { parent.selectedIndex; // Make sure that it also works with optgroups, see #5701 if ( parent.parentNode ) { parent.parentNode.selectedIndex; } } return null; } }); } // IE6/7 call enctype encoding if ( !jQuery.support.enctype ) { jQuery.propFix.enctype = "encoding"; } // Radios and checkboxes getter/setter if ( !jQuery.support.checkOn ) { jQuery.each([ "radio", "checkbox" ], function() { jQuery.valHooks[ this ] = { get: function( elem ) { // Handle the case where in Webkit "" is returned instead of "on" if a value isn't specified return elem.getAttribute("value") === null ? "on" : elem.value; } }; }); } jQuery.each([ "radio", "checkbox" ], function() { jQuery.valHooks[ this ] = jQuery.extend( jQuery.valHooks[ this ], { set: function( elem, value ) { if ( jQuery.isArray( value ) ) { return ( elem.checked = jQuery.inArray( jQuery(elem).val(), value ) >= 0 ); } } }); }); var rformElems = /^(?:input|select|textarea)$/i, rkeyEvent = /^key/, rmouseEvent = /^(?:mouse|contextmenu)|click/, rfocusMorph = /^(?:focusinfocus|focusoutblur)$/, rtypenamespace = /^([^.]*)(?:\.(.+)|)$/; function returnTrue() { return true; } function returnFalse() { return false; } /* * Helper functions for managing events -- not part of the public interface. * Props to Dean Edwards' addEvent library for many of the ideas. */ jQuery.event = { global: {}, add: function( elem, types, handler, data, selector ) { var tmp, events, t, handleObjIn, special, eventHandle, handleObj, handlers, type, namespaces, origType, elemData = jQuery._data( elem ); // Don't attach events to noData or text/comment nodes (but allow plain objects) if ( !elemData ) { return; } // Caller can pass in an object of custom data in lieu of the handler if ( handler.handler ) { handleObjIn = handler; handler = handleObjIn.handler; selector = handleObjIn.selector; } // Make sure that the handler has a unique ID, used to find/remove it later if ( !handler.guid ) { handler.guid = jQuery.guid++; } // Init the element's event structure and main handler, if this is the first if ( !(events = elemData.events) ) { events = elemData.events = {}; } if ( !(eventHandle = elemData.handle) ) { eventHandle = elemData.handle = function( e ) { // Discard the second event of a jQuery.event.trigger() and // when an event is called after a page has unloaded return typeof jQuery !== core_strundefined && (!e || jQuery.event.triggered !== e.type) ? jQuery.event.dispatch.apply( eventHandle.elem, arguments ) : undefined; }; // Add elem as a property of the handle fn to prevent a memory leak with IE non-native events eventHandle.elem = elem; } // Handle multiple events separated by a space // jQuery(...).bind("mouseover mouseout", fn); types = ( types || "" ).match( core_rnotwhite ) || [""]; t = types.length; while ( t-- ) { tmp = rtypenamespace.exec( types[t] ) || []; type = origType = tmp[1]; namespaces = ( tmp[2] || "" ).split( "." ).sort(); // If event changes its type, use the special event handlers for the changed type special = jQuery.event.special[ type ] || {}; // If selector defined, determine special event api type, otherwise given type type = ( selector ? special.delegateType : special.bindType ) || type; // Update special based on newly reset type special = jQuery.event.special[ type ] || {}; // handleObj is passed to all event handlers handleObj = jQuery.extend({ type: type, origType: origType, data: data, handler: handler, guid: handler.guid, selector: selector, needsContext: selector && jQuery.expr.match.needsContext.test( selector ), namespace: namespaces.join(".") }, handleObjIn ); // Init the event handler queue if we're the first if ( !(handlers = events[ type ]) ) { handlers = events[ type ] = []; handlers.delegateCount = 0; // Only use addEventListener/attachEvent if the special events handler returns false if ( !special.setup || special.setup.call( elem, data, namespaces, eventHandle ) === false ) { // Bind the global event handler to the element if ( elem.addEventListener ) { elem.addEventListener( type, eventHandle, false ); } else if ( elem.attachEvent ) { elem.attachEvent( "on" + type, eventHandle ); } } } if ( special.add ) { special.add.call( elem, handleObj ); if ( !handleObj.handler.guid ) { handleObj.handler.guid = handler.guid; } } // Add to the element's handler list, delegates in front if ( selector ) { handlers.splice( handlers.delegateCount++, 0, handleObj ); } else { handlers.push( handleObj ); } // Keep track of which events have ever been used, for event optimization jQuery.event.global[ type ] = true; } // Nullify elem to prevent memory leaks in IE elem = null; }, // Detach an event or set of events from an element remove: function( elem, types, handler, selector, mappedTypes ) { var j, handleObj, tmp, origCount, t, events, special, handlers, type, namespaces, origType, elemData = jQuery.hasData( elem ) && jQuery._data( elem ); if ( !elemData || !(events = elemData.events) ) { return; } // Once for each type.namespace in types; type may be omitted types = ( types || "" ).match( core_rnotwhite ) || [""]; t = types.length; while ( t-- ) { tmp = rtypenamespace.exec( types[t] ) || []; type = origType = tmp[1]; namespaces = ( tmp[2] || "" ).split( "." ).sort(); // Unbind all events (on this namespace, if provided) for the element if ( !type ) { for ( type in events ) { jQuery.event.remove( elem, type + types[ t ], handler, selector, true ); } continue; } special = jQuery.event.special[ type ] || {}; type = ( selector ? special.delegateType : special.bindType ) || type; handlers = events[ type ] || []; tmp = tmp[2] && new RegExp( "(^|\\.)" + namespaces.join("\\.(?:.*\\.|)") + "(\\.|$)" ); // Remove matching events origCount = j = handlers.length; while ( j-- ) { handleObj = handlers[ j ]; if ( ( mappedTypes || origType === handleObj.origType ) && ( !handler || handler.guid === handleObj.guid ) && ( !tmp || tmp.test( handleObj.namespace ) ) && ( !selector || selector === handleObj.selector || selector === "**" && handleObj.selector ) ) { handlers.splice( j, 1 ); if ( handleObj.selector ) { handlers.delegateCount--; } if ( special.remove ) { special.remove.call( elem, handleObj ); } } } // Remove generic event handler if we removed something and no more handlers exist // (avoids potential for endless recursion during removal of special event handlers) if ( origCount && !handlers.length ) { if ( !special.teardown || special.teardown.call( elem, namespaces, elemData.handle ) === false ) { jQuery.removeEvent( elem, type, elemData.handle ); } delete events[ type ]; } } // Remove the expando if it's no longer used if ( jQuery.isEmptyObject( events ) ) { delete elemData.handle; // removeData also checks for emptiness and clears the expando if empty // so use it instead of delete jQuery._removeData( elem, "events" ); } }, trigger: function( event, data, elem, onlyHandlers ) { var handle, ontype, cur, bubbleType, special, tmp, i, eventPath = [ elem || document ], type = core_hasOwn.call( event, "type" ) ? event.type : event, namespaces = core_hasOwn.call( event, "namespace" ) ? event.namespace.split(".") : []; cur = tmp = elem = elem || document; // Don't do events on text and comment nodes if ( elem.nodeType === 3 || elem.nodeType === 8 ) { return; } // focus/blur morphs to focusin/out; ensure we're not firing them right now if ( rfocusMorph.test( type + jQuery.event.triggered ) ) { return; } if ( type.indexOf(".") >= 0 ) { // Namespaced trigger; create a regexp to match event type in handle() namespaces = type.split("."); type = namespaces.shift(); namespaces.sort(); } ontype = type.indexOf(":") < 0 && "on" + type; // Caller can pass in a jQuery.Event object, Object, or just an event type string event = event[ jQuery.expando ] ? event : new jQuery.Event( type, typeof event === "object" && event ); event.isTrigger = true; event.namespace = namespaces.join("."); event.namespace_re = event.namespace ? new RegExp( "(^|\\.)" + namespaces.join("\\.(?:.*\\.|)") + "(\\.|$)" ) : null; // Clean up the event in case it is being reused event.result = undefined; if ( !event.target ) { event.target = elem; } // Clone any incoming data and prepend the event, creating the handler arg list data = data == null ? [ event ] : jQuery.makeArray( data, [ event ] ); // Allow special events to draw outside the lines special = jQuery.event.special[ type ] || {}; if ( !onlyHandlers && special.trigger && special.trigger.apply( elem, data ) === false ) { return; } // Determine event propagation path in advance, per W3C events spec (#9951) // Bubble up to document, then to window; watch for a global ownerDocument var (#9724) if ( !onlyHandlers && !special.noBubble && !jQuery.isWindow( elem ) ) { bubbleType = special.delegateType || type; if ( !rfocusMorph.test( bubbleType + type ) ) { cur = cur.parentNode; } for ( ; cur; cur = cur.parentNode ) { eventPath.push( cur ); tmp = cur; } // Only add window if we got to document (e.g., not plain obj or detached DOM) if ( tmp === (elem.ownerDocument || document) ) { eventPath.push( tmp.defaultView || tmp.parentWindow || window ); } } // Fire handlers on the event path i = 0; while ( (cur = eventPath[i++]) && !event.isPropagationStopped() ) { event.type = i > 1 ? bubbleType : special.bindType || type; // jQuery handler handle = ( jQuery._data( cur, "events" ) || {} )[ event.type ] && jQuery._data( cur, "handle" ); if ( handle ) { handle.apply( cur, data ); } // Native handler handle = ontype && cur[ ontype ]; if ( handle && jQuery.acceptData( cur ) && handle.apply && handle.apply( cur, data ) === false ) { event.preventDefault(); } } event.type = type; // If nobody prevented the default action, do it now if ( !onlyHandlers && !event.isDefaultPrevented() ) { if ( (!special._default || special._default.apply( elem.ownerDocument, data ) === false) && !(type === "click" && jQuery.nodeName( elem, "a" )) && jQuery.acceptData( elem ) ) { // Call a native DOM method on the target with the same name name as the event. // Can't use an .isFunction() check here because IE6/7 fails that test. // Don't do default actions on window, that's where global variables be (#6170) if ( ontype && elem[ type ] && !jQuery.isWindow( elem ) ) { // Don't re-trigger an onFOO event when we call its FOO() method tmp = elem[ ontype ]; if ( tmp ) { elem[ ontype ] = null; } // Prevent re-triggering of the same event, since we already bubbled it above jQuery.event.triggered = type; try { elem[ type ](); } catch ( e ) { // IE<9 dies on focus/blur to hidden element (#1486,#12518) // only reproducible on winXP IE8 native, not IE9 in IE8 mode } jQuery.event.triggered = undefined; if ( tmp ) { elem[ ontype ] = tmp; } } } } return event.result; }, dispatch: function( event ) { // Make a writable jQuery.Event from the native event object event = jQuery.event.fix( event ); var i, ret, handleObj, matched, j, handlerQueue = [], args = core_slice.call( arguments ), handlers = ( jQuery._data( this, "events" ) || {} )[ event.type ] || [], special = jQuery.event.special[ event.type ] || {}; // Use the fix-ed jQuery.Event rather than the (read-only) native event args[0] = event; event.delegateTarget = this; // Call the preDispatch hook for the mapped type, and let it bail if desired if ( special.preDispatch && special.preDispatch.call( this, event ) === false ) { return; } // Determine handlers handlerQueue = jQuery.event.handlers.call( this, event, handlers ); // Run delegates first; they may want to stop propagation beneath us i = 0; while ( (matched = handlerQueue[ i++ ]) && !event.isPropagationStopped() ) { event.currentTarget = matched.elem; j = 0; while ( (handleObj = matched.handlers[ j++ ]) && !event.isImmediatePropagationStopped() ) { // Triggered event must either 1) have no namespace, or // 2) have namespace(s) a subset or equal to those in the bound event (both can have no namespace). if ( !event.namespace_re || event.namespace_re.test( handleObj.namespace ) ) { event.handleObj = handleObj; event.data = handleObj.data; ret = ( (jQuery.event.special[ handleObj.origType ] || {}).handle || handleObj.handler ) .apply( matched.elem, args ); if ( ret !== undefined ) { if ( (event.result = ret) === false ) { event.preventDefault(); event.stopPropagation(); } } } } } // Call the postDispatch hook for the mapped type if ( special.postDispatch ) { special.postDispatch.call( this, event ); } return event.result; }, handlers: function( event, handlers ) { var sel, handleObj, matches, i, handlerQueue = [], delegateCount = handlers.delegateCount, cur = event.target; // Find delegate handlers // Black-hole SVG <use> instance trees (#13180) // Avoid non-left-click bubbling in Firefox (#3861) if ( delegateCount && cur.nodeType && (!event.button || event.type !== "click") ) { for ( ; cur != this; cur = cur.parentNode || this ) { // Don't check non-elements (#13208) // Don't process clicks on disabled elements (#6911, #8165, #11382, #11764) if ( cur.nodeType === 1 && (cur.disabled !== true || event.type !== "click") ) { matches = []; for ( i = 0; i < delegateCount; i++ ) { handleObj = handlers[ i ]; // Don't conflict with Object.prototype properties (#13203) sel = handleObj.selector + " "; if ( matches[ sel ] === undefined ) { matches[ sel ] = handleObj.needsContext ? jQuery( sel, this ).index( cur ) >= 0 : jQuery.find( sel, this, null, [ cur ] ).length; } if ( matches[ sel ] ) { matches.push( handleObj ); } } if ( matches.length ) { handlerQueue.push({ elem: cur, handlers: matches }); } } } } // Add the remaining (directly-bound) handlers if ( delegateCount < handlers.length ) { handlerQueue.push({ elem: this, handlers: handlers.slice( delegateCount ) }); } return handlerQueue; }, fix: function( event ) { if ( event[ jQuery.expando ] ) { return event; } // Create a writable copy of the event object and normalize some properties var i, prop, copy, type = event.type, originalEvent = event, fixHook = this.fixHooks[ type ]; if ( !fixHook ) { this.fixHooks[ type ] = fixHook = rmouseEvent.test( type ) ? this.mouseHooks : rkeyEvent.test( type ) ? this.keyHooks : {}; } copy = fixHook.props ? this.props.concat( fixHook.props ) : this.props; event = new jQuery.Event( originalEvent ); i = copy.length; while ( i-- ) { prop = copy[ i ]; event[ prop ] = originalEvent[ prop ]; } // Support: IE<9 // Fix target property (#1925) if ( !event.target ) { event.target = originalEvent.srcElement || document; } // Support: Chrome 23+, Safari? // Target should not be a text node (#504, #13143) if ( event.target.nodeType === 3 ) { event.target = event.target.parentNode; } // Support: IE<9 // For mouse/key events, metaKey==false if it's undefined (#3368, #11328) event.metaKey = !!event.metaKey; return fixHook.filter ? fixHook.filter( event, originalEvent ) : event; }, // Includes some event props shared by KeyEvent and MouseEvent props: "altKey bubbles cancelable ctrlKey currentTarget eventPhase metaKey relatedTarget shiftKey target timeStamp view which".split(" "), fixHooks: {}, keyHooks: { props: "char charCode key keyCode".split(" "), filter: function( event, original ) { // Add which for key events if ( event.which == null ) { event.which = original.charCode != null ? original.charCode : original.keyCode; } return event; } }, mouseHooks: { props: "button buttons clientX clientY fromElement offsetX offsetY pageX pageY screenX screenY toElement".split(" "), filter: function( event, original ) { var body, eventDoc, doc, button = original.button, fromElement = original.fromElement; // Calculate pageX/Y if missing and clientX/Y available if ( event.pageX == null && original.clientX != null ) { eventDoc = event.target.ownerDocument || document; doc = eventDoc.documentElement; body = eventDoc.body; event.pageX = original.clientX + ( doc && doc.scrollLeft || body && body.scrollLeft || 0 ) - ( doc && doc.clientLeft || body && body.clientLeft || 0 ); event.pageY = original.clientY + ( doc && doc.scrollTop || body && body.scrollTop || 0 ) - ( doc && doc.clientTop || body && body.clientTop || 0 ); } // Add relatedTarget, if necessary if ( !event.relatedTarget && fromElement ) { event.relatedTarget = fromElement === event.target ? original.toElement : fromElement; } // Add which for click: 1 === left; 2 === middle; 3 === right // Note: button is not normalized, so don't use it if ( !event.which && button !== undefined ) { event.which = ( button & 1 ? 1 : ( button & 2 ? 3 : ( button & 4 ? 2 : 0 ) ) ); } return event; } }, special: { load: { // Prevent triggered image.load events from bubbling to window.load noBubble: true }, click: { // For checkbox, fire native event so checked state will be right trigger: function() { if ( jQuery.nodeName( this, "input" ) && this.type === "checkbox" && this.click ) { this.click(); return false; } } }, focus: { // Fire native event if possible so blur/focus sequence is correct trigger: function() { if ( this !== document.activeElement && this.focus ) { try { this.focus(); return false; } catch ( e ) { // Support: IE<9 // If we error on focus to hidden element (#1486, #12518), // let .trigger() run the handlers } } }, delegateType: "focusin" }, blur: { trigger: function() { if ( this === document.activeElement && this.blur ) { this.blur(); return false; } }, delegateType: "focusout" }, beforeunload: { postDispatch: function( event ) { // Even when returnValue equals to undefined Firefox will still show alert if ( event.result !== undefined ) { event.originalEvent.returnValue = event.result; } } } }, simulate: function( type, elem, event, bubble ) { // Piggyback on a donor event to simulate a different one. // Fake originalEvent to avoid donor's stopPropagation, but if the // simulated event prevents default then we do the same on the donor. var e = jQuery.extend( new jQuery.Event(), event, { type: type, isSimulated: true, originalEvent: {} } ); if ( bubble ) { jQuery.event.trigger( e, null, elem ); } else { jQuery.event.dispatch.call( elem, e ); } if ( e.isDefaultPrevented() ) { event.preventDefault(); } } }; jQuery.removeEvent = document.removeEventListener ? function( elem, type, handle ) { if ( elem.removeEventListener ) { elem.removeEventListener( type, handle, false ); } } : function( elem, type, handle ) { var name = "on" + type; if ( elem.detachEvent ) { // #8545, #7054, preventing memory leaks for custom events in IE6-8 // detachEvent needed property on element, by name of that event, to properly expose it to GC if ( typeof elem[ name ] === core_strundefined ) { elem[ name ] = null; } elem.detachEvent( name, handle ); } }; jQuery.Event = function( src, props ) { // Allow instantiation without the 'new' keyword if ( !(this instanceof jQuery.Event) ) { return new jQuery.Event( src, props ); } // Event object if ( src && src.type ) { this.originalEvent = src; this.type = src.type; // Events bubbling up the document may have been marked as prevented // by a handler lower down the tree; reflect the correct value. this.isDefaultPrevented = ( src.defaultPrevented || src.returnValue === false || src.getPreventDefault && src.getPreventDefault() ) ? returnTrue : returnFalse; // Event type } else { this.type = src; } // Put explicitly provided properties onto the event object if ( props ) { jQuery.extend( this, props ); } // Create a timestamp if incoming event doesn't have one this.timeStamp = src && src.timeStamp || jQuery.now(); // Mark it as fixed this[ jQuery.expando ] = true; }; // jQuery.Event is based on DOM3 Events as specified by the ECMAScript Language Binding // http://www.w3.org/TR/2003/WD-DOM-Level-3-Events-20030331/ecma-script-binding.html jQuery.Event.prototype = { isDefaultPrevented: returnFalse, isPropagationStopped: returnFalse, isImmediatePropagationStopped: returnFalse, preventDefault: function() { var e = this.originalEvent; this.isDefaultPrevented = returnTrue; if ( !e ) { return; } // If preventDefault exists, run it on the original event if ( e.preventDefault ) { e.preventDefault(); // Support: IE // Otherwise set the returnValue property of the original event to false } else { e.returnValue = false; } }, stopPropagation: function() { var e = this.originalEvent; this.isPropagationStopped = returnTrue; if ( !e ) { return; } // If stopPropagation exists, run it on the original event if ( e.stopPropagation ) { e.stopPropagation(); } // Support: IE // Set the cancelBubble property of the original event to true e.cancelBubble = true; }, stopImmediatePropagation: function() { this.isImmediatePropagationStopped = returnTrue; this.stopPropagation(); } }; // Create mouseenter/leave events using mouseover/out and event-time checks jQuery.each({ mouseenter: "mouseover", mouseleave: "mouseout" }, function( orig, fix ) { jQuery.event.special[ orig ] = { delegateType: fix, bindType: fix, handle: function( event ) { var ret, target = this, related = event.relatedTarget, handleObj = event.handleObj; // For mousenter/leave call the handler if related is outside the target. // NB: No relatedTarget if the mouse left/entered the browser window if ( !related || (related !== target && !jQuery.contains( target, related )) ) { event.type = handleObj.origType; ret = handleObj.handler.apply( this, arguments ); event.type = fix; } return ret; } }; }); // IE submit delegation if ( !jQuery.support.submitBubbles ) { jQuery.event.special.submit = { setup: function() { // Only need this for delegated form submit events if ( jQuery.nodeName( this, "form" ) ) { return false; } // Lazy-add a submit handler when a descendant form may potentially be submitted jQuery.event.add( this, "click._submit keypress._submit", function( e ) { // Node name check avoids a VML-related crash in IE (#9807) var elem = e.target, form = jQuery.nodeName( elem, "input" ) || jQuery.nodeName( elem, "button" ) ? elem.form : undefined; if ( form && !jQuery._data( form, "submitBubbles" ) ) { jQuery.event.add( form, "submit._submit", function( event ) { event._submit_bubble = true; }); jQuery._data( form, "submitBubbles", true ); } }); // return undefined since we don't need an event listener }, postDispatch: function( event ) { // If form was submitted by the user, bubble the event up the tree if ( event._submit_bubble ) { delete event._submit_bubble; if ( this.parentNode && !event.isTrigger ) { jQuery.event.simulate( "submit", this.parentNode, event, true ); } } }, teardown: function() { // Only need this for delegated form submit events if ( jQuery.nodeName( this, "form" ) ) { return false; } // Remove delegated handlers; cleanData eventually reaps submit handlers attached above jQuery.event.remove( this, "._submit" ); } }; } // IE change delegation and checkbox/radio fix if ( !jQuery.support.changeBubbles ) { jQuery.event.special.change = { setup: function() { if ( rformElems.test( this.nodeName ) ) { // IE doesn't fire change on a check/radio until blur; trigger it on click // after a propertychange. Eat the blur-change in special.change.handle. // This still fires onchange a second time for check/radio after blur. if ( this.type === "checkbox" || this.type === "radio" ) { jQuery.event.add( this, "propertychange._change", function( event ) { if ( event.originalEvent.propertyName === "checked" ) { this._just_changed = true; } }); jQuery.event.add( this, "click._change", function( event ) { if ( this._just_changed && !event.isTrigger ) { this._just_changed = false; } // Allow triggered, simulated change events (#11500) jQuery.event.simulate( "change", this, event, true ); }); } return false; } // Delegated event; lazy-add a change handler on descendant inputs jQuery.event.add( this, "beforeactivate._change", function( e ) { var elem = e.target; if ( rformElems.test( elem.nodeName ) && !jQuery._data( elem, "changeBubbles" ) ) { jQuery.event.add( elem, "change._change", function( event ) { if ( this.parentNode && !event.isSimulated && !event.isTrigger ) { jQuery.event.simulate( "change", this.parentNode, event, true ); } }); jQuery._data( elem, "changeBubbles", true ); } }); }, handle: function( event ) { var elem = event.target; // Swallow native change events from checkbox/radio, we already triggered them above if ( this !== elem || event.isSimulated || event.isTrigger || (elem.type !== "radio" && elem.type !== "checkbox") ) { return event.handleObj.handler.apply( this, arguments ); } }, teardown: function() { jQuery.event.remove( this, "._change" ); return !rformElems.test( this.nodeName ); } }; } // Create "bubbling" focus and blur events if ( !jQuery.support.focusinBubbles ) { jQuery.each({ focus: "focusin", blur: "focusout" }, function( orig, fix ) { // Attach a single capturing handler while someone wants focusin/focusout var attaches = 0, handler = function( event ) { jQuery.event.simulate( fix, event.target, jQuery.event.fix( event ), true ); }; jQuery.event.special[ fix ] = { setup: function() { if ( attaches++ === 0 ) { document.addEventListener( orig, handler, true ); } }, teardown: function() { if ( --attaches === 0 ) { document.removeEventListener( orig, handler, true ); } } }; }); } jQuery.fn.extend({ on: function( types, selector, data, fn, /*INTERNAL*/ one ) { var type, origFn; // Types can be a map of types/handlers if ( typeof types === "object" ) { // ( types-Object, selector, data ) if ( typeof selector !== "string" ) { // ( types-Object, data ) data = data || selector; selector = undefined; } for ( type in types ) { this.on( type, selector, data, types[ type ], one ); } return this; } if ( data == null && fn == null ) { // ( types, fn ) fn = selector; data = selector = undefined; } else if ( fn == null ) { if ( typeof selector === "string" ) { // ( types, selector, fn ) fn = data; data = undefined; } else { // ( types, data, fn ) fn = data; data = selector; selector = undefined; } } if ( fn === false ) { fn = returnFalse; } else if ( !fn ) { return this; } if ( one === 1 ) { origFn = fn; fn = function( event ) { // Can use an empty set, since event contains the info jQuery().off( event ); return origFn.apply( this, arguments ); }; // Use same guid so caller can remove using origFn fn.guid = origFn.guid || ( origFn.guid = jQuery.guid++ ); } return this.each( function() { jQuery.event.add( this, types, fn, data, selector ); }); }, one: function( types, selector, data, fn ) { return this.on( types, selector, data, fn, 1 ); }, off: function( types, selector, fn ) { var handleObj, type; if ( types && types.preventDefault && types.handleObj ) { // ( event ) dispatched jQuery.Event handleObj = types.handleObj; jQuery( types.delegateTarget ).off( handleObj.namespace ? handleObj.origType + "." + handleObj.namespace : handleObj.origType, handleObj.selector, handleObj.handler ); return this; } if ( typeof types === "object" ) { // ( types-object [, selector] ) for ( type in types ) { this.off( type, selector, types[ type ] ); } return this; } if ( selector === false || typeof selector === "function" ) { // ( types [, fn] ) fn = selector; selector = undefined; } if ( fn === false ) { fn = returnFalse; } return this.each(function() { jQuery.event.remove( this, types, fn, selector ); }); }, bind: function( types, data, fn ) { return this.on( types, null, data, fn ); }, unbind: function( types, fn ) { return this.off( types, null, fn ); }, delegate: function( selector, types, data, fn ) { return this.on( types, selector, data, fn ); }, undelegate: function( selector, types, fn ) { // ( namespace ) or ( selector, types [, fn] ) return arguments.length === 1 ? this.off( selector, "**" ) : this.off( types, selector || "**", fn ); }, trigger: function( type, data ) { return this.each(function() { jQuery.event.trigger( type, data, this ); }); }, triggerHandler: function( type, data ) { var elem = this[0]; if ( elem ) { return jQuery.event.trigger( type, data, elem, true ); } } }); /*! * Sizzle CSS Selector Engine * Copyright 2012 jQuery Foundation and other contributors * Released under the MIT license * http://sizzlejs.com/ */ (function( window, undefined ) { var i, cachedruns, Expr, getText, isXML, compile, hasDuplicate, outermostContext, // Local document vars setDocument, document, docElem, documentIsXML, rbuggyQSA, rbuggyMatches, matches, contains, sortOrder, // Instance-specific data expando = "sizzle" + -(new Date()), preferredDoc = window.document, support = {}, dirruns = 0, done = 0, classCache = createCache(), tokenCache = createCache(), compilerCache = createCache(), // General-purpose constants strundefined = typeof undefined, MAX_NEGATIVE = 1 << 31, // Array methods arr = [], pop = arr.pop, push = arr.push, slice = arr.slice, // Use a stripped-down indexOf if we can't use a native one indexOf = arr.indexOf || function( elem ) { var i = 0, len = this.length; for ( ; i < len; i++ ) { if ( this[i] === elem ) { return i; } } return -1; }, // Regular expressions // Whitespace characters http://www.w3.org/TR/css3-selectors/#whitespace whitespace = "[\\x20\\t\\r\\n\\f]", // http://www.w3.org/TR/css3-syntax/#characters characterEncoding = "(?:\\\\.|[\\w-]|[^\\x00-\\xa0])+", // Loosely modeled on CSS identifier characters // An unquoted value should be a CSS identifier http://www.w3.org/TR/css3-selectors/#attribute-selectors // Proper syntax: http://www.w3.org/TR/CSS21/syndata.html#value-def-identifier identifier = characterEncoding.replace( "w", "w#" ), // Acceptable operators http://www.w3.org/TR/selectors/#attribute-selectors operators = "([*^$|!~]?=)", attributes = "\\[" + whitespace + "*(" + characterEncoding + ")" + whitespace + "*(?:" + operators + whitespace + "*(?:(['\"])((?:\\\\.|[^\\\\])*?)\\3|(" + identifier + ")|)|)" + whitespace + "*\\]", // Prefer arguments quoted, // then not containing pseudos/brackets, // then attribute selectors/non-parenthetical expressions, // then anything else // These preferences are here to reduce the number of selectors // needing tokenize in the PSEUDO preFilter pseudos = ":(" + characterEncoding + ")(?:\\(((['\"])((?:\\\\.|[^\\\\])*?)\\3|((?:\\\\.|[^\\\\()[\\]]|" + attributes.replace( 3, 8 ) + ")*)|.*)\\)|)", // Leading and non-escaped trailing whitespace, capturing some non-whitespace characters preceding the latter rtrim = new RegExp( "^" + whitespace + "+|((?:^|[^\\\\])(?:\\\\.)*)" + whitespace + "+$", "g" ), rcomma = new RegExp( "^" + whitespace + "*," + whitespace + "*" ), rcombinators = new RegExp( "^" + whitespace + "*([\\x20\\t\\r\\n\\f>+~])" + whitespace + "*" ), rpseudo = new RegExp( pseudos ), ridentifier = new RegExp( "^" + identifier + "$" ), matchExpr = { "ID": new RegExp( "^#(" + characterEncoding + ")" ), "CLASS": new RegExp( "^\\.(" + characterEncoding + ")" ), "NAME": new RegExp( "^\\[name=['\"]?(" + characterEncoding + ")['\"]?\\]" ), "TAG": new RegExp( "^(" + characterEncoding.replace( "w", "w*" ) + ")" ), "ATTR": new RegExp( "^" + attributes ), "PSEUDO": new RegExp( "^" + pseudos ), "CHILD": new RegExp( "^:(only|first|last|nth|nth-last)-(child|of-type)(?:\\(" + whitespace + "*(even|odd|(([+-]|)(\\d*)n|)" + whitespace + "*(?:([+-]|)" + whitespace + "*(\\d+)|))" + whitespace + "*\\)|)", "i" ), // For use in libraries implementing .is() // We use this for POS matching in `select` "needsContext": new RegExp( "^" + whitespace + "*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\\(" + whitespace + "*((?:-\\d)?\\d*)" + whitespace + "*\\)|)(?=[^-]|$)", "i" ) }, rsibling = /[\x20\t\r\n\f]*[+~]/, rnative = /^[^{]+\{\s*\[native code/, // Easily-parseable/retrievable ID or TAG or CLASS selectors rquickExpr = /^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/, rinputs = /^(?:input|select|textarea|button)$/i, rheader = /^h\d$/i, rescape = /'|\\/g, rattributeQuotes = /\=[\x20\t\r\n\f]*([^'"\]]*)[\x20\t\r\n\f]*\]/g, // CSS escapes http://www.w3.org/TR/CSS21/syndata.html#escaped-characters runescape = /\\([\da-fA-F]{1,6}[\x20\t\r\n\f]?|.)/g, funescape = function( _, escaped ) { var high = "0x" + escaped - 0x10000; // NaN means non-codepoint return high !== high ? escaped : // BMP codepoint high < 0 ? String.fromCharCode( high + 0x10000 ) : // Supplemental Plane codepoint (surrogate pair) String.fromCharCode( high >> 10 | 0xD800, high & 0x3FF | 0xDC00 ); }; // Use a stripped-down slice if we can't use a native one try { slice.call( preferredDoc.documentElement.childNodes, 0 )[0].nodeType; } catch ( e ) { slice = function( i ) { var elem, results = []; while ( (elem = this[i++]) ) { results.push( elem ); } return results; }; } /** * For feature detection * @param {Function} fn The function to test for native support */ function isNative( fn ) { return rnative.test( fn + "" ); } /** * Create key-value caches of limited size * @returns {Function(string, Object)} Returns the Object data after storing it on itself with * property name the (space-suffixed) string and (if the cache is larger than Expr.cacheLength) * deleting the oldest entry */ function createCache() { var cache, keys = []; return (cache = function( key, value ) { // Use (key + " ") to avoid collision with native prototype properties (see Issue #157) if ( keys.push( key += " " ) > Expr.cacheLength ) { // Only keep the most recent entries delete cache[ keys.shift() ]; } return (cache[ key ] = value); }); } /** * Mark a function for special use by Sizzle * @param {Function} fn The function to mark */ function markFunction( fn ) { fn[ expando ] = true; return fn; } /** * Support testing using an element * @param {Function} fn Passed the created div and expects a boolean result */ function assert( fn ) { var div = document.createElement("div"); try { return fn( div ); } catch (e) { return false; } finally { // release memory in IE div = null; } } function Sizzle( selector, context, results, seed ) { var match, elem, m, nodeType, // QSA vars i, groups, old, nid, newContext, newSelector; if ( ( context ? context.ownerDocument || context : preferredDoc ) !== document ) { setDocument( context ); } context = context || document; results = results || []; if ( !selector || typeof selector !== "string" ) { return results; } if ( (nodeType = context.nodeType) !== 1 && nodeType !== 9 ) { return []; } if ( !documentIsXML && !seed ) { // Shortcuts if ( (match = rquickExpr.exec( selector )) ) { // Speed-up: Sizzle("#ID") if ( (m = match[1]) ) { if ( nodeType === 9 ) { elem = context.getElementById( m ); // Check parentNode to catch when Blackberry 4.6 returns // nodes that are no longer in the document #6963 if ( elem && elem.parentNode ) { // Handle the case where IE, Opera, and Webkit return items // by name instead of ID if ( elem.id === m ) { results.push( elem ); return results; } } else { return results; } } else { // Context is not a document if ( context.ownerDocument && (elem = context.ownerDocument.getElementById( m )) && contains( context, elem ) && elem.id === m ) { results.push( elem ); return results; } } // Speed-up: Sizzle("TAG") } else if ( match[2] ) { push.apply( results, slice.call(context.getElementsByTagName( selector ), 0) ); return results; // Speed-up: Sizzle(".CLASS") } else if ( (m = match[3]) && support.getByClassName && context.getElementsByClassName ) { push.apply( results, slice.call(context.getElementsByClassName( m ), 0) ); return results; } } // QSA path if ( support.qsa && !rbuggyQSA.test(selector) ) { old = true; nid = expando; newContext = context; newSelector = nodeType === 9 && selector; // qSA works strangely on Element-rooted queries // We can work around this by specifying an extra ID on the root // and working up from there (Thanks to Andrew Dupont for the technique) // IE 8 doesn't work on object elements if ( nodeType === 1 && context.nodeName.toLowerCase() !== "object" ) { groups = tokenize( selector ); if ( (old = context.getAttribute("id")) ) { nid = old.replace( rescape, "\\$&" ); } else { context.setAttribute( "id", nid ); } nid = "[id='" + nid + "'] "; i = groups.length; while ( i-- ) { groups[i] = nid + toSelector( groups[i] ); } newContext = rsibling.test( selector ) && context.parentNode || context; newSelector = groups.join(","); } if ( newSelector ) { try { push.apply( results, slice.call( newContext.querySelectorAll( newSelector ), 0 ) ); return results; } catch(qsaError) { } finally { if ( !old ) { context.removeAttribute("id"); } } } } } // All others return select( selector.replace( rtrim, "$1" ), context, results, seed ); } /** * Detect xml * @param {Element|Object} elem An element or a document */ isXML = Sizzle.isXML = function( elem ) { // documentElement is verified for cases where it doesn't yet exist // (such as loading iframes in IE - #4833) var documentElement = elem && (elem.ownerDocument || elem).documentElement; return documentElement ? documentElement.nodeName !== "HTML" : false; }; /** * Sets document-related variables once based on the current document * @param {Element|Object} [doc] An element or document object to use to set the document * @returns {Object} Returns the current document */ setDocument = Sizzle.setDocument = function( node ) { var doc = node ? node.ownerDocument || node : preferredDoc; // If no document and documentElement is available, return if ( doc === document || doc.nodeType !== 9 || !doc.documentElement ) { return document; } // Set our document document = doc; docElem = doc.documentElement; // Support tests documentIsXML = isXML( doc ); // Check if getElementsByTagName("*") returns only elements support.tagNameNoComments = assert(function( div ) { div.appendChild( doc.createComment("") ); return !div.getElementsByTagName("*").length; }); // Check if attributes should be retrieved by attribute nodes support.attributes = assert(function( div ) { div.innerHTML = "<select></select>"; var type = typeof div.lastChild.getAttribute("multiple"); // IE8 returns a string for some attributes even when not present return type !== "boolean" && type !== "string"; }); // Check if getElementsByClassName can be trusted support.getByClassName = assert(function( div ) { // Opera can't find a second classname (in 9.6) div.innerHTML = "<div class='hidden e'></div><div class='hidden'></div>"; if ( !div.getElementsByClassName || !div.getElementsByClassName("e").length ) { return false; } // Safari 3.2 caches class attributes and doesn't catch changes div.lastChild.className = "e"; return div.getElementsByClassName("e").length === 2; }); // Check if getElementById returns elements by name // Check if getElementsByName privileges form controls or returns elements by ID support.getByName = assert(function( div ) { // Inject content div.id = expando + 0; div.innerHTML = "<a name='" + expando + "'></a><div name='" + expando + "'></div>"; docElem.insertBefore( div, docElem.firstChild ); // Test var pass = doc.getElementsByName && // buggy browsers will return fewer than the correct 2 doc.getElementsByName( expando ).length === 2 + // buggy browsers will return more than the correct 0 doc.getElementsByName( expando + 0 ).length; support.getIdNotName = !doc.getElementById( expando ); // Cleanup docElem.removeChild( div ); return pass; }); // IE6/7 return modified attributes Expr.attrHandle = assert(function( div ) { div.innerHTML = "<a href='#'></a>"; return div.firstChild && typeof div.firstChild.getAttribute !== strundefined && div.firstChild.getAttribute("href") === "#"; }) ? {} : { "href": function( elem ) { return elem.getAttribute( "href", 2 ); }, "type": function( elem ) { return elem.getAttribute("type"); } }; // ID find and filter if ( support.getIdNotName ) { Expr.find["ID"] = function( id, context ) { if ( typeof context.getElementById !== strundefined && !documentIsXML ) { var m = context.getElementById( id ); // Check parentNode to catch when Blackberry 4.6 returns // nodes that are no longer in the document #6963 return m && m.parentNode ? [m] : []; } }; Expr.filter["ID"] = function( id ) { var attrId = id.replace( runescape, funescape ); return function( elem ) { return elem.getAttribute("id") === attrId; }; }; } else { Expr.find["ID"] = function( id, context ) { if ( typeof context.getElementById !== strundefined && !documentIsXML ) { var m = context.getElementById( id ); return m ? m.id === id || typeof m.getAttributeNode !== strundefined && m.getAttributeNode("id").value === id ? [m] : undefined : []; } }; Expr.filter["ID"] = function( id ) { var attrId = id.replace( runescape, funescape ); return function( elem ) { var node = typeof elem.getAttributeNode !== strundefined && elem.getAttributeNode("id"); return node && node.value === attrId; }; }; } // Tag Expr.find["TAG"] = support.tagNameNoComments ? function( tag, context ) { if ( typeof context.getElementsByTagName !== strundefined ) { return context.getElementsByTagName( tag ); } } : function( tag, context ) { var elem, tmp = [], i = 0, results = context.getElementsByTagName( tag ); // Filter out possible comments if ( tag === "*" ) { while ( (elem = results[i++]) ) { if ( elem.nodeType === 1 ) { tmp.push( elem ); } } return tmp; } return results; }; // Name Expr.find["NAME"] = support.getByName && function( tag, context ) { if ( typeof context.getElementsByName !== strundefined ) { return context.getElementsByName( name ); } }; // Class Expr.find["CLASS"] = support.getByClassName && function( className, context ) { if ( typeof context.getElementsByClassName !== strundefined && !documentIsXML ) { return context.getElementsByClassName( className ); } }; // QSA and matchesSelector support // matchesSelector(:active) reports false when true (IE9/Opera 11.5) rbuggyMatches = []; // qSa(:focus) reports false when true (Chrome 21), // no need to also add to buggyMatches since matches checks buggyQSA // A support test would require too much code (would include document ready) rbuggyQSA = [ ":focus" ]; if ( (support.qsa = isNative(doc.querySelectorAll)) ) { // Build QSA regex // Regex strategy adopted from Diego Perini assert(function( div ) { // Select is set to empty string on purpose // This is to test IE's treatment of not explictly // setting a boolean content attribute, // since its presence should be enough // http://bugs.jquery.com/ticket/12359 div.innerHTML = "<select><option selected=''></option></select>"; // IE8 - Some boolean attributes are not treated correctly if ( !div.querySelectorAll("[selected]").length ) { rbuggyQSA.push( "\\[" + whitespace + "*(?:checked|disabled|ismap|multiple|readonly|selected|value)" ); } // Webkit/Opera - :checked should return selected option elements // http://www.w3.org/TR/2011/REC-css3-selectors-20110929/#checked // IE8 throws error here and will not see later tests if ( !div.querySelectorAll(":checked").length ) { rbuggyQSA.push(":checked"); } }); assert(function( div ) { // Opera 10-12/IE8 - ^= $= *= and empty values // Should not select anything div.innerHTML = "<input type='hidden' i=''/>"; if ( div.querySelectorAll("[i^='']").length ) { rbuggyQSA.push( "[*^$]=" + whitespace + "*(?:\"\"|'')" ); } // FF 3.5 - :enabled/:disabled and hidden elements (hidden elements are still enabled) // IE8 throws error here and will not see later tests if ( !div.querySelectorAll(":enabled").length ) { rbuggyQSA.push( ":enabled", ":disabled" ); } // Opera 10-11 does not throw on post-comma invalid pseudos div.querySelectorAll("*,:x"); rbuggyQSA.push(",.*:"); }); } if ( (support.matchesSelector = isNative( (matches = docElem.matchesSelector || docElem.mozMatchesSelector || docElem.webkitMatchesSelector || docElem.oMatchesSelector || docElem.msMatchesSelector) )) ) { assert(function( div ) { // Check to see if it's possible to do matchesSelector // on a disconnected node (IE 9) support.disconnectedMatch = matches.call( div, "div" ); // This should fail with an exception // Gecko does not error, returns false instead matches.call( div, "[s!='']:x" ); rbuggyMatches.push( "!=", pseudos ); }); } rbuggyQSA = new RegExp( rbuggyQSA.join("|") ); rbuggyMatches = new RegExp( rbuggyMatches.join("|") ); // Element contains another // Purposefully does not implement inclusive descendent // As in, an element does not contain itself contains = isNative(docElem.contains) || docElem.compareDocumentPosition ? function( a, b ) { var adown = a.nodeType === 9 ? a.documentElement : a, bup = b && b.parentNode; return a === bup || !!( bup && bup.nodeType === 1 && ( adown.contains ? adown.contains( bup ) : a.compareDocumentPosition && a.compareDocumentPosition( bup ) & 16 )); } : function( a, b ) { if ( b ) { while ( (b = b.parentNode) ) { if ( b === a ) { return true; } } } return false; }; // Document order sorting sortOrder = docElem.compareDocumentPosition ? function( a, b ) { var compare; if ( a === b ) { hasDuplicate = true; return 0; } if ( (compare = b.compareDocumentPosition && a.compareDocumentPosition && a.compareDocumentPosition( b )) ) { if ( compare & 1 || a.parentNode && a.parentNode.nodeType === 11 ) { if ( a === doc || contains( preferredDoc, a ) ) { return -1; } if ( b === doc || contains( preferredDoc, b ) ) { return 1; } return 0; } return compare & 4 ? -1 : 1; } return a.compareDocumentPosition ? -1 : 1; } : function( a, b ) { var cur, i = 0, aup = a.parentNode, bup = b.parentNode, ap = [ a ], bp = [ b ]; // Exit early if the nodes are identical if ( a === b ) { hasDuplicate = true; return 0; // Parentless nodes are either documents or disconnected } else if ( !aup || !bup ) { return a === doc ? -1 : b === doc ? 1 : aup ? -1 : bup ? 1 : 0; // If the nodes are siblings, we can do a quick check } else if ( aup === bup ) { return siblingCheck( a, b ); } // Otherwise we need full lists of their ancestors for comparison cur = a; while ( (cur = cur.parentNode) ) { ap.unshift( cur ); } cur = b; while ( (cur = cur.parentNode) ) { bp.unshift( cur ); } // Walk down the tree looking for a discrepancy while ( ap[i] === bp[i] ) { i++; } return i ? // Do a sibling check if the nodes have a common ancestor siblingCheck( ap[i], bp[i] ) : // Otherwise nodes in our document sort first ap[i] === preferredDoc ? -1 : bp[i] === preferredDoc ? 1 : 0; }; // Always assume the presence of duplicates if sort doesn't // pass them to our comparison function (as in Google Chrome). hasDuplicate = false; [0, 0].sort( sortOrder ); support.detectDuplicates = hasDuplicate; return document; }; Sizzle.matches = function( expr, elements ) { return Sizzle( expr, null, null, elements ); }; Sizzle.matchesSelector = function( elem, expr ) { // Set document vars if needed if ( ( elem.ownerDocument || elem ) !== document ) { setDocument( elem ); } // Make sure that attribute selectors are quoted expr = expr.replace( rattributeQuotes, "='$1']" ); // rbuggyQSA always contains :focus, so no need for an existence check if ( support.matchesSelector && !documentIsXML && (!rbuggyMatches || !rbuggyMatches.test(expr)) && !rbuggyQSA.test(expr) ) { try { var ret = matches.call( elem, expr ); // IE 9's matchesSelector returns false on disconnected nodes if ( ret || support.disconnectedMatch || // As well, disconnected nodes are said to be in a document // fragment in IE 9 elem.document && elem.document.nodeType !== 11 ) { return ret; } } catch(e) {} } return Sizzle( expr, document, null, [elem] ).length > 0; }; Sizzle.contains = function( context, elem ) { // Set document vars if needed if ( ( context.ownerDocument || context ) !== document ) { setDocument( context ); } return contains( context, elem ); }; Sizzle.attr = function( elem, name ) { var val; // Set document vars if needed if ( ( elem.ownerDocument || elem ) !== document ) { setDocument( elem ); } if ( !documentIsXML ) { name = name.toLowerCase(); } if ( (val = Expr.attrHandle[ name ]) ) { return val( elem ); } if ( documentIsXML || support.attributes ) { return elem.getAttribute( name ); } return ( (val = elem.getAttributeNode( name )) || elem.getAttribute( name ) ) && elem[ name ] === true ? name : val && val.specified ? val.value : null; }; Sizzle.error = function( msg ) { throw new Error( "Syntax error, unrecognized expression: " + msg ); }; // Document sorting and removing duplicates Sizzle.uniqueSort = function( results ) { var elem, duplicates = [], i = 1, j = 0; // Unless we *know* we can detect duplicates, assume their presence hasDuplicate = !support.detectDuplicates; results.sort( sortOrder ); if ( hasDuplicate ) { for ( ; (elem = results[i]); i++ ) { if ( elem === results[ i - 1 ] ) { j = duplicates.push( i ); } } while ( j-- ) { results.splice( duplicates[ j ], 1 ); } } return results; }; function siblingCheck( a, b ) { var cur = b && a, diff = cur && ( ~b.sourceIndex || MAX_NEGATIVE ) - ( ~a.sourceIndex || MAX_NEGATIVE ); // Use IE sourceIndex if available on both nodes if ( diff ) { return diff; } // Check if b follows a if ( cur ) { while ( (cur = cur.nextSibling) ) { if ( cur === b ) { return -1; } } } return a ? 1 : -1; } // Returns a function to use in pseudos for input types function createInputPseudo( type ) { return function( elem ) { var name = elem.nodeName.toLowerCase(); return name === "input" && elem.type === type; }; } // Returns a function to use in pseudos for buttons function createButtonPseudo( type ) { return function( elem ) { var name = elem.nodeName.toLowerCase(); return (name === "input" || name === "button") && elem.type === type; }; } // Returns a function to use in pseudos for positionals function createPositionalPseudo( fn ) { return markFunction(function( argument ) { argument = +argument; return markFunction(function( seed, matches ) { var j, matchIndexes = fn( [], seed.length, argument ), i = matchIndexes.length; // Match elements found at the specified indexes while ( i-- ) { if ( seed[ (j = matchIndexes[i]) ] ) { seed[j] = !(matches[j] = seed[j]); } } }); }); } /** * Utility function for retrieving the text value of an array of DOM nodes * @param {Array|Element} elem */ getText = Sizzle.getText = function( elem ) { var node, ret = "", i = 0, nodeType = elem.nodeType; if ( !nodeType ) { // If no nodeType, this is expected to be an array for ( ; (node = elem[i]); i++ ) { // Do not traverse comment nodes ret += getText( node ); } } else if ( nodeType === 1 || nodeType === 9 || nodeType === 11 ) { // Use textContent for elements // innerText usage removed for consistency of new lines (see #11153) if ( typeof elem.textContent === "string" ) { return elem.textContent; } else { // Traverse its children for ( elem = elem.firstChild; elem; elem = elem.nextSibling ) { ret += getText( elem ); } } } else if ( nodeType === 3 || nodeType === 4 ) { return elem.nodeValue; } // Do not include comment or processing instruction nodes return ret; }; Expr = Sizzle.selectors = { // Can be adjusted by the user cacheLength: 50, createPseudo: markFunction, match: matchExpr, find: {}, relative: { ">": { dir: "parentNode", first: true }, " ": { dir: "parentNode" }, "+": { dir: "previousSibling", first: true }, "~": { dir: "previousSibling" } }, preFilter: { "ATTR": function( match ) { match[1] = match[1].replace( runescape, funescape ); // Move the given value to match[3] whether quoted or unquoted match[3] = ( match[4] || match[5] || "" ).replace( runescape, funescape ); if ( match[2] === "~=" ) { match[3] = " " + match[3] + " "; } return match.slice( 0, 4 ); }, "CHILD": function( match ) { /* matches from matchExpr["CHILD"] 1 type (only|nth|...) 2 what (child|of-type) 3 argument (even|odd|\d*|\d*n([+-]\d+)?|...) 4 xn-component of xn+y argument ([+-]?\d*n|) 5 sign of xn-component 6 x of xn-component 7 sign of y-component 8 y of y-component */ match[1] = match[1].toLowerCase(); if ( match[1].slice( 0, 3 ) === "nth" ) { // nth-* requires argument if ( !match[3] ) { Sizzle.error( match[0] ); } // numeric x and y parameters for Expr.filter.CHILD // remember that false/true cast respectively to 0/1 match[4] = +( match[4] ? match[5] + (match[6] || 1) : 2 * ( match[3] === "even" || match[3] === "odd" ) ); match[5] = +( ( match[7] + match[8] ) || match[3] === "odd" ); // other types prohibit arguments } else if ( match[3] ) { Sizzle.error( match[0] ); } return match; }, "PSEUDO": function( match ) { var excess, unquoted = !match[5] && match[2]; if ( matchExpr["CHILD"].test( match[0] ) ) { return null; } // Accept quoted arguments as-is if ( match[4] ) { match[2] = match[4]; // Strip excess characters from unquoted arguments } else if ( unquoted && rpseudo.test( unquoted ) && // Get excess from tokenize (recursively) (excess = tokenize( unquoted, true )) && // advance to the next closing parenthesis (excess = unquoted.indexOf( ")", unquoted.length - excess ) - unquoted.length) ) { // excess is a negative index match[0] = match[0].slice( 0, excess ); match[2] = unquoted.slice( 0, excess ); } // Return only captures needed by the pseudo filter method (type and argument) return match.slice( 0, 3 ); } }, filter: { "TAG": function( nodeName ) { if ( nodeName === "*" ) { return function() { return true; }; } nodeName = nodeName.replace( runescape, funescape ).toLowerCase(); return function( elem ) { return elem.nodeName && elem.nodeName.toLowerCase() === nodeName; }; }, "CLASS": function( className ) { var pattern = classCache[ className + " " ]; return pattern || (pattern = new RegExp( "(^|" + whitespace + ")" + className + "(" + whitespace + "|$)" )) && classCache( className, function( elem ) { return pattern.test( elem.className || (typeof elem.getAttribute !== strundefined && elem.getAttribute("class")) || "" ); }); }, "ATTR": function( name, operator, check ) { return function( elem ) { var result = Sizzle.attr( elem, name ); if ( result == null ) { return operator === "!="; } if ( !operator ) { return true; } result += ""; return operator === "=" ? result === check : operator === "!=" ? result !== check : operator === "^=" ? check && result.indexOf( check ) === 0 : operator === "*=" ? check && result.indexOf( check ) > -1 : operator === "$=" ? check && result.slice( -check.length ) === check : operator === "~=" ? ( " " + result + " " ).indexOf( check ) > -1 : operator === "|=" ? result === check || result.slice( 0, check.length + 1 ) === check + "-" : false; }; }, "CHILD": function( type, what, argument, first, last ) { var simple = type.slice( 0, 3 ) !== "nth", forward = type.slice( -4 ) !== "last", ofType = what === "of-type"; return first === 1 && last === 0 ? // Shortcut for :nth-*(n) function( elem ) { return !!elem.parentNode; } : function( elem, context, xml ) { var cache, outerCache, node, diff, nodeIndex, start, dir = simple !== forward ? "nextSibling" : "previousSibling", parent = elem.parentNode, name = ofType && elem.nodeName.toLowerCase(), useCache = !xml && !ofType; if ( parent ) { // :(first|last|only)-(child|of-type) if ( simple ) { while ( dir ) { node = elem; while ( (node = node[ dir ]) ) { if ( ofType ? node.nodeName.toLowerCase() === name : node.nodeType === 1 ) { return false; } } // Reverse direction for :only-* (if we haven't yet done so) start = dir = type === "only" && !start && "nextSibling"; } return true; } start = [ forward ? parent.firstChild : parent.lastChild ]; // non-xml :nth-child(...) stores cache data on `parent` if ( forward && useCache ) { // Seek `elem` from a previously-cached index outerCache = parent[ expando ] || (parent[ expando ] = {}); cache = outerCache[ type ] || []; nodeIndex = cache[0] === dirruns && cache[1]; diff = cache[0] === dirruns && cache[2]; node = nodeIndex && parent.childNodes[ nodeIndex ]; while ( (node = ++nodeIndex && node && node[ dir ] || // Fallback to seeking `elem` from the start (diff = nodeIndex = 0) || start.pop()) ) { // When found, cache indexes on `parent` and break if ( node.nodeType === 1 && ++diff && node === elem ) { outerCache[ type ] = [ dirruns, nodeIndex, diff ]; break; } } // Use previously-cached element index if available } else if ( useCache && (cache = (elem[ expando ] || (elem[ expando ] = {}))[ type ]) && cache[0] === dirruns ) { diff = cache[1]; // xml :nth-child(...) or :nth-last-child(...) or :nth(-last)?-of-type(...) } else { // Use the same loop as above to seek `elem` from the start while ( (node = ++nodeIndex && node && node[ dir ] || (diff = nodeIndex = 0) || start.pop()) ) { if ( ( ofType ? node.nodeName.toLowerCase() === name : node.nodeType === 1 ) && ++diff ) { // Cache the index of each encountered element if ( useCache ) { (node[ expando ] || (node[ expando ] = {}))[ type ] = [ dirruns, diff ]; } if ( node === elem ) { break; } } } } // Incorporate the offset, then check against cycle size diff -= last; return diff === first || ( diff % first === 0 && diff / first >= 0 ); } }; }, "PSEUDO": function( pseudo, argument ) { // pseudo-class names are case-insensitive // http://www.w3.org/TR/selectors/#pseudo-classes // Prioritize by case sensitivity in case custom pseudos are added with uppercase letters // Remember that setFilters inherits from pseudos var args, fn = Expr.pseudos[ pseudo ] || Expr.setFilters[ pseudo.toLowerCase() ] || Sizzle.error( "unsupported pseudo: " + pseudo ); // The user may use createPseudo to indicate that // arguments are needed to create the filter function // just as Sizzle does if ( fn[ expando ] ) { return fn( argument ); } // But maintain support for old signatures if ( fn.length > 1 ) { args = [ pseudo, pseudo, "", argument ]; return Expr.setFilters.hasOwnProperty( pseudo.toLowerCase() ) ? markFunction(function( seed, matches ) { var idx, matched = fn( seed, argument ), i = matched.length; while ( i-- ) { idx = indexOf.call( seed, matched[i] ); seed[ idx ] = !( matches[ idx ] = matched[i] ); } }) : function( elem ) { return fn( elem, 0, args ); }; } return fn; } }, pseudos: { // Potentially complex pseudos "not": markFunction(function( selector ) { // Trim the selector passed to compile // to avoid treating leading and trailing // spaces as combinators var input = [], results = [], matcher = compile( selector.replace( rtrim, "$1" ) ); return matcher[ expando ] ? markFunction(function( seed, matches, context, xml ) { var elem, unmatched = matcher( seed, null, xml, [] ), i = seed.length; // Match elements unmatched by `matcher` while ( i-- ) { if ( (elem = unmatched[i]) ) { seed[i] = !(matches[i] = elem); } } }) : function( elem, context, xml ) { input[0] = elem; matcher( input, null, xml, results ); return !results.pop(); }; }), "has": markFunction(function( selector ) { return function( elem ) { return Sizzle( selector, elem ).length > 0; }; }), "contains": markFunction(function( text ) { return function( elem ) { return ( elem.textContent || elem.innerText || getText( elem ) ).indexOf( text ) > -1; }; }), // "Whether an element is represented by a :lang() selector // is based solely on the element's language value // being equal to the identifier C, // or beginning with the identifier C immediately followed by "-". // The matching of C against the element's language value is performed case-insensitively. // The identifier C does not have to be a valid language name." // http://www.w3.org/TR/selectors/#lang-pseudo "lang": markFunction( function( lang ) { // lang value must be a valid identifider if ( !ridentifier.test(lang || "") ) { Sizzle.error( "unsupported lang: " + lang ); } lang = lang.replace( runescape, funescape ).toLowerCase(); return function( elem ) { var elemLang; do { if ( (elemLang = documentIsXML ? elem.getAttribute("xml:lang") || elem.getAttribute("lang") : elem.lang) ) { elemLang = elemLang.toLowerCase(); return elemLang === lang || elemLang.indexOf( lang + "-" ) === 0; } } while ( (elem = elem.parentNode) && elem.nodeType === 1 ); return false; }; }), // Miscellaneous "target": function( elem ) { var hash = window.location && window.location.hash; return hash && hash.slice( 1 ) === elem.id; }, "root": function( elem ) { return elem === docElem; }, "focus": function( elem ) { return elem === document.activeElement && (!document.hasFocus || document.hasFocus()) && !!(elem.type || elem.href || ~elem.tabIndex); }, // Boolean properties "enabled": function( elem ) { return elem.disabled === false; }, "disabled": function( elem ) { return elem.disabled === true; }, "checked": function( elem ) { // In CSS3, :checked should return both checked and selected elements // http://www.w3.org/TR/2011/REC-css3-selectors-20110929/#checked var nodeName = elem.nodeName.toLowerCase(); return (nodeName === "input" && !!elem.checked) || (nodeName === "option" && !!elem.selected); }, "selected": function( elem ) { // Accessing this property makes selected-by-default // options in Safari work properly if ( elem.parentNode ) { elem.parentNode.selectedIndex; } return elem.selected === true; }, // Contents "empty": function( elem ) { // http://www.w3.org/TR/selectors/#empty-pseudo // :empty is only affected by element nodes and content nodes(including text(3), cdata(4)), // not comment, processing instructions, or others // Thanks to Diego Perini for the nodeName shortcut // Greater than "@" means alpha characters (specifically not starting with "#" or "?") for ( elem = elem.firstChild; elem; elem = elem.nextSibling ) { if ( elem.nodeName > "@" || elem.nodeType === 3 || elem.nodeType === 4 ) { return false; } } return true; }, "parent": function( elem ) { return !Expr.pseudos["empty"]( elem ); }, // Element/input types "header": function( elem ) { return rheader.test( elem.nodeName ); }, "input": function( elem ) { return rinputs.test( elem.nodeName ); }, "button": function( elem ) { var name = elem.nodeName.toLowerCase(); return name === "input" && elem.type === "button" || name === "button"; }, "text": function( elem ) { var attr; // IE6 and 7 will map elem.type to 'text' for new HTML5 types (search, etc) // use getAttribute instead to test this case return elem.nodeName.toLowerCase() === "input" && elem.type === "text" && ( (attr = elem.getAttribute("type")) == null || attr.toLowerCase() === elem.type ); }, // Position-in-collection "first": createPositionalPseudo(function() { return [ 0 ]; }), "last": createPositionalPseudo(function( matchIndexes, length ) { return [ length - 1 ]; }), "eq": createPositionalPseudo(function( matchIndexes, length, argument ) { return [ argument < 0 ? argument + length : argument ]; }), "even": createPositionalPseudo(function( matchIndexes, length ) { var i = 0; for ( ; i < length; i += 2 ) { matchIndexes.push( i ); } return matchIndexes; }), "odd": createPositionalPseudo(function( matchIndexes, length ) { var i = 1; for ( ; i < length; i += 2 ) { matchIndexes.push( i ); } return matchIndexes; }), "lt": createPositionalPseudo(function( matchIndexes, length, argument ) { var i = argument < 0 ? argument + length : argument; for ( ; --i >= 0; ) { matchIndexes.push( i ); } return matchIndexes; }), "gt": createPositionalPseudo(function( matchIndexes, length, argument ) { var i = argument < 0 ? argument + length : argument; for ( ; ++i < length; ) { matchIndexes.push( i ); } return matchIndexes; }) } }; // Add button/input type pseudos for ( i in { radio: true, checkbox: true, file: true, password: true, image: true } ) { Expr.pseudos[ i ] = createInputPseudo( i ); } for ( i in { submit: true, reset: true } ) { Expr.pseudos[ i ] = createButtonPseudo( i ); } function tokenize( selector, parseOnly ) { var matched, match, tokens, type, soFar, groups, preFilters, cached = tokenCache[ selector + " " ]; if ( cached ) { return parseOnly ? 0 : cached.slice( 0 ); } soFar = selector; groups = []; preFilters = Expr.preFilter; while ( soFar ) { // Comma and first run if ( !matched || (match = rcomma.exec( soFar )) ) { if ( match ) { // Don't consume trailing commas as valid soFar = soFar.slice( match[0].length ) || soFar; } groups.push( tokens = [] ); } matched = false; // Combinators if ( (match = rcombinators.exec( soFar )) ) { matched = match.shift(); tokens.push( { value: matched, // Cast descendant combinators to space type: match[0].replace( rtrim, " " ) } ); soFar = soFar.slice( matched.length ); } // Filters for ( type in Expr.filter ) { if ( (match = matchExpr[ type ].exec( soFar )) && (!preFilters[ type ] || (match = preFilters[ type ]( match ))) ) { matched = match.shift(); tokens.push( { value: matched, type: type, matches: match } ); soFar = soFar.slice( matched.length ); } } if ( !matched ) { break; } } // Return the length of the invalid excess // if we're just parsing // Otherwise, throw an error or return tokens return parseOnly ? soFar.length : soFar ? Sizzle.error( selector ) : // Cache the tokens tokenCache( selector, groups ).slice( 0 ); } function toSelector( tokens ) { var i = 0, len = tokens.length, selector = ""; for ( ; i < len; i++ ) { selector += tokens[i].value; } return selector; } function addCombinator( matcher, combinator, base ) { var dir = combinator.dir, checkNonElements = base && dir === "parentNode", doneName = done++; return combinator.first ? // Check against closest ancestor/preceding element function( elem, context, xml ) { while ( (elem = elem[ dir ]) ) { if ( elem.nodeType === 1 || checkNonElements ) { return matcher( elem, context, xml ); } } } : // Check against all ancestor/preceding elements function( elem, context, xml ) { var data, cache, outerCache, dirkey = dirruns + " " + doneName; // We can't set arbitrary data on XML nodes, so they don't benefit from dir caching if ( xml ) { while ( (elem = elem[ dir ]) ) { if ( elem.nodeType === 1 || checkNonElements ) { if ( matcher( elem, context, xml ) ) { return true; } } } } else { while ( (elem = elem[ dir ]) ) { if ( elem.nodeType === 1 || checkNonElements ) { outerCache = elem[ expando ] || (elem[ expando ] = {}); if ( (cache = outerCache[ dir ]) && cache[0] === dirkey ) { if ( (data = cache[1]) === true || data === cachedruns ) { return data === true; } } else { cache = outerCache[ dir ] = [ dirkey ]; cache[1] = matcher( elem, context, xml ) || cachedruns; if ( cache[1] === true ) { return true; } } } } } }; } function elementMatcher( matchers ) { return matchers.length > 1 ? function( elem, context, xml ) { var i = matchers.length; while ( i-- ) { if ( !matchers[i]( elem, context, xml ) ) { return false; } } return true; } : matchers[0]; } function condense( unmatched, map, filter, context, xml ) { var elem, newUnmatched = [], i = 0, len = unmatched.length, mapped = map != null; for ( ; i < len; i++ ) { if ( (elem = unmatched[i]) ) { if ( !filter || filter( elem, context, xml ) ) { newUnmatched.push( elem ); if ( mapped ) { map.push( i ); } } } } return newUnmatched; } function setMatcher( preFilter, selector, matcher, postFilter, postFinder, postSelector ) { if ( postFilter && !postFilter[ expando ] ) { postFilter = setMatcher( postFilter ); } if ( postFinder && !postFinder[ expando ] ) { postFinder = setMatcher( postFinder, postSelector ); } return markFunction(function( seed, results, context, xml ) { var temp, i, elem, preMap = [], postMap = [], preexisting = results.length, // Get initial elements from seed or context elems = seed || multipleContexts( selector || "*", context.nodeType ? [ context ] : context, [] ), // Prefilter to get matcher input, preserving a map for seed-results synchronization matcherIn = preFilter && ( seed || !selector ) ? condense( elems, preMap, preFilter, context, xml ) : elems, matcherOut = matcher ? // If we have a postFinder, or filtered seed, or non-seed postFilter or preexisting results, postFinder || ( seed ? preFilter : preexisting || postFilter ) ? // ...intermediate processing is necessary [] : // ...otherwise use results directly results : matcherIn; // Find primary matches if ( matcher ) { matcher( matcherIn, matcherOut, context, xml ); } // Apply postFilter if ( postFilter ) { temp = condense( matcherOut, postMap ); postFilter( temp, [], context, xml ); // Un-match failing elements by moving them back to matcherIn i = temp.length; while ( i-- ) { if ( (elem = temp[i]) ) { matcherOut[ postMap[i] ] = !(matcherIn[ postMap[i] ] = elem); } } } if ( seed ) { if ( postFinder || preFilter ) { if ( postFinder ) { // Get the final matcherOut by condensing this intermediate into postFinder contexts temp = []; i = matcherOut.length; while ( i-- ) { if ( (elem = matcherOut[i]) ) { // Restore matcherIn since elem is not yet a final match temp.push( (matcherIn[i] = elem) ); } } postFinder( null, (matcherOut = []), temp, xml ); } // Move matched elements from seed to results to keep them synchronized i = matcherOut.length; while ( i-- ) { if ( (elem = matcherOut[i]) && (temp = postFinder ? indexOf.call( seed, elem ) : preMap[i]) > -1 ) { seed[temp] = !(results[temp] = elem); } } } // Add elements to results, through postFinder if defined } else { matcherOut = condense( matcherOut === results ? matcherOut.splice( preexisting, matcherOut.length ) : matcherOut ); if ( postFinder ) { postFinder( null, results, matcherOut, xml ); } else { push.apply( results, matcherOut ); } } }); } function matcherFromTokens( tokens ) { var checkContext, matcher, j, len = tokens.length, leadingRelative = Expr.relative[ tokens[0].type ], implicitRelative = leadingRelative || Expr.relative[" "], i = leadingRelative ? 1 : 0, // The foundational matcher ensures that elements are reachable from top-level context(s) matchContext = addCombinator( function( elem ) { return elem === checkContext; }, implicitRelative, true ), matchAnyContext = addCombinator( function( elem ) { return indexOf.call( checkContext, elem ) > -1; }, implicitRelative, true ), matchers = [ function( elem, context, xml ) { return ( !leadingRelative && ( xml || context !== outermostContext ) ) || ( (checkContext = context).nodeType ? matchContext( elem, context, xml ) : matchAnyContext( elem, context, xml ) ); } ]; for ( ; i < len; i++ ) { if ( (matcher = Expr.relative[ tokens[i].type ]) ) { matchers = [ addCombinator(elementMatcher( matchers ), matcher) ]; } else { matcher = Expr.filter[ tokens[i].type ].apply( null, tokens[i].matches ); // Return special upon seeing a positional matcher if ( matcher[ expando ] ) { // Find the next relative operator (if any) for proper handling j = ++i; for ( ; j < len; j++ ) { if ( Expr.relative[ tokens[j].type ] ) { break; } } return setMatcher( i > 1 && elementMatcher( matchers ), i > 1 && toSelector( tokens.slice( 0, i - 1 ) ).replace( rtrim, "$1" ), matcher, i < j && matcherFromTokens( tokens.slice( i, j ) ), j < len && matcherFromTokens( (tokens = tokens.slice( j )) ), j < len && toSelector( tokens ) ); } matchers.push( matcher ); } } return elementMatcher( matchers ); } function matcherFromGroupMatchers( elementMatchers, setMatchers ) { // A counter to specify which element is currently being matched var matcherCachedRuns = 0, bySet = setMatchers.length > 0, byElement = elementMatchers.length > 0, superMatcher = function( seed, context, xml, results, expandContext ) { var elem, j, matcher, setMatched = [], matchedCount = 0, i = "0", unmatched = seed && [], outermost = expandContext != null, contextBackup = outermostContext, // We must always have either seed elements or context elems = seed || byElement && Expr.find["TAG"]( "*", expandContext && context.parentNode || context ), // Use integer dirruns iff this is the outermost matcher dirrunsUnique = (dirruns += contextBackup == null ? 1 : Math.random() || 0.1); if ( outermost ) { outermostContext = context !== document && context; cachedruns = matcherCachedRuns; } // Add elements passing elementMatchers directly to results // Keep `i` a string if there are no elements so `matchedCount` will be "00" below for ( ; (elem = elems[i]) != null; i++ ) { if ( byElement && elem ) { j = 0; while ( (matcher = elementMatchers[j++]) ) { if ( matcher( elem, context, xml ) ) { results.push( elem ); break; } } if ( outermost ) { dirruns = dirrunsUnique; cachedruns = ++matcherCachedRuns; } } // Track unmatched elements for set filters if ( bySet ) { // They will have gone through all possible matchers if ( (elem = !matcher && elem) ) { matchedCount--; } // Lengthen the array for every element, matched or not if ( seed ) { unmatched.push( elem ); } } } // Apply set filters to unmatched elements matchedCount += i; if ( bySet && i !== matchedCount ) { j = 0; while ( (matcher = setMatchers[j++]) ) { matcher( unmatched, setMatched, context, xml ); } if ( seed ) { // Reintegrate element matches to eliminate the need for sorting if ( matchedCount > 0 ) { while ( i-- ) { if ( !(unmatched[i] || setMatched[i]) ) { setMatched[i] = pop.call( results ); } } } // Discard index placeholder values to get only actual matches setMatched = condense( setMatched ); } // Add matches to results push.apply( results, setMatched ); // Seedless set matches succeeding multiple successful matchers stipulate sorting if ( outermost && !seed && setMatched.length > 0 && ( matchedCount + setMatchers.length ) > 1 ) { Sizzle.uniqueSort( results ); } } // Override manipulation of globals by nested matchers if ( outermost ) { dirruns = dirrunsUnique; outermostContext = contextBackup; } return unmatched; }; return bySet ? markFunction( superMatcher ) : superMatcher; } compile = Sizzle.compile = function( selector, group /* Internal Use Only */ ) { var i, setMatchers = [], elementMatchers = [], cached = compilerCache[ selector + " " ]; if ( !cached ) { // Generate a function of recursive functions that can be used to check each element if ( !group ) { group = tokenize( selector ); } i = group.length; while ( i-- ) { cached = matcherFromTokens( group[i] ); if ( cached[ expando ] ) { setMatchers.push( cached ); } else { elementMatchers.push( cached ); } } // Cache the compiled function cached = compilerCache( selector, matcherFromGroupMatchers( elementMatchers, setMatchers ) ); } return cached; }; function multipleContexts( selector, contexts, results ) { var i = 0, len = contexts.length; for ( ; i < len; i++ ) { Sizzle( selector, contexts[i], results ); } return results; } function select( selector, context, results, seed ) { var i, tokens, token, type, find, match = tokenize( selector ); if ( !seed ) { // Try to minimize operations if there is only one group if ( match.length === 1 ) { // Take a shortcut and set the context if the root selector is an ID tokens = match[0] = match[0].slice( 0 ); if ( tokens.length > 2 && (token = tokens[0]).type === "ID" && context.nodeType === 9 && !documentIsXML && Expr.relative[ tokens[1].type ] ) { context = Expr.find["ID"]( token.matches[0].replace( runescape, funescape ), context )[0]; if ( !context ) { return results; } selector = selector.slice( tokens.shift().value.length ); } // Fetch a seed set for right-to-left matching i = matchExpr["needsContext"].test( selector ) ? 0 : tokens.length; while ( i-- ) { token = tokens[i]; // Abort if we hit a combinator if ( Expr.relative[ (type = token.type) ] ) { break; } if ( (find = Expr.find[ type ]) ) { // Search, expanding context for leading sibling combinators if ( (seed = find( token.matches[0].replace( runescape, funescape ), rsibling.test( tokens[0].type ) && context.parentNode || context )) ) { // If seed is empty or no tokens remain, we can return early tokens.splice( i, 1 ); selector = seed.length && toSelector( tokens ); if ( !selector ) { push.apply( results, slice.call( seed, 0 ) ); return results; } break; } } } } } // Compile and execute a filtering function // Provide `match` to avoid retokenization if we modified the selector above compile( selector, match )( seed, context, documentIsXML, results, rsibling.test( selector ) ); return results; } // Deprecated Expr.pseudos["nth"] = Expr.pseudos["eq"]; // Easy API for creating new setFilters function setFilters() {} Expr.filters = setFilters.prototype = Expr.pseudos; Expr.setFilters = new setFilters(); // Initialize with the default document setDocument(); // Override sizzle attribute retrieval Sizzle.attr = jQuery.attr; jQuery.find = Sizzle; jQuery.expr = Sizzle.selectors; jQuery.expr[":"] = jQuery.expr.pseudos; jQuery.unique = Sizzle.uniqueSort; jQuery.text = Sizzle.getText; jQuery.isXMLDoc = Sizzle.isXML; jQuery.contains = Sizzle.contains; })( window ); var runtil = /Until$/, rparentsprev = /^(?:parents|prev(?:Until|All))/, isSimple = /^.[^:#\[\.,]*$/, rneedsContext = jQuery.expr.match.needsContext, // methods guaranteed to produce a unique set when starting from a unique set guaranteedUnique = { children: true, contents: true, next: true, prev: true }; jQuery.fn.extend({ find: function( selector ) { var i, ret, self, len = this.length; if ( typeof selector !== "string" ) { self = this; return this.pushStack( jQuery( selector ).filter(function() { for ( i = 0; i < len; i++ ) { if ( jQuery.contains( self[ i ], this ) ) { return true; } } }) ); } ret = []; for ( i = 0; i < len; i++ ) { jQuery.find( selector, this[ i ], ret ); } // Needed because $( selector, context ) becomes $( context ).find( selector ) ret = this.pushStack( len > 1 ? jQuery.unique( ret ) : ret ); ret.selector = ( this.selector ? this.selector + " " : "" ) + selector; return ret; }, has: function( target ) { var i, targets = jQuery( target, this ), len = targets.length; return this.filter(function() { for ( i = 0; i < len; i++ ) { if ( jQuery.contains( this, targets[i] ) ) { return true; } } }); }, not: function( selector ) { return this.pushStack( winnow(this, selector, false) ); }, filter: function( selector ) { return this.pushStack( winnow(this, selector, true) ); }, is: function( selector ) { return !!selector && ( typeof selector === "string" ? // If this is a positional/relative selector, check membership in the returned set // so $("p:first").is("p:last") won't return true for a doc with two "p". rneedsContext.test( selector ) ? jQuery( selector, this.context ).index( this[0] ) >= 0 : jQuery.filter( selector, this ).length > 0 : this.filter( selector ).length > 0 ); }, closest: function( selectors, context ) { var cur, i = 0, l = this.length, ret = [], pos = rneedsContext.test( selectors ) || typeof selectors !== "string" ? jQuery( selectors, context || this.context ) : 0; for ( ; i < l; i++ ) { cur = this[i]; while ( cur && cur.ownerDocument && cur !== context && cur.nodeType !== 11 ) { if ( pos ? pos.index(cur) > -1 : jQuery.find.matchesSelector(cur, selectors) ) { ret.push( cur ); break; } cur = cur.parentNode; } } return this.pushStack( ret.length > 1 ? jQuery.unique( ret ) : ret ); }, // Determine the position of an element within // the matched set of elements index: function( elem ) { // No argument, return index in parent if ( !elem ) { return ( this[0] && this[0].parentNode ) ? this.first().prevAll().length : -1; } // index in selector if ( typeof elem === "string" ) { return jQuery.inArray( this[0], jQuery( elem ) ); } // Locate the position of the desired element return jQuery.inArray( // If it receives a jQuery object, the first element is used elem.jquery ? elem[0] : elem, this ); }, add: function( selector, context ) { var set = typeof selector === "string" ? jQuery( selector, context ) : jQuery.makeArray( selector && selector.nodeType ? [ selector ] : selector ), all = jQuery.merge( this.get(), set ); return this.pushStack( jQuery.unique(all) ); }, addBack: function( selector ) { return this.add( selector == null ? this.prevObject : this.prevObject.filter(selector) ); } }); jQuery.fn.andSelf = jQuery.fn.addBack; function sibling( cur, dir ) { do { cur = cur[ dir ]; } while ( cur && cur.nodeType !== 1 ); return cur; } jQuery.each({ parent: function( elem ) { var parent = elem.parentNode; return parent && parent.nodeType !== 11 ? parent : null; }, parents: function( elem ) { return jQuery.dir( elem, "parentNode" ); }, parentsUntil: function( elem, i, until ) { return jQuery.dir( elem, "parentNode", until ); }, next: function( elem ) { return sibling( elem, "nextSibling" ); }, prev: function( elem ) { return sibling( elem, "previousSibling" ); }, nextAll: function( elem ) { return jQuery.dir( elem, "nextSibling" ); }, prevAll: function( elem ) { return jQuery.dir( elem, "previousSibling" ); }, nextUntil: function( elem, i, until ) { return jQuery.dir( elem, "nextSibling", until ); }, prevUntil: function( elem, i, until ) { return jQuery.dir( elem, "previousSibling", until ); }, siblings: function( elem ) { return jQuery.sibling( ( elem.parentNode || {} ).firstChild, elem ); }, children: function( elem ) { return jQuery.sibling( elem.firstChild ); }, contents: function( elem ) { return jQuery.nodeName( elem, "iframe" ) ? elem.contentDocument || elem.contentWindow.document : jQuery.merge( [], elem.childNodes ); } }, function( name, fn ) { jQuery.fn[ name ] = function( until, selector ) { var ret = jQuery.map( this, fn, until ); if ( !runtil.test( name ) ) { selector = until; } if ( selector && typeof selector === "string" ) { ret = jQuery.filter( selector, ret ); } ret = this.length > 1 && !guaranteedUnique[ name ] ? jQuery.unique( ret ) : ret; if ( this.length > 1 && rparentsprev.test( name ) ) { ret = ret.reverse(); } return this.pushStack( ret ); }; }); jQuery.extend({ filter: function( expr, elems, not ) { if ( not ) { expr = ":not(" + expr + ")"; } return elems.length === 1 ? jQuery.find.matchesSelector(elems[0], expr) ? [ elems[0] ] : [] : jQuery.find.matches(expr, elems); }, dir: function( elem, dir, until ) { var matched = [], cur = elem[ dir ]; while ( cur && cur.nodeType !== 9 && (until === undefined || cur.nodeType !== 1 || !jQuery( cur ).is( until )) ) { if ( cur.nodeType === 1 ) { matched.push( cur ); } cur = cur[dir]; } return matched; }, sibling: function( n, elem ) { var r = []; for ( ; n; n = n.nextSibling ) { if ( n.nodeType === 1 && n !== elem ) { r.push( n ); } } return r; } }); // Implement the identical functionality for filter and not function winnow( elements, qualifier, keep ) { // Can't pass null or undefined to indexOf in Firefox 4 // Set to 0 to skip string check qualifier = qualifier || 0; if ( jQuery.isFunction( qualifier ) ) { return jQuery.grep(elements, function( elem, i ) { var retVal = !!qualifier.call( elem, i, elem ); return retVal === keep; }); } else if ( qualifier.nodeType ) { return jQuery.grep(elements, function( elem ) { return ( elem === qualifier ) === keep; }); } else if ( typeof qualifier === "string" ) { var filtered = jQuery.grep(elements, function( elem ) { return elem.nodeType === 1; }); if ( isSimple.test( qualifier ) ) { return jQuery.filter(qualifier, filtered, !keep); } else { qualifier = jQuery.filter( qualifier, filtered ); } } return jQuery.grep(elements, function( elem ) { return ( jQuery.inArray( elem, qualifier ) >= 0 ) === keep; }); } function createSafeFragment( document ) { var list = nodeNames.split( "|" ), safeFrag = document.createDocumentFragment(); if ( safeFrag.createElement ) { while ( list.length ) { safeFrag.createElement( list.pop() ); } } return safeFrag; } var nodeNames = "abbr|article|aside|audio|bdi|canvas|data|datalist|details|figcaption|figure|footer|" + "header|hgroup|mark|meter|nav|output|progress|section|summary|time|video", rinlinejQuery = / jQuery\d+="(?:null|\d+)"/g, rnoshimcache = new RegExp("<(?:" + nodeNames + ")[\\s/>]", "i"), rleadingWhitespace = /^\s+/, rxhtmlTag = /<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/gi, rtagName = /<([\w:]+)/, rtbody = /<tbody/i, rhtml = /<|&#?\w+;/, rnoInnerhtml = /<(?:script|style|link)/i, manipulation_rcheckableType = /^(?:checkbox|radio)$/i, // checked="checked" or checked rchecked = /checked\s*(?:[^=]|=\s*.checked.)/i, rscriptType = /^$|\/(?:java|ecma)script/i, rscriptTypeMasked = /^true\/(.*)/, rcleanScript = /^\s*<!(?:\[CDATA\[|--)|(?:\]\]|--)>\s*$/g, // We have to close these tags to support XHTML (#13200) wrapMap = { 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>" ], // IE6-8 can't serialize link, script, style, or any html5 (NoScope) tags, // unless wrapped in a div with non-breaking characters in front of it. _default: jQuery.support.htmlSerialize ? [ 0, "", "" ] : [ 1, "X<div>", "</div>" ] }, safeFragment = createSafeFragment( document ), fragmentDiv = safeFragment.appendChild( document.createElement("div") ); wrapMap.optgroup = wrapMap.option; wrapMap.tbody = wrapMap.tfoot = wrapMap.colgroup = wrapMap.caption = wrapMap.thead; wrapMap.th = wrapMap.td; jQuery.fn.extend({ text: function( value ) { return jQuery.access( this, function( value ) { return value === undefined ? jQuery.text( this ) : this.empty().append( ( this[0] && this[0].ownerDocument || document ).createTextNode( value ) ); }, null, value, arguments.length ); }, wrapAll: function( html ) { if ( jQuery.isFunction( html ) ) { return this.each(function(i) { jQuery(this).wrapAll( html.call(this, i) ); }); } if ( this[0] ) { // The elements to wrap the target around var wrap = jQuery( html, this[0].ownerDocument ).eq(0).clone(true); if ( this[0].parentNode ) { wrap.insertBefore( this[0] ); } wrap.map(function() { var elem = this; while ( elem.firstChild && elem.firstChild.nodeType === 1 ) { elem = elem.firstChild; } return elem; }).append( this ); } return this; }, wrapInner: function( html ) { if ( jQuery.isFunction( html ) ) { return this.each(function(i) { jQuery(this).wrapInner( html.call(this, i) ); }); } return this.each(function() { var self = jQuery( this ), contents = self.contents(); if ( contents.length ) { contents.wrapAll( html ); } else { self.append( html ); } }); }, wrap: function( html ) { var isFunction = jQuery.isFunction( html ); return this.each(function(i) { jQuery( this ).wrapAll( isFunction ? html.call(this, i) : html ); }); }, unwrap: function() { return this.parent().each(function() { if ( !jQuery.nodeName( this, "body" ) ) { jQuery( this ).replaceWith( this.childNodes ); } }).end(); }, append: function() { return this.domManip(arguments, true, function( elem ) { if ( this.nodeType === 1 || this.nodeType === 11 || this.nodeType === 9 ) { this.appendChild( elem ); } }); }, prepend: function() { return this.domManip(arguments, true, function( elem ) { if ( this.nodeType === 1 || this.nodeType === 11 || this.nodeType === 9 ) { this.insertBefore( elem, this.firstChild ); } }); }, before: function() { return this.domManip( arguments, false, function( elem ) { if ( this.parentNode ) { this.parentNode.insertBefore( elem, this ); } }); }, after: function() { return this.domManip( arguments, false, function( elem ) { if ( this.parentNode ) { this.parentNode.insertBefore( elem, this.nextSibling ); } }); }, // keepData is for internal use only--do not document remove: function( selector, keepData ) { var elem, i = 0; for ( ; (elem = this[i]) != null; i++ ) { if ( !selector || jQuery.filter( selector, [ elem ] ).length > 0 ) { if ( !keepData && elem.nodeType === 1 ) { jQuery.cleanData( getAll( elem ) ); } if ( elem.parentNode ) { if ( keepData && jQuery.contains( elem.ownerDocument, elem ) ) { setGlobalEval( getAll( elem, "script" ) ); } elem.parentNode.removeChild( elem ); } } } return this; }, empty: function() { var elem, i = 0; for ( ; (elem = this[i]) != null; i++ ) { // Remove element nodes and prevent memory leaks if ( elem.nodeType === 1 ) { jQuery.cleanData( getAll( elem, false ) ); } // Remove any remaining nodes while ( elem.firstChild ) { elem.removeChild( elem.firstChild ); } // If this is a select, ensure that it displays empty (#12336) // Support: IE<9 if ( elem.options && jQuery.nodeName( elem, "select" ) ) { elem.options.length = 0; } } return this; }, clone: function( dataAndEvents, deepDataAndEvents ) { dataAndEvents = dataAndEvents == null ? false : dataAndEvents; deepDataAndEvents = deepDataAndEvents == null ? dataAndEvents : deepDataAndEvents; return this.map( function () { return jQuery.clone( this, dataAndEvents, deepDataAndEvents ); }); }, html: function( value ) { return jQuery.access( this, function( value ) { var elem = this[0] || {}, i = 0, l = this.length; if ( value === undefined ) { return elem.nodeType === 1 ? elem.innerHTML.replace( rinlinejQuery, "" ) : undefined; } // See if we can take a shortcut and just use innerHTML if ( typeof value === "string" && !rnoInnerhtml.test( value ) && ( jQuery.support.htmlSerialize || !rnoshimcache.test( value ) ) && ( jQuery.support.leadingWhitespace || !rleadingWhitespace.test( value ) ) && !wrapMap[ ( rtagName.exec( value ) || ["", ""] )[1].toLowerCase() ] ) { value = value.replace( rxhtmlTag, "<$1></$2>" ); try { for (; i < l; i++ ) { // Remove element nodes and prevent memory leaks elem = this[i] || {}; if ( elem.nodeType === 1 ) { jQuery.cleanData( getAll( elem, false ) ); elem.innerHTML = value; } } elem = 0; // If using innerHTML throws an exception, use the fallback method } catch(e) {} } if ( elem ) { this.empty().append( value ); } }, null, value, arguments.length ); }, replaceWith: function( value ) { var isFunc = jQuery.isFunction( value ); // Make sure that the elements are removed from the DOM before they are inserted // this can help fix replacing a parent with child elements if ( !isFunc && typeof value !== "string" ) { value = jQuery( value ).not( this ).detach(); } return this.domManip( [ value ], true, function( elem ) { var next = this.nextSibling, parent = this.parentNode; if ( parent ) { jQuery( this ).remove(); parent.insertBefore( elem, next ); } }); }, detach: function( selector ) { return this.remove( selector, true ); }, domManip: function( args, table, callback ) { // Flatten any nested arrays args = core_concat.apply( [], args ); var first, node, hasScripts, scripts, doc, fragment, i = 0, l = this.length, set = this, iNoClone = l - 1, value = args[0], isFunction = jQuery.isFunction( value ); // We can't cloneNode fragments that contain checked, in WebKit if ( isFunction || !( l <= 1 || typeof value !== "string" || jQuery.support.checkClone || !rchecked.test( value ) ) ) { return this.each(function( index ) { var self = set.eq( index ); if ( isFunction ) { args[0] = value.call( this, index, table ? self.html() : undefined ); } self.domManip( args, table, callback ); }); } if ( l ) { fragment = jQuery.buildFragment( args, this[ 0 ].ownerDocument, false, this ); first = fragment.firstChild; if ( fragment.childNodes.length === 1 ) { fragment = first; } if ( first ) { table = table && jQuery.nodeName( first, "tr" ); scripts = jQuery.map( getAll( fragment, "script" ), disableScript ); hasScripts = scripts.length; // Use the original fragment for the last item instead of the first because it can end up // being emptied incorrectly in certain situations (#8070). for ( ; i < l; i++ ) { node = fragment; if ( i !== iNoClone ) { node = jQuery.clone( node, true, true ); // Keep references to cloned scripts for later restoration if ( hasScripts ) { jQuery.merge( scripts, getAll( node, "script" ) ); } } callback.call( table && jQuery.nodeName( this[i], "table" ) ? findOrAppend( this[i], "tbody" ) : this[i], node, i ); } if ( hasScripts ) { doc = scripts[ scripts.length - 1 ].ownerDocument; // Reenable scripts jQuery.map( scripts, restoreScript ); // Evaluate executable scripts on first document insertion for ( i = 0; i < hasScripts; i++ ) { node = scripts[ i ]; if ( rscriptType.test( node.type || "" ) && !jQuery._data( node, "globalEval" ) && jQuery.contains( doc, node ) ) { if ( node.src ) { // Hope ajax is available... jQuery.ajax({ url: node.src, type: "GET", dataType: "script", async: false, global: false, "throws": true }); } else { jQuery.globalEval( ( node.text || node.textContent || node.innerHTML || "" ).replace( rcleanScript, "" ) ); } } } } // Fix #11809: Avoid leaking memory fragment = first = null; } } return this; } }); function findOrAppend( elem, tag ) { return elem.getElementsByTagName( tag )[0] || elem.appendChild( elem.ownerDocument.createElement( tag ) ); } // Replace/restore the type attribute of script elements for safe DOM manipulation function disableScript( elem ) { var attr = elem.getAttributeNode("type"); elem.type = ( attr && attr.specified ) + "/" + elem.type; return elem; } function restoreScript( elem ) { var match = rscriptTypeMasked.exec( elem.type ); if ( match ) { elem.type = match[1]; } else { elem.removeAttribute("type"); } return elem; } // Mark scripts as having already been evaluated function setGlobalEval( elems, refElements ) { var elem, i = 0; for ( ; (elem = elems[i]) != null; i++ ) { jQuery._data( elem, "globalEval", !refElements || jQuery._data( refElements[i], "globalEval" ) ); } } function cloneCopyEvent( src, dest ) { if ( dest.nodeType !== 1 || !jQuery.hasData( src ) ) { return; } var type, i, l, oldData = jQuery._data( src ), curData = jQuery._data( dest, oldData ), events = oldData.events; if ( events ) { delete curData.handle; curData.events = {}; for ( type in events ) { for ( i = 0, l = events[ type ].length; i < l; i++ ) { jQuery.event.add( dest, type, events[ type ][ i ] ); } } } // make the cloned public data object a copy from the original if ( curData.data ) { curData.data = jQuery.extend( {}, curData.data ); } } function fixCloneNodeIssues( src, dest ) { var nodeName, e, data; // We do not need to do anything for non-Elements if ( dest.nodeType !== 1 ) { return; } nodeName = dest.nodeName.toLowerCase(); // IE6-8 copies events bound via attachEvent when using cloneNode. if ( !jQuery.support.noCloneEvent && dest[ jQuery.expando ] ) { data = jQuery._data( dest ); for ( e in data.events ) { jQuery.removeEvent( dest, e, data.handle ); } // Event data gets referenced instead of copied if the expando gets copied too dest.removeAttribute( jQuery.expando ); } // IE blanks contents when cloning scripts, and tries to evaluate newly-set text if ( nodeName === "script" && dest.text !== src.text ) { disableScript( dest ).text = src.text; restoreScript( dest ); // IE6-10 improperly clones children of object elements using classid. // IE10 throws NoModificationAllowedError if parent is null, #12132. } else if ( nodeName === "object" ) { if ( dest.parentNode ) { dest.outerHTML = src.outerHTML; } // This path appears unavoidable for IE9. When cloning an object // element in IE9, the outerHTML strategy above is not sufficient. // If the src has innerHTML and the destination does not, // copy the src.innerHTML into the dest.innerHTML. #10324 if ( jQuery.support.html5Clone && ( src.innerHTML && !jQuery.trim(dest.innerHTML) ) ) { dest.innerHTML = src.innerHTML; } } else if ( nodeName === "input" && manipulation_rcheckableType.test( src.type ) ) { // IE6-8 fails to persist the checked state of a cloned checkbox // or radio button. Worse, IE6-7 fail to give the cloned element // a checked appearance if the defaultChecked value isn't also set dest.defaultChecked = dest.checked = src.checked; // IE6-7 get confused and end up setting the value of a cloned // checkbox/radio button to an empty string instead of "on" if ( dest.value !== src.value ) { dest.value = src.value; } // IE6-8 fails to return the selected option to the default selected // state when cloning options } else if ( nodeName === "option" ) { dest.defaultSelected = dest.selected = src.defaultSelected; // IE6-8 fails to set the defaultValue to the correct value when // cloning other types of input fields } else if ( nodeName === "input" || nodeName === "textarea" ) { dest.defaultValue = src.defaultValue; } } jQuery.each({ appendTo: "append", prependTo: "prepend", insertBefore: "before", insertAfter: "after", replaceAll: "replaceWith" }, function( name, original ) { jQuery.fn[ name ] = function( selector ) { var elems, i = 0, ret = [], insert = jQuery( selector ), last = insert.length - 1; for ( ; i <= last; i++ ) { elems = i === last ? this : this.clone(true); jQuery( insert[i] )[ original ]( elems ); // Modern browsers can apply jQuery collections as arrays, but oldIE needs a .get() core_push.apply( ret, elems.get() ); } return this.pushStack( ret ); }; }); function getAll( context, tag ) { var elems, elem, i = 0, found = typeof context.getElementsByTagName !== core_strundefined ? context.getElementsByTagName( tag || "*" ) : typeof context.querySelectorAll !== core_strundefined ? context.querySelectorAll( tag || "*" ) : undefined; if ( !found ) { for ( found = [], elems = context.childNodes || context; (elem = elems[i]) != null; i++ ) { if ( !tag || jQuery.nodeName( elem, tag ) ) { found.push( elem ); } else { jQuery.merge( found, getAll( elem, tag ) ); } } } return tag === undefined || tag && jQuery.nodeName( context, tag ) ? jQuery.merge( [ context ], found ) : found; } // Used in buildFragment, fixes the defaultChecked property function fixDefaultChecked( elem ) { if ( manipulation_rcheckableType.test( elem.type ) ) { elem.defaultChecked = elem.checked; } } jQuery.extend({ clone: function( elem, dataAndEvents, deepDataAndEvents ) { var destElements, node, clone, i, srcElements, inPage = jQuery.contains( elem.ownerDocument, elem ); if ( jQuery.support.html5Clone || jQuery.isXMLDoc(elem) || !rnoshimcache.test( "<" + elem.nodeName + ">" ) ) { clone = elem.cloneNode( true ); // IE<=8 does not properly clone detached, unknown element nodes } else { fragmentDiv.innerHTML = elem.outerHTML; fragmentDiv.removeChild( clone = fragmentDiv.firstChild ); } if ( (!jQuery.support.noCloneEvent || !jQuery.support.noCloneChecked) && (elem.nodeType === 1 || elem.nodeType === 11) && !jQuery.isXMLDoc(elem) ) { // We eschew Sizzle here for performance reasons: http://jsperf.com/getall-vs-sizzle/2 destElements = getAll( clone ); srcElements = getAll( elem ); // Fix all IE cloning issues for ( i = 0; (node = srcElements[i]) != null; ++i ) { // Ensure that the destination node is not null; Fixes #9587 if ( destElements[i] ) { fixCloneNodeIssues( node, destElements[i] ); } } } // Copy the events from the original to the clone if ( dataAndEvents ) { if ( deepDataAndEvents ) { srcElements = srcElements || getAll( elem ); destElements = destElements || getAll( clone ); for ( i = 0; (node = srcElements[i]) != null; i++ ) { cloneCopyEvent( node, destElements[i] ); } } else { cloneCopyEvent( elem, clone ); } } // Preserve script evaluation history destElements = getAll( clone, "script" ); if ( destElements.length > 0 ) { setGlobalEval( destElements, !inPage && getAll( elem, "script" ) ); } destElements = srcElements = node = null; // Return the cloned set return clone; }, buildFragment: function( elems, context, scripts, selection ) { var j, elem, contains, tmp, tag, tbody, wrap, l = elems.length, // Ensure a safe fragment safe = createSafeFragment( context ), nodes = [], i = 0; for ( ; i < l; i++ ) { elem = elems[ i ]; if ( elem || elem === 0 ) { // Add nodes directly if ( jQuery.type( elem ) === "object" ) { jQuery.merge( nodes, elem.nodeType ? [ elem ] : elem ); // Convert non-html into a text node } else if ( !rhtml.test( elem ) ) { nodes.push( context.createTextNode( elem ) ); // Convert html into DOM nodes } else { tmp = tmp || safe.appendChild( context.createElement("div") ); // Deserialize a standard representation tag = ( rtagName.exec( elem ) || ["", ""] )[1].toLowerCase(); wrap = wrapMap[ tag ] || wrapMap._default; tmp.innerHTML = wrap[1] + elem.replace( rxhtmlTag, "<$1></$2>" ) + wrap[2]; // Descend through wrappers to the right content j = wrap[0]; while ( j-- ) { tmp = tmp.lastChild; } // Manually add leading whitespace removed by IE if ( !jQuery.support.leadingWhitespace && rleadingWhitespace.test( elem ) ) { nodes.push( context.createTextNode( rleadingWhitespace.exec( elem )[0] ) ); } // Remove IE's autoinserted <tbody> from table fragments if ( !jQuery.support.tbody ) { // String was a <table>, *may* have spurious <tbody> elem = tag === "table" && !rtbody.test( elem ) ? tmp.firstChild : // String was a bare <thead> or <tfoot> wrap[1] === "<table>" && !rtbody.test( elem ) ? tmp : 0; j = elem && elem.childNodes.length; while ( j-- ) { if ( jQuery.nodeName( (tbody = elem.childNodes[j]), "tbody" ) && !tbody.childNodes.length ) { elem.removeChild( tbody ); } } } jQuery.merge( nodes, tmp.childNodes ); // Fix #12392 for WebKit and IE > 9 tmp.textContent = ""; // Fix #12392 for oldIE while ( tmp.firstChild ) { tmp.removeChild( tmp.firstChild ); } // Remember the top-level container for proper cleanup tmp = safe.lastChild; } } } // Fix #11356: Clear elements from fragment if ( tmp ) { safe.removeChild( tmp ); } // Reset defaultChecked for any radios and checkboxes // about to be appended to the DOM in IE 6/7 (#8060) if ( !jQuery.support.appendChecked ) { jQuery.grep( getAll( nodes, "input" ), fixDefaultChecked ); } i = 0; while ( (elem = nodes[ i++ ]) ) { // #4087 - If origin and destination elements are the same, and this is // that element, do not do anything if ( selection && jQuery.inArray( elem, selection ) !== -1 ) { continue; } contains = jQuery.contains( elem.ownerDocument, elem ); // Append to fragment tmp = getAll( safe.appendChild( elem ), "script" ); // Preserve script evaluation history if ( contains ) { setGlobalEval( tmp ); } // Capture executables if ( scripts ) { j = 0; while ( (elem = tmp[ j++ ]) ) { if ( rscriptType.test( elem.type || "" ) ) { scripts.push( elem ); } } } } tmp = null; return safe; }, cleanData: function( elems, /* internal */ acceptData ) { var elem, type, id, data, i = 0, internalKey = jQuery.expando, cache = jQuery.cache, deleteExpando = jQuery.support.deleteExpando, special = jQuery.event.special; for ( ; (elem = elems[i]) != null; i++ ) { if ( acceptData || jQuery.acceptData( elem ) ) { id = elem[ internalKey ]; data = id && cache[ id ]; if ( data ) { if ( data.events ) { for ( type in data.events ) { if ( special[ type ] ) { jQuery.event.remove( elem, type ); // This is a shortcut to avoid jQuery.event.remove's overhead } else { jQuery.removeEvent( elem, type, data.handle ); } } } // Remove cache only if it was not already removed by jQuery.event.remove if ( cache[ id ] ) { delete cache[ id ]; // IE does not allow us to delete expando properties from nodes, // nor does it have a removeAttribute function on Document nodes; // we must handle all of these cases if ( deleteExpando ) { delete elem[ internalKey ]; } else if ( typeof elem.removeAttribute !== core_strundefined ) { elem.removeAttribute( internalKey ); } else { elem[ internalKey ] = null; } core_deletedIds.push( id ); } } } } } }); var iframe, getStyles, curCSS, ralpha = /alpha\([^)]*\)/i, ropacity = /opacity\s*=\s*([^)]*)/, rposition = /^(top|right|bottom|left)$/, // swappable if display is none or starts with table except "table", "table-cell", or "table-caption" // see here for display values: https://developer.mozilla.org/en-US/docs/CSS/display rdisplayswap = /^(none|table(?!-c[ea]).+)/, rmargin = /^margin/, rnumsplit = new RegExp( "^(" + core_pnum + ")(.*)$", "i" ), rnumnonpx = new RegExp( "^(" + core_pnum + ")(?!px)[a-z%]+$", "i" ), rrelNum = new RegExp( "^([+-])=(" + core_pnum + ")", "i" ), elemdisplay = { BODY: "block" }, cssShow = { position: "absolute", visibility: "hidden", display: "block" }, cssNormalTransform = { letterSpacing: 0, fontWeight: 400 }, cssExpand = [ "Top", "Right", "Bottom", "Left" ], cssPrefixes = [ "Webkit", "O", "Moz", "ms" ]; // return a css property mapped to a potentially vendor prefixed property function vendorPropName( style, name ) { // shortcut for names that are not vendor prefixed if ( name in style ) { return name; } // check for vendor prefixed names var capName = name.charAt(0).toUpperCase() + name.slice(1), origName = name, i = cssPrefixes.length; while ( i-- ) { name = cssPrefixes[ i ] + capName; if ( name in style ) { return name; } } return origName; } function isHidden( elem, el ) { // isHidden might be called from jQuery#filter function; // in that case, element will be second argument elem = el || elem; return jQuery.css( elem, "display" ) === "none" || !jQuery.contains( elem.ownerDocument, elem ); } function showHide( elements, show ) { var display, elem, hidden, values = [], index = 0, length = elements.length; for ( ; index < length; index++ ) { elem = elements[ index ]; if ( !elem.style ) { continue; } values[ index ] = jQuery._data( elem, "olddisplay" ); display = elem.style.display; if ( show ) { // Reset the inline display of this element to learn if it is // being hidden by cascaded rules or not if ( !values[ index ] && display === "none" ) { elem.style.display = ""; } // Set elements which have been overridden with display: none // in a stylesheet to whatever the default browser style is // for such an element if ( elem.style.display === "" && isHidden( elem ) ) { values[ index ] = jQuery._data( elem, "olddisplay", css_defaultDisplay(elem.nodeName) ); } } else { if ( !values[ index ] ) { hidden = isHidden( elem ); if ( display && display !== "none" || !hidden ) { jQuery._data( elem, "olddisplay", hidden ? display : jQuery.css( elem, "display" ) ); } } } } // Set the display of most of the elements in a second loop // to avoid the constant reflow for ( index = 0; index < length; index++ ) { elem = elements[ index ]; if ( !elem.style ) { continue; } if ( !show || elem.style.display === "none" || elem.style.display === "" ) { elem.style.display = show ? values[ index ] || "" : "none"; } } return elements; } jQuery.fn.extend({ css: function( name, value ) { return jQuery.access( this, function( elem, name, value ) { var len, styles, map = {}, i = 0; if ( jQuery.isArray( name ) ) { styles = getStyles( elem ); len = name.length; for ( ; i < len; i++ ) { map[ name[ i ] ] = jQuery.css( elem, name[ i ], false, styles ); } return map; } return value !== undefined ? jQuery.style( elem, name, value ) : jQuery.css( elem, name ); }, name, value, arguments.length > 1 ); }, show: function() { return showHide( this, true ); }, hide: function() { return showHide( this ); }, toggle: function( state ) { var bool = typeof state === "boolean"; return this.each(function() { if ( bool ? state : isHidden( this ) ) { jQuery( this ).show(); } else { jQuery( this ).hide(); } }); } }); jQuery.extend({ // Add in style property hooks for overriding the default // behavior of getting and setting a style property cssHooks: { opacity: { get: function( elem, computed ) { if ( computed ) { // We should always get a number back from opacity var ret = curCSS( elem, "opacity" ); return ret === "" ? "1" : ret; } } } }, // Exclude the following css properties to add px cssNumber: { "columnCount": true, "fillOpacity": true, "fontWeight": true, "lineHeight": true, "opacity": true, "orphans": true, "widows": true, "zIndex": true, "zoom": true }, // Add in properties whose names you wish to fix before // setting or getting the value cssProps: { // normalize float css property "float": jQuery.support.cssFloat ? "cssFloat" : "styleFloat" }, // Get and set the style property on a DOM Node style: function( elem, name, value, extra ) { // Don't set styles on text and comment nodes if ( !elem || elem.nodeType === 3 || elem.nodeType === 8 || !elem.style ) { return; } // Make sure that we're working with the right name var ret, type, hooks, origName = jQuery.camelCase( name ), style = elem.style; name = jQuery.cssProps[ origName ] || ( jQuery.cssProps[ origName ] = vendorPropName( style, origName ) ); // gets hook for the prefixed version // followed by the unprefixed version hooks = jQuery.cssHooks[ name ] || jQuery.cssHooks[ origName ]; // Check if we're setting a value if ( value !== undefined ) { type = typeof value; // convert relative number strings (+= or -=) to relative numbers. #7345 if ( type === "string" && (ret = rrelNum.exec( value )) ) { value = ( ret[1] + 1 ) * ret[2] + parseFloat( jQuery.css( elem, name ) ); // Fixes bug #9237 type = "number"; } // Make sure that NaN and null values aren't set. See: #7116 if ( value == null || type === "number" && isNaN( value ) ) { return; } // If a number was passed in, add 'px' to the (except for certain CSS properties) if ( type === "number" && !jQuery.cssNumber[ origName ] ) { value += "px"; } // Fixes #8908, it can be done more correctly by specifing setters in cssHooks, // but it would mean to define eight (for every problematic property) identical functions if ( !jQuery.support.clearCloneStyle && value === "" && name.indexOf("background") === 0 ) { style[ name ] = "inherit"; } // If a hook was provided, use that value, otherwise just set the specified value if ( !hooks || !("set" in hooks) || (value = hooks.set( elem, value, extra )) !== undefined ) { // Wrapped to prevent IE from throwing errors when 'invalid' values are provided // Fixes bug #5509 try { style[ name ] = value; } catch(e) {} } } else { // If a hook was provided get the non-computed value from there if ( hooks && "get" in hooks && (ret = hooks.get( elem, false, extra )) !== undefined ) { return ret; } // Otherwise just get the value from the style object return style[ name ]; } }, css: function( elem, name, extra, styles ) { var num, val, hooks, origName = jQuery.camelCase( name ); // Make sure that we're working with the right name name = jQuery.cssProps[ origName ] || ( jQuery.cssProps[ origName ] = vendorPropName( elem.style, origName ) ); // gets hook for the prefixed version // followed by the unprefixed version hooks = jQuery.cssHooks[ name ] || jQuery.cssHooks[ origName ]; // If a hook was provided get the computed value from there if ( hooks && "get" in hooks ) { val = hooks.get( elem, true, extra ); } // Otherwise, if a way to get the computed value exists, use that if ( val === undefined ) { val = curCSS( elem, name, styles ); } //convert "normal" to computed value if ( val === "normal" && name in cssNormalTransform ) { val = cssNormalTransform[ name ]; } // Return, converting to number if forced or a qualifier was provided and val looks numeric if ( extra === "" || extra ) { num = parseFloat( val ); return extra === true || jQuery.isNumeric( num ) ? num || 0 : val; } return val; }, // A method for quickly swapping in/out CSS properties to get correct calculations swap: function( elem, options, callback, args ) { var ret, name, old = {}; // Remember the old values, and insert the new ones for ( name in options ) { old[ name ] = elem.style[ name ]; elem.style[ name ] = options[ name ]; } ret = callback.apply( elem, args || [] ); // Revert the old values for ( name in options ) { elem.style[ name ] = old[ name ]; } return ret; } }); // NOTE: we've included the "window" in window.getComputedStyle // because jsdom on node.js will break without it. if ( window.getComputedStyle ) { getStyles = function( elem ) { return window.getComputedStyle( elem, null ); }; curCSS = function( elem, name, _computed ) { var width, minWidth, maxWidth, computed = _computed || getStyles( elem ), // getPropertyValue is only needed for .css('filter') in IE9, see #12537 ret = computed ? computed.getPropertyValue( name ) || computed[ name ] : undefined, style = elem.style; if ( computed ) { if ( ret === "" && !jQuery.contains( elem.ownerDocument, elem ) ) { ret = jQuery.style( elem, name ); } // A tribute to the "awesome hack by Dean Edwards" // Chrome < 17 and Safari 5.0 uses "computed value" instead of "used value" for margin-right // Safari 5.1.7 (at least) returns percentage for a larger set of values, but width seems to be reliably pixels // this is against the CSSOM draft spec: http://dev.w3.org/csswg/cssom/#resolved-values if ( rnumnonpx.test( ret ) && rmargin.test( name ) ) { // Remember the original values width = style.width; minWidth = style.minWidth; maxWidth = style.maxWidth; // Put in the new values to get a computed value out style.minWidth = style.maxWidth = style.width = ret; ret = computed.width; // Revert the changed values style.width = width; style.minWidth = minWidth; style.maxWidth = maxWidth; } } return ret; }; } else if ( document.documentElement.currentStyle ) { getStyles = function( elem ) { return elem.currentStyle; }; curCSS = function( elem, name, _computed ) { var left, rs, rsLeft, computed = _computed || getStyles( elem ), ret = computed ? computed[ name ] : undefined, style = elem.style; // Avoid setting ret to empty string here // so we don't default to auto if ( ret == null && style && style[ name ] ) { ret = style[ name ]; } // From the awesome hack by Dean Edwards // http://erik.eae.net/archives/2007/07/27/18.54.15/#comment-102291 // If we're not dealing with a regular pixel number // but a number that has a weird ending, we need to convert it to pixels // but not position css attributes, as those are proportional to the parent element instead // and we can't measure the parent instead because it might trigger a "stacking dolls" problem if ( rnumnonpx.test( ret ) && !rposition.test( name ) ) { // Remember the original values left = style.left; rs = elem.runtimeStyle; rsLeft = rs && rs.left; // Put in the new values to get a computed value out if ( rsLeft ) { rs.left = elem.currentStyle.left; } style.left = name === "fontSize" ? "1em" : ret; ret = style.pixelLeft + "px"; // Revert the changed values style.left = left; if ( rsLeft ) { rs.left = rsLeft; } } return ret === "" ? "auto" : ret; }; } function setPositiveNumber( elem, value, subtract ) { var matches = rnumsplit.exec( value ); return matches ? // Guard against undefined "subtract", e.g., when used as in cssHooks Math.max( 0, matches[ 1 ] - ( subtract || 0 ) ) + ( matches[ 2 ] || "px" ) : value; } function augmentWidthOrHeight( elem, name, extra, isBorderBox, styles ) { var i = extra === ( isBorderBox ? "border" : "content" ) ? // If we already have the right measurement, avoid augmentation 4 : // Otherwise initialize for horizontal or vertical properties name === "width" ? 1 : 0, val = 0; for ( ; i < 4; i += 2 ) { // both box models exclude margin, so add it if we want it if ( extra === "margin" ) { val += jQuery.css( elem, extra + cssExpand[ i ], true, styles ); } if ( isBorderBox ) { // border-box includes padding, so remove it if we want content if ( extra === "content" ) { val -= jQuery.css( elem, "padding" + cssExpand[ i ], true, styles ); } // at this point, extra isn't border nor margin, so remove border if ( extra !== "margin" ) { val -= jQuery.css( elem, "border" + cssExpand[ i ] + "Width", true, styles ); } } else { // at this point, extra isn't content, so add padding val += jQuery.css( elem, "padding" + cssExpand[ i ], true, styles ); // at this point, extra isn't content nor padding, so add border if ( extra !== "padding" ) { val += jQuery.css( elem, "border" + cssExpand[ i ] + "Width", true, styles ); } } } return val; } function getWidthOrHeight( elem, name, extra ) { // Start with offset property, which is equivalent to the border-box value var valueIsBorderBox = true, val = name === "width" ? elem.offsetWidth : elem.offsetHeight, styles = getStyles( elem ), isBorderBox = jQuery.support.boxSizing && jQuery.css( elem, "boxSizing", false, styles ) === "border-box"; // some non-html elements return undefined for offsetWidth, so check for null/undefined // svg - https://bugzilla.mozilla.org/show_bug.cgi?id=649285 // MathML - https://bugzilla.mozilla.org/show_bug.cgi?id=491668 if ( val <= 0 || val == null ) { // Fall back to computed then uncomputed css if necessary val = curCSS( elem, name, styles ); if ( val < 0 || val == null ) { val = elem.style[ name ]; } // Computed unit is not pixels. Stop here and return. if ( rnumnonpx.test(val) ) { return val; } // we need the check for style in case a browser which returns unreliable values // for getComputedStyle silently falls back to the reliable elem.style valueIsBorderBox = isBorderBox && ( jQuery.support.boxSizingReliable || val === elem.style[ name ] ); // Normalize "", auto, and prepare for extra val = parseFloat( val ) || 0; } // use the active box-sizing model to add/subtract irrelevant styles return ( val + augmentWidthOrHeight( elem, name, extra || ( isBorderBox ? "border" : "content" ), valueIsBorderBox, styles ) ) + "px"; } // Try to determine the default display value of an element function css_defaultDisplay( nodeName ) { var doc = document, display = elemdisplay[ nodeName ]; if ( !display ) { display = actualDisplay( nodeName, doc ); // If the simple way fails, read from inside an iframe if ( display === "none" || !display ) { // Use the already-created iframe if possible iframe = ( iframe || jQuery("<iframe frameborder='0' width='0' height='0'/>") .css( "cssText", "display:block !important" ) ).appendTo( doc.documentElement ); // Always write a new HTML skeleton so Webkit and Firefox don't choke on reuse doc = ( iframe[0].contentWindow || iframe[0].contentDocument ).document; doc.write("<!doctype html><html><body>"); doc.close(); display = actualDisplay( nodeName, doc ); iframe.detach(); } // Store the correct default display elemdisplay[ nodeName ] = display; } return display; } // Called ONLY from within css_defaultDisplay function actualDisplay( name, doc ) { var elem = jQuery( doc.createElement( name ) ).appendTo( doc.body ), display = jQuery.css( elem[0], "display" ); elem.remove(); return display; } jQuery.each([ "height", "width" ], function( i, name ) { jQuery.cssHooks[ name ] = { get: function( elem, computed, extra ) { if ( computed ) { // certain elements can have dimension info if we invisibly show them // however, it must have a current display style that would benefit from this return elem.offsetWidth === 0 && rdisplayswap.test( jQuery.css( elem, "display" ) ) ? jQuery.swap( elem, cssShow, function() { return getWidthOrHeight( elem, name, extra ); }) : getWidthOrHeight( elem, name, extra ); } }, set: function( elem, value, extra ) { var styles = extra && getStyles( elem ); return setPositiveNumber( elem, value, extra ? augmentWidthOrHeight( elem, name, extra, jQuery.support.boxSizing && jQuery.css( elem, "boxSizing", false, styles ) === "border-box", styles ) : 0 ); } }; }); if ( !jQuery.support.opacity ) { jQuery.cssHooks.opacity = { get: function( elem, computed ) { // IE uses filters for opacity return ropacity.test( (computed && elem.currentStyle ? elem.currentStyle.filter : elem.style.filter) || "" ) ? ( 0.01 * parseFloat( RegExp.$1 ) ) + "" : computed ? "1" : ""; }, set: function( elem, value ) { var style = elem.style, currentStyle = elem.currentStyle, opacity = jQuery.isNumeric( value ) ? "alpha(opacity=" + value * 100 + ")" : "", filter = currentStyle && currentStyle.filter || style.filter || ""; // IE has trouble with opacity if it does not have layout // Force it by setting the zoom level style.zoom = 1; // if setting opacity to 1, and no other filters exist - attempt to remove filter attribute #6652 // if value === "", then remove inline opacity #12685 if ( ( value >= 1 || value === "" ) && jQuery.trim( filter.replace( ralpha, "" ) ) === "" && style.removeAttribute ) { // Setting style.filter to null, "" & " " still leave "filter:" in the cssText // if "filter:" is present at all, clearType is disabled, we want to avoid this // style.removeAttribute is IE Only, but so apparently is this code path... style.removeAttribute( "filter" ); // if there is no filter style applied in a css rule or unset inline opacity, we are done if ( value === "" || currentStyle && !currentStyle.filter ) { return; } } // otherwise, set new filter values style.filter = ralpha.test( filter ) ? filter.replace( ralpha, opacity ) : filter + " " + opacity; } }; } // These hooks cannot be added until DOM ready because the support test // for it is not run until after DOM ready jQuery(function() { if ( !jQuery.support.reliableMarginRight ) { jQuery.cssHooks.marginRight = { get: function( elem, computed ) { if ( computed ) { // WebKit Bug 13343 - getComputedStyle returns wrong value for margin-right // Work around by temporarily setting element display to inline-block return jQuery.swap( elem, { "display": "inline-block" }, curCSS, [ elem, "marginRight" ] ); } } }; } // Webkit bug: https://bugs.webkit.org/show_bug.cgi?id=29084 // getComputedStyle returns percent when specified for top/left/bottom/right // rather than make the css module depend on the offset module, we just check for it here if ( !jQuery.support.pixelPosition && jQuery.fn.position ) { jQuery.each( [ "top", "left" ], function( i, prop ) { jQuery.cssHooks[ prop ] = { get: function( elem, computed ) { if ( computed ) { computed = curCSS( elem, prop ); // if curCSS returns percentage, fallback to offset return rnumnonpx.test( computed ) ? jQuery( elem ).position()[ prop ] + "px" : computed; } } }; }); } }); if ( jQuery.expr && jQuery.expr.filters ) { jQuery.expr.filters.hidden = function( elem ) { // Support: Opera <= 12.12 // Opera reports offsetWidths and offsetHeights less than zero on some elements return elem.offsetWidth <= 0 && elem.offsetHeight <= 0 || (!jQuery.support.reliableHiddenOffsets && ((elem.style && elem.style.display) || jQuery.css( elem, "display" )) === "none"); }; jQuery.expr.filters.visible = function( elem ) { return !jQuery.expr.filters.hidden( elem ); }; } // These hooks are used by animate to expand properties jQuery.each({ margin: "", padding: "", border: "Width" }, function( prefix, suffix ) { jQuery.cssHooks[ prefix + suffix ] = { expand: function( value ) { var i = 0, expanded = {}, // assumes a single number if not a string parts = typeof value === "string" ? value.split(" ") : [ value ]; for ( ; i < 4; i++ ) { expanded[ prefix + cssExpand[ i ] + suffix ] = parts[ i ] || parts[ i - 2 ] || parts[ 0 ]; } return expanded; } }; if ( !rmargin.test( prefix ) ) { jQuery.cssHooks[ prefix + suffix ].set = setPositiveNumber; } }); var r20 = /%20/g, rbracket = /\[\]$/, rCRLF = /\r?\n/g, rsubmitterTypes = /^(?:submit|button|image|reset|file)$/i, rsubmittable = /^(?:input|select|textarea|keygen)/i; jQuery.fn.extend({ serialize: function() { return jQuery.param( this.serializeArray() ); }, serializeArray: function() { return this.map(function(){ // Can add propHook for "elements" to filter or add form elements var elements = jQuery.prop( this, "elements" ); return elements ? jQuery.makeArray( elements ) : this; }) .filter(function(){ var type = this.type; // Use .is(":disabled") so that fieldset[disabled] works return this.name && !jQuery( this ).is( ":disabled" ) && rsubmittable.test( this.nodeName ) && !rsubmitterTypes.test( type ) && ( this.checked || !manipulation_rcheckableType.test( type ) ); }) .map(function( i, elem ){ var val = jQuery( this ).val(); return val == null ? null : jQuery.isArray( val ) ? jQuery.map( val, function( val ){ return { name: elem.name, value: val.replace( rCRLF, "\r\n" ) }; }) : { name: elem.name, value: val.replace( rCRLF, "\r\n" ) }; }).get(); } }); //Serialize an array of form elements or a set of //key/values into a query string jQuery.param = function( a, traditional ) { var prefix, s = [], add = function( key, value ) { // If value is a function, invoke it and return its value value = jQuery.isFunction( value ) ? value() : ( value == null ? "" : value ); s[ s.length ] = encodeURIComponent( key ) + "=" + encodeURIComponent( value ); }; // Set traditional to true for jQuery <= 1.3.2 behavior. if ( traditional === undefined ) { traditional = jQuery.ajaxSettings && jQuery.ajaxSettings.traditional; } // If an array was passed in, assume that it is an array of form elements. if ( jQuery.isArray( a ) || ( a.jquery && !jQuery.isPlainObject( a ) ) ) { // Serialize the form elements jQuery.each( a, function() { add( this.name, this.value ); }); } else { // If traditional, encode the "old" way (the way 1.3.2 or older // did it), otherwise encode params recursively. for ( prefix in a ) { buildParams( prefix, a[ prefix ], traditional, add ); } } // Return the resulting serialization return s.join( "&" ).replace( r20, "+" ); }; function buildParams( prefix, obj, traditional, add ) { var name; if ( jQuery.isArray( obj ) ) { // Serialize array item. jQuery.each( obj, function( i, v ) { if ( traditional || rbracket.test( prefix ) ) { // Treat each array item as a scalar. add( prefix, v ); } else { // Item is non-scalar (array or object), encode its numeric index. buildParams( prefix + "[" + ( typeof v === "object" ? i : "" ) + "]", v, traditional, add ); } }); } else if ( !traditional && jQuery.type( obj ) === "object" ) { // Serialize object item. for ( name in obj ) { buildParams( prefix + "[" + name + "]", obj[ name ], traditional, add ); } } else { // Serialize scalar item. add( prefix, obj ); } } jQuery.each( ("blur focus focusin focusout load resize scroll unload click dblclick " + "mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave " + "change select submit keydown keypress keyup error contextmenu").split(" "), function( i, name ) { // Handle event binding jQuery.fn[ name ] = function( data, fn ) { return arguments.length > 0 ? this.on( name, null, data, fn ) : this.trigger( name ); }; }); jQuery.fn.hover = function( fnOver, fnOut ) { return this.mouseenter( fnOver ).mouseleave( fnOut || fnOver ); }; var // Document location ajaxLocParts, ajaxLocation, ajax_nonce = jQuery.now(), ajax_rquery = /\?/, rhash = /#.*$/, rts = /([?&])_=[^&]*/, rheaders = /^(.*?):[ \t]*([^\r\n]*)\r?$/mg, // IE leaves an \r character at EOL // #7653, #8125, #8152: local protocol detection rlocalProtocol = /^(?:about|app|app-storage|.+-extension|file|res|widget):$/, rnoContent = /^(?:GET|HEAD)$/, rprotocol = /^\/\//, rurl = /^([\w.+-]+:)(?:\/\/([^\/?#:]*)(?::(\d+)|)|)/, // Keep a copy of the old load method _load = jQuery.fn.load, /* Prefilters * 1) They are useful to introduce custom dataTypes (see ajax/jsonp.js for an example) * 2) These are called: * - BEFORE asking for a transport * - AFTER param serialization (s.data is a string if s.processData is true) * 3) key is the dataType * 4) the catchall symbol "*" can be used * 5) execution will start with transport dataType and THEN continue down to "*" if needed */ prefilters = {}, /* Transports bindings * 1) key is the dataType * 2) the catchall symbol "*" can be used * 3) selection will start with transport dataType and THEN go to "*" if needed */ transports = {}, // Avoid comment-prolog char sequence (#10098); must appease lint and evade compression allTypes = "*/".concat("*"); // #8138, IE may throw an exception when accessing // a field from window.location if document.domain has been set try { ajaxLocation = location.href; } catch( e ) { // Use the href attribute of an A element // since IE will modify it given document.location ajaxLocation = document.createElement( "a" ); ajaxLocation.href = ""; ajaxLocation = ajaxLocation.href; } // Segment location into parts ajaxLocParts = rurl.exec( ajaxLocation.toLowerCase() ) || []; // Base "constructor" for jQuery.ajaxPrefilter and jQuery.ajaxTransport function addToPrefiltersOrTransports( structure ) { // dataTypeExpression is optional and defaults to "*" return function( dataTypeExpression, func ) { if ( typeof dataTypeExpression !== "string" ) { func = dataTypeExpression; dataTypeExpression = "*"; } var dataType, i = 0, dataTypes = dataTypeExpression.toLowerCase().match( core_rnotwhite ) || []; if ( jQuery.isFunction( func ) ) { // For each dataType in the dataTypeExpression while ( (dataType = dataTypes[i++]) ) { // Prepend if requested if ( dataType[0] === "+" ) { dataType = dataType.slice( 1 ) || "*"; (structure[ dataType ] = structure[ dataType ] || []).unshift( func ); // Otherwise append } else { (structure[ dataType ] = structure[ dataType ] || []).push( func ); } } } }; } // Base inspection function for prefilters and transports function inspectPrefiltersOrTransports( structure, options, originalOptions, jqXHR ) { var inspected = {}, seekingTransport = ( structure === transports ); function inspect( dataType ) { var selected; inspected[ dataType ] = true; jQuery.each( structure[ dataType ] || [], function( _, prefilterOrFactory ) { var dataTypeOrTransport = prefilterOrFactory( options, originalOptions, jqXHR ); if( typeof dataTypeOrTransport === "string" && !seekingTransport && !inspected[ dataTypeOrTransport ] ) { options.dataTypes.unshift( dataTypeOrTransport ); inspect( dataTypeOrTransport ); return false; } else if ( seekingTransport ) { return !( selected = dataTypeOrTransport ); } }); return selected; } return inspect( options.dataTypes[ 0 ] ) || !inspected[ "*" ] && inspect( "*" ); } // A special extend for ajax options // that takes "flat" options (not to be deep extended) // Fixes #9887 function ajaxExtend( target, src ) { var deep, key, flatOptions = jQuery.ajaxSettings.flatOptions || {}; for ( key in src ) { if ( src[ key ] !== undefined ) { ( flatOptions[ key ] ? target : ( deep || (deep = {}) ) )[ key ] = src[ key ]; } } if ( deep ) { jQuery.extend( true, target, deep ); } return target; } jQuery.fn.load = function( url, params, callback ) { if ( typeof url !== "string" && _load ) { return _load.apply( this, arguments ); } var selector, response, type, self = this, off = url.indexOf(" "); if ( off >= 0 ) { selector = url.slice( off, url.length ); url = url.slice( 0, off ); } // If it's a function if ( jQuery.isFunction( params ) ) { // We assume that it's the callback callback = params; params = undefined; // Otherwise, build a param string } else if ( params && typeof params === "object" ) { type = "POST"; } // If we have elements to modify, make the request if ( self.length > 0 ) { jQuery.ajax({ url: url, // if "type" variable is undefined, then "GET" method will be used type: type, dataType: "html", data: params }).done(function( responseText ) { // Save response for use in complete callback response = arguments; self.html( selector ? // If a selector was specified, locate the right elements in a dummy div // Exclude scripts to avoid IE 'Permission Denied' errors jQuery("<div>").append( jQuery.parseHTML( responseText ) ).find( selector ) : // Otherwise use the full result responseText ); }).complete( callback && function( jqXHR, status ) { self.each( callback, response || [ jqXHR.responseText, status, jqXHR ] ); }); } return this; }; // Attach a bunch of functions for handling common AJAX events jQuery.each( [ "ajaxStart", "ajaxStop", "ajaxComplete", "ajaxError", "ajaxSuccess", "ajaxSend" ], function( i, type ){ jQuery.fn[ type ] = function( fn ){ return this.on( type, fn ); }; }); jQuery.each( [ "get", "post" ], function( i, method ) { jQuery[ method ] = function( url, data, callback, type ) { // shift arguments if data argument was omitted if ( jQuery.isFunction( data ) ) { type = type || callback; callback = data; data = undefined; } return jQuery.ajax({ url: url, type: method, dataType: type, data: data, success: callback }); }; }); jQuery.extend({ // Counter for holding the number of active queries active: 0, // Last-Modified header cache for next request lastModified: {}, etag: {}, ajaxSettings: { url: ajaxLocation, type: "GET", isLocal: rlocalProtocol.test( ajaxLocParts[ 1 ] ), global: true, processData: true, async: true, contentType: "application/x-www-form-urlencoded; charset=UTF-8", /* timeout: 0, data: null, dataType: null, username: null, password: null, cache: null, throws: false, traditional: false, headers: {}, */ accepts: { "*": allTypes, text: "text/plain", html: "text/html", xml: "application/xml, text/xml", json: "application/json, text/javascript" }, contents: { xml: /xml/, html: /html/, json: /json/ }, responseFields: { xml: "responseXML", text: "responseText" }, // Data converters // Keys separate source (or catchall "*") and destination types with a single space converters: { // Convert anything to text "* text": window.String, // Text to html (true = no transformation) "text html": true, // Evaluate text as a json expression "text json": jQuery.parseJSON, // Parse text as xml "text xml": jQuery.parseXML }, // For options that shouldn't be deep extended: // you can add your own custom options here if // and when you create one that shouldn't be // deep extended (see ajaxExtend) flatOptions: { url: true, context: true } }, // Creates a full fledged settings object into target // with both ajaxSettings and settings fields. // If target is omitted, writes into ajaxSettings. ajaxSetup: function( target, settings ) { return settings ? // Building a settings object ajaxExtend( ajaxExtend( target, jQuery.ajaxSettings ), settings ) : // Extending ajaxSettings ajaxExtend( jQuery.ajaxSettings, target ); }, ajaxPrefilter: addToPrefiltersOrTransports( prefilters ), ajaxTransport: addToPrefiltersOrTransports( transports ), // Main method ajax: function( url, options ) { // If url is an object, simulate pre-1.5 signature if ( typeof url === "object" ) { options = url; url = undefined; } // Force options to be an object options = options || {}; var // Cross-domain detection vars parts, // Loop variable i, // URL without anti-cache param cacheURL, // Response headers as string responseHeadersString, // timeout handle timeoutTimer, // To know if global events are to be dispatched fireGlobals, transport, // Response headers responseHeaders, // Create the final options object s = jQuery.ajaxSetup( {}, options ), // Callbacks context callbackContext = s.context || s, // Context for global events is callbackContext if it is a DOM node or jQuery collection globalEventContext = s.context && ( callbackContext.nodeType || callbackContext.jquery ) ? jQuery( callbackContext ) : jQuery.event, // Deferreds deferred = jQuery.Deferred(), completeDeferred = jQuery.Callbacks("once memory"), // Status-dependent callbacks statusCode = s.statusCode || {}, // Headers (they are sent all at once) requestHeaders = {}, requestHeadersNames = {}, // The jqXHR state state = 0, // Default abort message strAbort = "canceled", // Fake xhr jqXHR = { readyState: 0, // Builds headers hashtable if needed getResponseHeader: function( key ) { var match; if ( state === 2 ) { if ( !responseHeaders ) { responseHeaders = {}; while ( (match = rheaders.exec( responseHeadersString )) ) { responseHeaders[ match[1].toLowerCase() ] = match[ 2 ]; } } match = responseHeaders[ key.toLowerCase() ]; } return match == null ? null : match; }, // Raw string getAllResponseHeaders: function() { return state === 2 ? responseHeadersString : null; }, // Caches the header setRequestHeader: function( name, value ) { var lname = name.toLowerCase(); if ( !state ) { name = requestHeadersNames[ lname ] = requestHeadersNames[ lname ] || name; requestHeaders[ name ] = value; } return this; }, // Overrides response content-type header overrideMimeType: function( type ) { if ( !state ) { s.mimeType = type; } return this; }, // Status-dependent callbacks statusCode: function( map ) { var code; if ( map ) { if ( state < 2 ) { for ( code in map ) { // Lazy-add the new callback in a way that preserves old ones statusCode[ code ] = [ statusCode[ code ], map[ code ] ]; } } else { // Execute the appropriate callbacks jqXHR.always( map[ jqXHR.status ] ); } } return this; }, // Cancel the request abort: function( statusText ) { var finalText = statusText || strAbort; if ( transport ) { transport.abort( finalText ); } done( 0, finalText ); return this; } }; // Attach deferreds deferred.promise( jqXHR ).complete = completeDeferred.add; jqXHR.success = jqXHR.done; jqXHR.error = jqXHR.fail; // Remove hash character (#7531: and string promotion) // Add protocol if not provided (#5866: IE7 issue with protocol-less urls) // Handle falsy url in the settings object (#10093: consistency with old signature) // We also use the url parameter if available s.url = ( ( url || s.url || ajaxLocation ) + "" ).replace( rhash, "" ).replace( rprotocol, ajaxLocParts[ 1 ] + "//" ); // Alias method option to type as per ticket #12004 s.type = options.method || options.type || s.method || s.type; // Extract dataTypes list s.dataTypes = jQuery.trim( s.dataType || "*" ).toLowerCase().match( core_rnotwhite ) || [""]; // A cross-domain request is in order when we have a protocol:host:port mismatch if ( s.crossDomain == null ) { parts = rurl.exec( s.url.toLowerCase() ); s.crossDomain = !!( parts && ( parts[ 1 ] !== ajaxLocParts[ 1 ] || parts[ 2 ] !== ajaxLocParts[ 2 ] || ( parts[ 3 ] || ( parts[ 1 ] === "http:" ? 80 : 443 ) ) != ( ajaxLocParts[ 3 ] || ( ajaxLocParts[ 1 ] === "http:" ? 80 : 443 ) ) ) ); } // Convert data if not already a string if ( s.data && s.processData && typeof s.data !== "string" ) { s.data = jQuery.param( s.data, s.traditional ); } // Apply prefilters inspectPrefiltersOrTransports( prefilters, s, options, jqXHR ); // If request was aborted inside a prefilter, stop there if ( state === 2 ) { return jqXHR; } // We can fire global events as of now if asked to fireGlobals = s.global; // Watch for a new set of requests if ( fireGlobals && jQuery.active++ === 0 ) { jQuery.event.trigger("ajaxStart"); } // Uppercase the type s.type = s.type.toUpperCase(); // Determine if request has content s.hasContent = !rnoContent.test( s.type ); // Save the URL in case we're toying with the If-Modified-Since // and/or If-None-Match header later on cacheURL = s.url; // More options handling for requests with no content if ( !s.hasContent ) { // If data is available, append data to url if ( s.data ) { cacheURL = ( s.url += ( ajax_rquery.test( cacheURL ) ? "&" : "?" ) + s.data ); // #9682: remove data so that it's not used in an eventual retry delete s.data; } // Add anti-cache in url if needed if ( s.cache === false ) { s.url = rts.test( cacheURL ) ? // If there is already a '_' parameter, set its value cacheURL.replace( rts, "$1_=" + ajax_nonce++ ) : // Otherwise add one to the end cacheURL + ( ajax_rquery.test( cacheURL ) ? "&" : "?" ) + "_=" + ajax_nonce++; } } // Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode. if ( s.ifModified ) { if ( jQuery.lastModified[ cacheURL ] ) { jqXHR.setRequestHeader( "If-Modified-Since", jQuery.lastModified[ cacheURL ] ); } if ( jQuery.etag[ cacheURL ] ) { jqXHR.setRequestHeader( "If-None-Match", jQuery.etag[ cacheURL ] ); } } // Set the correct header, if data is being sent if ( s.data && s.hasContent && s.contentType !== false || options.contentType ) { jqXHR.setRequestHeader( "Content-Type", s.contentType ); } // Set the Accepts header for the server, depending on the dataType jqXHR.setRequestHeader( "Accept", s.dataTypes[ 0 ] && s.accepts[ s.dataTypes[0] ] ? s.accepts[ s.dataTypes[0] ] + ( s.dataTypes[ 0 ] !== "*" ? ", " + allTypes + "; q=0.01" : "" ) : s.accepts[ "*" ] ); // Check for headers option for ( i in s.headers ) { jqXHR.setRequestHeader( i, s.headers[ i ] ); } // Allow custom headers/mimetypes and early abort if ( s.beforeSend && ( s.beforeSend.call( callbackContext, jqXHR, s ) === false || state === 2 ) ) { // Abort if not done already and return return jqXHR.abort(); } // aborting is no longer a cancellation strAbort = "abort"; // Install callbacks on deferreds for ( i in { success: 1, error: 1, complete: 1 } ) { jqXHR[ i ]( s[ i ] ); } // Get transport transport = inspectPrefiltersOrTransports( transports, s, options, jqXHR ); // If no transport, we auto-abort if ( !transport ) { done( -1, "No Transport" ); } else { jqXHR.readyState = 1; // Send global event if ( fireGlobals ) { globalEventContext.trigger( "ajaxSend", [ jqXHR, s ] ); } // Timeout if ( s.async && s.timeout > 0 ) { timeoutTimer = setTimeout(function() { jqXHR.abort("timeout"); }, s.timeout ); } try { state = 1; transport.send( requestHeaders, done ); } catch ( e ) { // Propagate exception as error if not done if ( state < 2 ) { done( -1, e ); // Simply rethrow otherwise } else { throw e; } } } // Callback for when everything is done function done( status, nativeStatusText, responses, headers ) { var isSuccess, success, error, response, modified, statusText = nativeStatusText; // Called once if ( state === 2 ) { return; } // State is "done" now state = 2; // Clear timeout if it exists if ( timeoutTimer ) { clearTimeout( timeoutTimer ); } // Dereference transport for early garbage collection // (no matter how long the jqXHR object will be used) transport = undefined; // Cache response headers responseHeadersString = headers || ""; // Set readyState jqXHR.readyState = status > 0 ? 4 : 0; // Get response data if ( responses ) { response = ajaxHandleResponses( s, jqXHR, responses ); } // If successful, handle type chaining if ( status >= 200 && status < 300 || status === 304 ) { // Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode. if ( s.ifModified ) { modified = jqXHR.getResponseHeader("Last-Modified"); if ( modified ) { jQuery.lastModified[ cacheURL ] = modified; } modified = jqXHR.getResponseHeader("etag"); if ( modified ) { jQuery.etag[ cacheURL ] = modified; } } // if no content if ( status === 204 ) { isSuccess = true; statusText = "nocontent"; // if not modified } else if ( status === 304 ) { isSuccess = true; statusText = "notmodified"; // If we have data, let's convert it } else { isSuccess = ajaxConvert( s, response ); statusText = isSuccess.state; success = isSuccess.data; error = isSuccess.error; isSuccess = !error; } } else { // We extract error from statusText // then normalize statusText and status for non-aborts error = statusText; if ( status || !statusText ) { statusText = "error"; if ( status < 0 ) { status = 0; } } } // Set data for the fake xhr object jqXHR.status = status; jqXHR.statusText = ( nativeStatusText || statusText ) + ""; // Success/Error if ( isSuccess ) { deferred.resolveWith( callbackContext, [ success, statusText, jqXHR ] ); } else { deferred.rejectWith( callbackContext, [ jqXHR, statusText, error ] ); } // Status-dependent callbacks jqXHR.statusCode( statusCode ); statusCode = undefined; if ( fireGlobals ) { globalEventContext.trigger( isSuccess ? "ajaxSuccess" : "ajaxError", [ jqXHR, s, isSuccess ? success : error ] ); } // Complete completeDeferred.fireWith( callbackContext, [ jqXHR, statusText ] ); if ( fireGlobals ) { globalEventContext.trigger( "ajaxComplete", [ jqXHR, s ] ); // Handle the global AJAX counter if ( !( --jQuery.active ) ) { jQuery.event.trigger("ajaxStop"); } } } return jqXHR; }, getScript: function( url, callback ) { return jQuery.get( url, undefined, callback, "script" ); }, getJSON: function( url, data, callback ) { return jQuery.get( url, data, callback, "json" ); } }); /* Handles responses to an ajax request: * - sets all responseXXX fields accordingly * - finds the right dataType (mediates between content-type and expected dataType) * - returns the corresponding response */ function ajaxHandleResponses( s, jqXHR, responses ) { var firstDataType, ct, finalDataType, type, contents = s.contents, dataTypes = s.dataTypes, responseFields = s.responseFields; // Fill responseXXX fields for ( type in responseFields ) { if ( type in responses ) { jqXHR[ responseFields[type] ] = responses[ type ]; } } // Remove auto dataType and get content-type in the process while( dataTypes[ 0 ] === "*" ) { dataTypes.shift(); if ( ct === undefined ) { ct = s.mimeType || jqXHR.getResponseHeader("Content-Type"); } } // Check if we're dealing with a known content-type if ( ct ) { for ( type in contents ) { if ( contents[ type ] && contents[ type ].test( ct ) ) { dataTypes.unshift( type ); break; } } } // Check to see if we have a response for the expected dataType if ( dataTypes[ 0 ] in responses ) { finalDataType = dataTypes[ 0 ]; } else { // Try convertible dataTypes for ( type in responses ) { if ( !dataTypes[ 0 ] || s.converters[ type + " " + dataTypes[0] ] ) { finalDataType = type; break; } if ( !firstDataType ) { firstDataType = type; } } // Or just use first one finalDataType = finalDataType || firstDataType; } // If we found a dataType // We add the dataType to the list if needed // and return the corresponding response if ( finalDataType ) { if ( finalDataType !== dataTypes[ 0 ] ) { dataTypes.unshift( finalDataType ); } return responses[ finalDataType ]; } } // Chain conversions given the request and the original response function ajaxConvert( s, response ) { var conv2, current, conv, tmp, converters = {}, i = 0, // Work with a copy of dataTypes in case we need to modify it for conversion dataTypes = s.dataTypes.slice(), prev = dataTypes[ 0 ]; // Apply the dataFilter if provided if ( s.dataFilter ) { response = s.dataFilter( response, s.dataType ); } // Create converters map with lowercased keys if ( dataTypes[ 1 ] ) { for ( conv in s.converters ) { converters[ conv.toLowerCase() ] = s.converters[ conv ]; } } // Convert to each sequential dataType, tolerating list modification for ( ; (current = dataTypes[++i]); ) { // There's only work to do if current dataType is non-auto if ( current !== "*" ) { // Convert response if prev dataType is non-auto and differs from current if ( prev !== "*" && prev !== current ) { // Seek a direct converter conv = converters[ prev + " " + current ] || converters[ "* " + current ]; // If none found, seek a pair if ( !conv ) { for ( conv2 in converters ) { // If conv2 outputs current tmp = conv2.split(" "); if ( tmp[ 1 ] === current ) { // If prev can be converted to accepted input conv = converters[ prev + " " + tmp[ 0 ] ] || converters[ "* " + tmp[ 0 ] ]; if ( conv ) { // Condense equivalence converters if ( conv === true ) { conv = converters[ conv2 ]; // Otherwise, insert the intermediate dataType } else if ( converters[ conv2 ] !== true ) { current = tmp[ 0 ]; dataTypes.splice( i--, 0, current ); } break; } } } } // Apply converter (if not an equivalence) if ( conv !== true ) { // Unless errors are allowed to bubble, catch and return them if ( conv && s["throws"] ) { response = conv( response ); } else { try { response = conv( response ); } catch ( e ) { return { state: "parsererror", error: conv ? e : "No conversion from " + prev + " to " + current }; } } } } // Update prev for next iteration prev = current; } } return { state: "success", data: response }; } // Install script dataType jQuery.ajaxSetup({ accepts: { script: "text/javascript, application/javascript, application/ecmascript, application/x-ecmascript" }, contents: { script: /(?:java|ecma)script/ }, converters: { "text script": function( text ) { jQuery.globalEval( text ); return text; } } }); // Handle cache's special case and global jQuery.ajaxPrefilter( "script", function( s ) { if ( s.cache === undefined ) { s.cache = false; } if ( s.crossDomain ) { s.type = "GET"; s.global = false; } }); // Bind script tag hack transport jQuery.ajaxTransport( "script", function(s) { // This transport only deals with cross domain requests if ( s.crossDomain ) { var script, head = document.head || jQuery("head")[0] || document.documentElement; return { send: function( _, callback ) { script = document.createElement("script"); script.async = true; if ( s.scriptCharset ) { script.charset = s.scriptCharset; } script.src = s.url; // Attach handlers for all browsers script.onload = script.onreadystatechange = function( _, isAbort ) { if ( isAbort || !script.readyState || /loaded|complete/.test( script.readyState ) ) { // Handle memory leak in IE script.onload = script.onreadystatechange = null; // Remove the script if ( script.parentNode ) { script.parentNode.removeChild( script ); } // Dereference the script script = null; // Callback if not abort if ( !isAbort ) { callback( 200, "success" ); } } }; // Circumvent IE6 bugs with base elements (#2709 and #4378) by prepending // Use native DOM manipulation to avoid our domManip AJAX trickery head.insertBefore( script, head.firstChild ); }, abort: function() { if ( script ) { script.onload( undefined, true ); } } }; } }); var oldCallbacks = [], rjsonp = /(=)\?(?=&|$)|\?\?/; // Default jsonp settings jQuery.ajaxSetup({ jsonp: "callback", jsonpCallback: function() { var callback = oldCallbacks.pop() || ( jQuery.expando + "_" + ( ajax_nonce++ ) ); this[ callback ] = true; return callback; } }); // Detect, normalize options and install callbacks for jsonp requests jQuery.ajaxPrefilter( "json jsonp", function( s, originalSettings, jqXHR ) { var callbackName, overwritten, responseContainer, jsonProp = s.jsonp !== false && ( rjsonp.test( s.url ) ? "url" : typeof s.data === "string" && !( s.contentType || "" ).indexOf("application/x-www-form-urlencoded") && rjsonp.test( s.data ) && "data" ); // Handle iff the expected data type is "jsonp" or we have a parameter to set if ( jsonProp || s.dataTypes[ 0 ] === "jsonp" ) { // Get callback name, remembering preexisting value associated with it callbackName = s.jsonpCallback = jQuery.isFunction( s.jsonpCallback ) ? s.jsonpCallback() : s.jsonpCallback; // Insert callback into url or form data if ( jsonProp ) { s[ jsonProp ] = s[ jsonProp ].replace( rjsonp, "$1" + callbackName ); } else if ( s.jsonp !== false ) { s.url += ( ajax_rquery.test( s.url ) ? "&" : "?" ) + s.jsonp + "=" + callbackName; } // Use data converter to retrieve json after script execution s.converters["script json"] = function() { if ( !responseContainer ) { jQuery.error( callbackName + " was not called" ); } return responseContainer[ 0 ]; }; // force json dataType s.dataTypes[ 0 ] = "json"; // Install callback overwritten = window[ callbackName ]; window[ callbackName ] = function() { responseContainer = arguments; }; // Clean-up function (fires after converters) jqXHR.always(function() { // Restore preexisting value window[ callbackName ] = overwritten; // Save back as free if ( s[ callbackName ] ) { // make sure that re-using the options doesn't screw things around s.jsonpCallback = originalSettings.jsonpCallback; // save the callback name for future use oldCallbacks.push( callbackName ); } // Call if it was a function and we have a response if ( responseContainer && jQuery.isFunction( overwritten ) ) { overwritten( responseContainer[ 0 ] ); } responseContainer = overwritten = undefined; }); // Delegate to script return "script"; } }); var xhrCallbacks, xhrSupported, xhrId = 0, // #5280: Internet Explorer will keep connections alive if we don't abort on unload xhrOnUnloadAbort = window.ActiveXObject && function() { // Abort all pending requests var key; for ( key in xhrCallbacks ) { xhrCallbacks[ key ]( undefined, true ); } }; // Functions to create xhrs function createStandardXHR() { try { return new window.XMLHttpRequest(); } catch( e ) {} } function createActiveXHR() { try { return new window.ActiveXObject("Microsoft.XMLHTTP"); } catch( e ) {} } // Create the request object // (This is still attached to ajaxSettings for backward compatibility) jQuery.ajaxSettings.xhr = window.ActiveXObject ? /* Microsoft failed to properly * implement the XMLHttpRequest in IE7 (can't request local files), * so we use the ActiveXObject when it is available * Additionally XMLHttpRequest can be disabled in IE7/IE8 so * we need a fallback. */ function() { return !this.isLocal && createStandardXHR() || createActiveXHR(); } : // For all other browsers, use the standard XMLHttpRequest object createStandardXHR; // Determine support properties xhrSupported = jQuery.ajaxSettings.xhr(); jQuery.support.cors = !!xhrSupported && ( "withCredentials" in xhrSupported ); xhrSupported = jQuery.support.ajax = !!xhrSupported; // Create transport if the browser can provide an xhr if ( xhrSupported ) { jQuery.ajaxTransport(function( s ) { // Cross domain only allowed if supported through XMLHttpRequest if ( !s.crossDomain || jQuery.support.cors ) { var callback; return { send: function( headers, complete ) { // Get a new xhr var handle, i, xhr = s.xhr(); // Open the socket // Passing null username, generates a login popup on Opera (#2865) if ( s.username ) { xhr.open( s.type, s.url, s.async, s.username, s.password ); } else { xhr.open( s.type, s.url, s.async ); } // Apply custom fields if provided if ( s.xhrFields ) { for ( i in s.xhrFields ) { xhr[ i ] = s.xhrFields[ i ]; } } // Override mime type if needed if ( s.mimeType && xhr.overrideMimeType ) { xhr.overrideMimeType( s.mimeType ); } // X-Requested-With header // For cross-domain requests, seeing as conditions for a preflight are // akin to a jigsaw puzzle, we simply never set it to be sure. // (it can always be set on a per-request basis or even using ajaxSetup) // For same-domain requests, won't change header if already provided. if ( !s.crossDomain && !headers["X-Requested-With"] ) { headers["X-Requested-With"] = "XMLHttpRequest"; } // Need an extra try/catch for cross domain requests in Firefox 3 try { for ( i in headers ) { xhr.setRequestHeader( i, headers[ i ] ); } } catch( err ) {} // Do send the request // This may raise an exception which is actually // handled in jQuery.ajax (so no try/catch here) xhr.send( ( s.hasContent && s.data ) || null ); // Listener callback = function( _, isAbort ) { var status, responseHeaders, statusText, responses; // Firefox throws exceptions when accessing properties // of an xhr when a network error occurred // http://helpful.knobs-dials.com/index.php/Component_returned_failure_code:_0x80040111_(NS_ERROR_NOT_AVAILABLE) try { // Was never called and is aborted or complete if ( callback && ( isAbort || xhr.readyState === 4 ) ) { // Only called once callback = undefined; // Do not keep as active anymore if ( handle ) { xhr.onreadystatechange = jQuery.noop; if ( xhrOnUnloadAbort ) { delete xhrCallbacks[ handle ]; } } // If it's an abort if ( isAbort ) { // Abort it manually if needed if ( xhr.readyState !== 4 ) { xhr.abort(); } } else { responses = {}; status = xhr.status; responseHeaders = xhr.getAllResponseHeaders(); // When requesting binary data, IE6-9 will throw an exception // on any attempt to access responseText (#11426) if ( typeof xhr.responseText === "string" ) { responses.text = xhr.responseText; } // Firefox throws an exception when accessing // statusText for faulty cross-domain requests try { statusText = xhr.statusText; } catch( e ) { // We normalize with Webkit giving an empty statusText statusText = ""; } // Filter status for non standard behaviors // If the request is local and we have data: assume a success // (success with no data won't get notified, that's the best we // can do given current implementations) if ( !status && s.isLocal && !s.crossDomain ) { status = responses.text ? 200 : 404; // IE - #1450: sometimes returns 1223 when it should be 204 } else if ( status === 1223 ) { status = 204; } } } } catch( firefoxAccessException ) { if ( !isAbort ) { complete( -1, firefoxAccessException ); } } // Call complete if needed if ( responses ) { complete( status, statusText, responses, responseHeaders ); } }; if ( !s.async ) { // if we're in sync mode we fire the callback callback(); } else if ( xhr.readyState === 4 ) { // (IE6 & IE7) if it's in cache and has been // retrieved directly we need to fire the callback setTimeout( callback ); } else { handle = ++xhrId; if ( xhrOnUnloadAbort ) { // Create the active xhrs callbacks list if needed // and attach the unload handler if ( !xhrCallbacks ) { xhrCallbacks = {}; jQuery( window ).unload( xhrOnUnloadAbort ); } // Add to list of active xhrs callbacks xhrCallbacks[ handle ] = callback; } xhr.onreadystatechange = callback; } }, abort: function() { if ( callback ) { callback( undefined, true ); } } }; } }); } var fxNow, timerId, rfxtypes = /^(?:toggle|show|hide)$/, rfxnum = new RegExp( "^(?:([+-])=|)(" + core_pnum + ")([a-z%]*)$", "i" ), rrun = /queueHooks$/, animationPrefilters = [ defaultPrefilter ], tweeners = { "*": [function( prop, value ) { var end, unit, tween = this.createTween( prop, value ), parts = rfxnum.exec( value ), target = tween.cur(), start = +target || 0, scale = 1, maxIterations = 20; if ( parts ) { end = +parts[2]; unit = parts[3] || ( jQuery.cssNumber[ prop ] ? "" : "px" ); // We need to compute starting value if ( unit !== "px" && start ) { // Iteratively approximate from a nonzero starting point // Prefer the current property, because this process will be trivial if it uses the same units // Fallback to end or a simple constant start = jQuery.css( tween.elem, prop, true ) || end || 1; do { // If previous iteration zeroed out, double until we get *something* // Use a string for doubling factor so we don't accidentally see scale as unchanged below scale = scale || ".5"; // Adjust and apply start = start / scale; jQuery.style( tween.elem, prop, start + unit ); // Update scale, tolerating zero or NaN from tween.cur() // And breaking the loop if scale is unchanged or perfect, or if we've just had enough } while ( scale !== (scale = tween.cur() / target) && scale !== 1 && --maxIterations ); } tween.unit = unit; tween.start = start; // If a +=/-= token was provided, we're doing a relative animation tween.end = parts[1] ? start + ( parts[1] + 1 ) * end : end; } return tween; }] }; // Animations created synchronously will run synchronously function createFxNow() { setTimeout(function() { fxNow = undefined; }); return ( fxNow = jQuery.now() ); } function createTweens( animation, props ) { jQuery.each( props, function( prop, value ) { var collection = ( tweeners[ prop ] || [] ).concat( tweeners[ "*" ] ), index = 0, length = collection.length; for ( ; index < length; index++ ) { if ( collection[ index ].call( animation, prop, value ) ) { // we're done with this property return; } } }); } function Animation( elem, properties, options ) { var result, stopped, index = 0, length = animationPrefilters.length, deferred = jQuery.Deferred().always( function() { // don't match elem in the :animated selector delete tick.elem; }), tick = function() { if ( stopped ) { return false; } var currentTime = fxNow || createFxNow(), remaining = Math.max( 0, animation.startTime + animation.duration - currentTime ), // archaic crash bug won't allow us to use 1 - ( 0.5 || 0 ) (#12497) temp = remaining / animation.duration || 0, percent = 1 - temp, index = 0, length = animation.tweens.length; for ( ; index < length ; index++ ) { animation.tweens[ index ].run( percent ); } deferred.notifyWith( elem, [ animation, percent, remaining ]); if ( percent < 1 && length ) { return remaining; } else { deferred.resolveWith( elem, [ animation ] ); return false; } }, animation = deferred.promise({ elem: elem, props: jQuery.extend( {}, properties ), opts: jQuery.extend( true, { specialEasing: {} }, options ), originalProperties: properties, originalOptions: options, startTime: fxNow || createFxNow(), duration: options.duration, tweens: [], createTween: function( prop, end ) { var tween = jQuery.Tween( elem, animation.opts, prop, end, animation.opts.specialEasing[ prop ] || animation.opts.easing ); animation.tweens.push( tween ); return tween; }, stop: function( gotoEnd ) { var index = 0, // if we are going to the end, we want to run all the tweens // otherwise we skip this part length = gotoEnd ? animation.tweens.length : 0; if ( stopped ) { return this; } stopped = true; for ( ; index < length ; index++ ) { animation.tweens[ index ].run( 1 ); } // resolve when we played the last frame // otherwise, reject if ( gotoEnd ) { deferred.resolveWith( elem, [ animation, gotoEnd ] ); } else { deferred.rejectWith( elem, [ animation, gotoEnd ] ); } return this; } }), props = animation.props; propFilter( props, animation.opts.specialEasing ); for ( ; index < length ; index++ ) { result = animationPrefilters[ index ].call( animation, elem, props, animation.opts ); if ( result ) { return result; } } createTweens( animation, props ); if ( jQuery.isFunction( animation.opts.start ) ) { animation.opts.start.call( elem, animation ); } jQuery.fx.timer( jQuery.extend( tick, { elem: elem, anim: animation, queue: animation.opts.queue }) ); // attach callbacks from options return animation.progress( animation.opts.progress ) .done( animation.opts.done, animation.opts.complete ) .fail( animation.opts.fail ) .always( animation.opts.always ); } function propFilter( props, specialEasing ) { var value, name, index, easing, hooks; // camelCase, specialEasing and expand cssHook pass for ( index in props ) { name = jQuery.camelCase( index ); easing = specialEasing[ name ]; value = props[ index ]; if ( jQuery.isArray( value ) ) { easing = value[ 1 ]; value = props[ index ] = value[ 0 ]; } if ( index !== name ) { props[ name ] = value; delete props[ index ]; } hooks = jQuery.cssHooks[ name ]; if ( hooks && "expand" in hooks ) { value = hooks.expand( value ); delete props[ name ]; // not quite $.extend, this wont overwrite keys already present. // also - reusing 'index' from above because we have the correct "name" for ( index in value ) { if ( !( index in props ) ) { props[ index ] = value[ index ]; specialEasing[ index ] = easing; } } } else { specialEasing[ name ] = easing; } } } jQuery.Animation = jQuery.extend( Animation, { tweener: function( props, callback ) { if ( jQuery.isFunction( props ) ) { callback = props; props = [ "*" ]; } else { props = props.split(" "); } var prop, index = 0, length = props.length; for ( ; index < length ; index++ ) { prop = props[ index ]; tweeners[ prop ] = tweeners[ prop ] || []; tweeners[ prop ].unshift( callback ); } }, prefilter: function( callback, prepend ) { if ( prepend ) { animationPrefilters.unshift( callback ); } else { animationPrefilters.push( callback ); } } }); function defaultPrefilter( elem, props, opts ) { /*jshint validthis:true */ var prop, index, length, value, dataShow, toggle, tween, hooks, oldfire, anim = this, style = elem.style, orig = {}, handled = [], hidden = elem.nodeType && isHidden( elem ); // handle queue: false promises if ( !opts.queue ) { hooks = jQuery._queueHooks( elem, "fx" ); if ( hooks.unqueued == null ) { hooks.unqueued = 0; oldfire = hooks.empty.fire; hooks.empty.fire = function() { if ( !hooks.unqueued ) { oldfire(); } }; } hooks.unqueued++; anim.always(function() { // doing this makes sure that the complete handler will be called // before this completes anim.always(function() { hooks.unqueued--; if ( !jQuery.queue( elem, "fx" ).length ) { hooks.empty.fire(); } }); }); } // height/width overflow pass if ( elem.nodeType === 1 && ( "height" in props || "width" in props ) ) { // Make sure that nothing sneaks out // Record all 3 overflow attributes because IE does not // change the overflow attribute when overflowX and // overflowY are set to the same value opts.overflow = [ style.overflow, style.overflowX, style.overflowY ]; // Set display property to inline-block for height/width // animations on inline elements that are having width/height animated if ( jQuery.css( elem, "display" ) === "inline" && jQuery.css( elem, "float" ) === "none" ) { // inline-level elements accept inline-block; // block-level elements need to be inline with layout if ( !jQuery.support.inlineBlockNeedsLayout || css_defaultDisplay( elem.nodeName ) === "inline" ) { style.display = "inline-block"; } else { style.zoom = 1; } } } if ( opts.overflow ) { style.overflow = "hidden"; if ( !jQuery.support.shrinkWrapBlocks ) { anim.always(function() { style.overflow = opts.overflow[ 0 ]; style.overflowX = opts.overflow[ 1 ]; style.overflowY = opts.overflow[ 2 ]; }); } } // show/hide pass for ( index in props ) { value = props[ index ]; if ( rfxtypes.exec( value ) ) { delete props[ index ]; toggle = toggle || value === "toggle"; if ( value === ( hidden ? "hide" : "show" ) ) { continue; } handled.push( index ); } } length = handled.length; if ( length ) { dataShow = jQuery._data( elem, "fxshow" ) || jQuery._data( elem, "fxshow", {} ); if ( "hidden" in dataShow ) { hidden = dataShow.hidden; } // store state if its toggle - enables .stop().toggle() to "reverse" if ( toggle ) { dataShow.hidden = !hidden; } if ( hidden ) { jQuery( elem ).show(); } else { anim.done(function() { jQuery( elem ).hide(); }); } anim.done(function() { var prop; jQuery._removeData( elem, "fxshow" ); for ( prop in orig ) { jQuery.style( elem, prop, orig[ prop ] ); } }); for ( index = 0 ; index < length ; index++ ) { prop = handled[ index ]; tween = anim.createTween( prop, hidden ? dataShow[ prop ] : 0 ); orig[ prop ] = dataShow[ prop ] || jQuery.style( elem, prop ); if ( !( prop in dataShow ) ) { dataShow[ prop ] = tween.start; if ( hidden ) { tween.end = tween.start; tween.start = prop === "width" || prop === "height" ? 1 : 0; } } } } } function Tween( elem, options, prop, end, easing ) { return new Tween.prototype.init( elem, options, prop, end, easing ); } jQuery.Tween = Tween; Tween.prototype = { constructor: Tween, init: function( elem, options, prop, end, easing, unit ) { this.elem = elem; this.prop = prop; this.easing = easing || "swing"; this.options = options; this.start = this.now = this.cur(); this.end = end; this.unit = unit || ( jQuery.cssNumber[ prop ] ? "" : "px" ); }, cur: function() { var hooks = Tween.propHooks[ this.prop ]; return hooks && hooks.get ? hooks.get( this ) : Tween.propHooks._default.get( this ); }, run: function( percent ) { var eased, hooks = Tween.propHooks[ this.prop ]; if ( this.options.duration ) { this.pos = eased = jQuery.easing[ this.easing ]( percent, this.options.duration * percent, 0, 1, this.options.duration ); } else { this.pos = eased = percent; } this.now = ( this.end - this.start ) * eased + this.start; if ( this.options.step ) { this.options.step.call( this.elem, this.now, this ); } if ( hooks && hooks.set ) { hooks.set( this ); } else { Tween.propHooks._default.set( this ); } return this; } }; Tween.prototype.init.prototype = Tween.prototype; Tween.propHooks = { _default: { get: function( tween ) { var result; if ( tween.elem[ tween.prop ] != null && (!tween.elem.style || tween.elem.style[ tween.prop ] == null) ) { return tween.elem[ tween.prop ]; } // passing an empty string as a 3rd parameter to .css will automatically // attempt a parseFloat and fallback to a string if the parse fails // so, simple values such as "10px" are parsed to Float. // complex values such as "rotate(1rad)" are returned as is. result = jQuery.css( tween.elem, tween.prop, "" ); // Empty strings, null, undefined and "auto" are converted to 0. return !result || result === "auto" ? 0 : result; }, set: function( tween ) { // use step hook for back compat - use cssHook if its there - use .style if its // available and use plain properties where available if ( jQuery.fx.step[ tween.prop ] ) { jQuery.fx.step[ tween.prop ]( tween ); } else if ( tween.elem.style && ( tween.elem.style[ jQuery.cssProps[ tween.prop ] ] != null || jQuery.cssHooks[ tween.prop ] ) ) { jQuery.style( tween.elem, tween.prop, tween.now + tween.unit ); } else { tween.elem[ tween.prop ] = tween.now; } } } }; // Remove in 2.0 - this supports IE8's panic based approach // to setting things on disconnected nodes Tween.propHooks.scrollTop = Tween.propHooks.scrollLeft = { set: function( tween ) { if ( tween.elem.nodeType && tween.elem.parentNode ) { tween.elem[ tween.prop ] = tween.now; } } }; jQuery.each([ "toggle", "show", "hide" ], function( i, name ) { var cssFn = jQuery.fn[ name ]; jQuery.fn[ name ] = function( speed, easing, callback ) { return speed == null || typeof speed === "boolean" ? cssFn.apply( this, arguments ) : this.animate( genFx( name, true ), speed, easing, callback ); }; }); jQuery.fn.extend({ fadeTo: function( speed, to, easing, callback ) { // show any hidden elements after setting opacity to 0 return this.filter( isHidden ).css( "opacity", 0 ).show() // animate to the value specified .end().animate({ opacity: to }, speed, easing, callback ); }, animate: function( prop, speed, easing, callback ) { var empty = jQuery.isEmptyObject( prop ), optall = jQuery.speed( speed, easing, callback ), doAnimation = function() { // Operate on a copy of prop so per-property easing won't be lost var anim = Animation( this, jQuery.extend( {}, prop ), optall ); doAnimation.finish = function() { anim.stop( true ); }; // Empty animations, or finishing resolves immediately if ( empty || jQuery._data( this, "finish" ) ) { anim.stop( true ); } }; doAnimation.finish = doAnimation; return empty || optall.queue === false ? this.each( doAnimation ) : this.queue( optall.queue, doAnimation ); }, stop: function( type, clearQueue, gotoEnd ) { var stopQueue = function( hooks ) { var stop = hooks.stop; delete hooks.stop; stop( gotoEnd ); }; if ( typeof type !== "string" ) { gotoEnd = clearQueue; clearQueue = type; type = undefined; } if ( clearQueue && type !== false ) { this.queue( type || "fx", [] ); } return this.each(function() { var dequeue = true, index = type != null && type + "queueHooks", timers = jQuery.timers, data = jQuery._data( this ); if ( index ) { if ( data[ index ] && data[ index ].stop ) { stopQueue( data[ index ] ); } } else { for ( index in data ) { if ( data[ index ] && data[ index ].stop && rrun.test( index ) ) { stopQueue( data[ index ] ); } } } for ( index = timers.length; index--; ) { if ( timers[ index ].elem === this && (type == null || timers[ index ].queue === type) ) { timers[ index ].anim.stop( gotoEnd ); dequeue = false; timers.splice( index, 1 ); } } // start the next in the queue if the last step wasn't forced // timers currently will call their complete callbacks, which will dequeue // but only if they were gotoEnd if ( dequeue || !gotoEnd ) { jQuery.dequeue( this, type ); } }); }, finish: function( type ) { if ( type !== false ) { type = type || "fx"; } return this.each(function() { var index, data = jQuery._data( this ), queue = data[ type + "queue" ], hooks = data[ type + "queueHooks" ], timers = jQuery.timers, length = queue ? queue.length : 0; // enable finishing flag on private data data.finish = true; // empty the queue first jQuery.queue( this, type, [] ); if ( hooks && hooks.cur && hooks.cur.finish ) { hooks.cur.finish.call( this ); } // look for any active animations, and finish them for ( index = timers.length; index--; ) { if ( timers[ index ].elem === this && timers[ index ].queue === type ) { timers[ index ].anim.stop( true ); timers.splice( index, 1 ); } } // look for any animations in the old queue and finish them for ( index = 0; index < length; index++ ) { if ( queue[ index ] && queue[ index ].finish ) { queue[ index ].finish.call( this ); } } // turn off finishing flag delete data.finish; }); } }); // Generate parameters to create a standard animation function genFx( type, includeWidth ) { var which, attrs = { height: type }, i = 0; // if we include width, step value is 1 to do all cssExpand values, // if we don't include width, step value is 2 to skip over Left and Right includeWidth = includeWidth? 1 : 0; for( ; i < 4 ; i += 2 - includeWidth ) { which = cssExpand[ i ]; attrs[ "margin" + which ] = attrs[ "padding" + which ] = type; } if ( includeWidth ) { attrs.opacity = attrs.width = type; } return attrs; } // Generate shortcuts for custom animations jQuery.each({ slideDown: genFx("show"), slideUp: genFx("hide"), slideToggle: genFx("toggle"), fadeIn: { opacity: "show" }, fadeOut: { opacity: "hide" }, fadeToggle: { opacity: "toggle" } }, function( name, props ) { jQuery.fn[ name ] = function( speed, easing, callback ) { return this.animate( props, speed, easing, callback ); }; }); jQuery.speed = function( speed, easing, fn ) { var opt = speed && typeof speed === "object" ? jQuery.extend( {}, speed ) : { complete: fn || !fn && easing || jQuery.isFunction( speed ) && speed, duration: speed, easing: fn && easing || easing && !jQuery.isFunction( easing ) && easing }; opt.duration = jQuery.fx.off ? 0 : typeof opt.duration === "number" ? opt.duration : opt.duration in jQuery.fx.speeds ? jQuery.fx.speeds[ opt.duration ] : jQuery.fx.speeds._default; // normalize opt.queue - true/undefined/null -> "fx" if ( opt.queue == null || opt.queue === true ) { opt.queue = "fx"; } // Queueing opt.old = opt.complete; opt.complete = function() { if ( jQuery.isFunction( opt.old ) ) { opt.old.call( this ); } if ( opt.queue ) { jQuery.dequeue( this, opt.queue ); } }; return opt; }; jQuery.easing = { linear: function( p ) { return p; }, swing: function( p ) { return 0.5 - Math.cos( p*Math.PI ) / 2; } }; jQuery.timers = []; jQuery.fx = Tween.prototype.init; jQuery.fx.tick = function() { var timer, timers = jQuery.timers, i = 0; fxNow = jQuery.now(); for ( ; i < timers.length; i++ ) { timer = timers[ i ]; // Checks the timer has not already been removed if ( !timer() && timers[ i ] === timer ) { timers.splice( i--, 1 ); } } if ( !timers.length ) { jQuery.fx.stop(); } fxNow = undefined; }; jQuery.fx.timer = function( timer ) { if ( timer() && jQuery.timers.push( timer ) ) { jQuery.fx.start(); } }; jQuery.fx.interval = 13; jQuery.fx.start = function() { if ( !timerId ) { timerId = setInterval( jQuery.fx.tick, jQuery.fx.interval ); } }; jQuery.fx.stop = function() { clearInterval( timerId ); timerId = null; }; jQuery.fx.speeds = { slow: 600, fast: 200, // Default speed _default: 400 }; // Back Compat <1.8 extension point jQuery.fx.step = {}; if ( jQuery.expr && jQuery.expr.filters ) { jQuery.expr.filters.animated = function( elem ) { return jQuery.grep(jQuery.timers, function( fn ) { return elem === fn.elem; }).length; }; } jQuery.fn.offset = function( options ) { if ( arguments.length ) { return options === undefined ? this : this.each(function( i ) { jQuery.offset.setOffset( this, options, i ); }); } var docElem, win, box = { top: 0, left: 0 }, elem = this[ 0 ], doc = elem && elem.ownerDocument; if ( !doc ) { return; } docElem = doc.documentElement; // Make sure it's not a disconnected DOM node if ( !jQuery.contains( docElem, elem ) ) { return box; } // If we don't have gBCR, just use 0,0 rather than error // BlackBerry 5, iOS 3 (original iPhone) if ( typeof elem.getBoundingClientRect !== core_strundefined ) { box = elem.getBoundingClientRect(); } win = getWindow( doc ); return { top: box.top + ( win.pageYOffset || docElem.scrollTop ) - ( docElem.clientTop || 0 ), left: box.left + ( win.pageXOffset || docElem.scrollLeft ) - ( docElem.clientLeft || 0 ) }; }; jQuery.offset = { setOffset: function( elem, options, i ) { var position = jQuery.css( elem, "position" ); // set position first, in-case top/left are set even on static elem if ( position === "static" ) { elem.style.position = "relative"; } var curElem = jQuery( elem ), curOffset = curElem.offset(), curCSSTop = jQuery.css( elem, "top" ), curCSSLeft = jQuery.css( elem, "left" ), calculatePosition = ( position === "absolute" || position === "fixed" ) && jQuery.inArray("auto", [curCSSTop, curCSSLeft]) > -1, props = {}, curPosition = {}, curTop, curLeft; // need to be able to calculate position if either top or left is auto and position is either absolute or fixed if ( calculatePosition ) { curPosition = curElem.position(); curTop = curPosition.top; curLeft = curPosition.left; } else { curTop = parseFloat( curCSSTop ) || 0; curLeft = parseFloat( curCSSLeft ) || 0; } if ( jQuery.isFunction( options ) ) { options = options.call( elem, i, curOffset ); } if ( options.top != null ) { props.top = ( options.top - curOffset.top ) + curTop; } if ( options.left != null ) { props.left = ( options.left - curOffset.left ) + curLeft; } if ( "using" in options ) { options.using.call( elem, props ); } else { curElem.css( props ); } } }; jQuery.fn.extend({ position: function() { if ( !this[ 0 ] ) { return; } var offsetParent, offset, parentOffset = { top: 0, left: 0 }, elem = this[ 0 ]; // fixed elements are offset from window (parentOffset = {top:0, left: 0}, because it is it's only offset parent if ( jQuery.css( elem, "position" ) === "fixed" ) { // we assume that getBoundingClientRect is available when computed position is fixed offset = elem.getBoundingClientRect(); } else { // Get *real* offsetParent offsetParent = this.offsetParent(); // Get correct offsets offset = this.offset(); if ( !jQuery.nodeName( offsetParent[ 0 ], "html" ) ) { parentOffset = offsetParent.offset(); } // Add offsetParent borders parentOffset.top += jQuery.css( offsetParent[ 0 ], "borderTopWidth", true ); parentOffset.left += jQuery.css( offsetParent[ 0 ], "borderLeftWidth", true ); } // Subtract parent offsets and element margins // note: when an element has margin: auto the offsetLeft and marginLeft // are the same in Safari causing offset.left to incorrectly be 0 return { top: offset.top - parentOffset.top - jQuery.css( elem, "marginTop", true ), left: offset.left - parentOffset.left - jQuery.css( elem, "marginLeft", true) }; }, offsetParent: function() { return this.map(function() { var offsetParent = this.offsetParent || document.documentElement; while ( offsetParent && ( !jQuery.nodeName( offsetParent, "html" ) && jQuery.css( offsetParent, "position") === "static" ) ) { offsetParent = offsetParent.offsetParent; } return offsetParent || document.documentElement; }); } }); // Create scrollLeft and scrollTop methods jQuery.each( {scrollLeft: "pageXOffset", scrollTop: "pageYOffset"}, function( method, prop ) { var top = /Y/.test( prop ); jQuery.fn[ method ] = function( val ) { return jQuery.access( this, function( elem, method, val ) { var win = getWindow( elem ); if ( val === undefined ) { return win ? (prop in win) ? win[ prop ] : win.document.documentElement[ method ] : elem[ method ]; } if ( win ) { win.scrollTo( !top ? val : jQuery( win ).scrollLeft(), top ? val : jQuery( win ).scrollTop() ); } else { elem[ method ] = val; } }, method, val, arguments.length, null ); }; }); function getWindow( elem ) { return jQuery.isWindow( elem ) ? elem : elem.nodeType === 9 ? elem.defaultView || elem.parentWindow : false; } // Create innerHeight, innerWidth, height, width, outerHeight and outerWidth methods jQuery.each( { Height: "height", Width: "width" }, function( name, type ) { jQuery.each( { padding: "inner" + name, content: type, "": "outer" + name }, function( defaultExtra, funcName ) { // margin is only for outerHeight, outerWidth jQuery.fn[ funcName ] = function( margin, value ) { var chainable = arguments.length && ( defaultExtra || typeof margin !== "boolean" ), extra = defaultExtra || ( margin === true || value === true ? "margin" : "border" ); return jQuery.access( this, function( elem, type, value ) { var doc; if ( jQuery.isWindow( elem ) ) { // As of 5/8/2012 this will yield incorrect results for Mobile Safari, but there // isn't a whole lot we can do. See pull request at this URL for discussion: // https://github.com/jquery/jquery/pull/764 return elem.document.documentElement[ "client" + name ]; } // Get document width or height if ( elem.nodeType === 9 ) { doc = elem.documentElement; // Either scroll[Width/Height] or offset[Width/Height] or client[Width/Height], whichever is greatest // unfortunately, this causes bug #3838 in IE6/8 only, but there is currently no good, small way to fix it. return Math.max( elem.body[ "scroll" + name ], doc[ "scroll" + name ], elem.body[ "offset" + name ], doc[ "offset" + name ], doc[ "client" + name ] ); } return value === undefined ? // Get width or height on the element, requesting but not forcing parseFloat jQuery.css( elem, type, extra ) : // Set width or height on the element jQuery.style( elem, type, value, extra ); }, type, chainable ? margin : undefined, chainable, null ); }; }); }); // Limit scope pollution from any deprecated API // (function() { // })(); // Expose jQuery to the global object window.jQuery = window.$ = jQuery; // Expose jQuery as an AMD module, but only for AMD loaders that // understand the issues with loading multiple versions of jQuery // in a page that all might call define(). The loader will indicate // they have special allowances for multiple jQuery versions by // specifying define.amd.jQuery = true. Register as a named module, // since jQuery can be concatenated with other files that may use define, // but not use a proper concatenation script that understands anonymous // AMD modules. A named AMD is safest and most robust way to register. // Lowercase jquery is used because AMD module names are derived from // file names, and jQuery is normally delivered in a lowercase file name. // Do this after creating the global so that if an AMD module wants to call // noConflict to hide this version of jQuery, it will work. if ( typeof define === "function" && define.amd && define.amd.jQuery ) { define( "jquery", [], function () { return jQuery; } ); } })( window );
src/components/LinkInput.js
ZachGawlik/print-to-resist
import PropTypes from 'prop-types'; import React from 'react'; import '../styles/LinkInput.css'; class LinkInput extends React.Component { handleUrlChange = event => { this.props.onUrlChange(this.props.index, event.target.value); }; handleDeleteClick = () => { this.props.onDeleteLink(this.props.index); }; render() { return ( <div className="LinkInput"> <input type="url" onChange={this.handleUrlChange} value={this.props.url} /> <button className="LinkInput__remove" type="button" onClick={this.handleDeleteClick} > - </button> </div> ); } } LinkInput.propTypes = { index: PropTypes.number.isRequired, onUrlChange: PropTypes.func.isRequired, onDeleteLink: PropTypes.func.isRequired, url: PropTypes.string.isRequired }; export default LinkInput;
src/container/TaggedEntrypoints.js
legendecas/material-swagger-ui
import { connect } from 'react-redux'; import _ from 'lodash'; import EntrypointList from '../component/EntrypointLists'; const TaggedEntrypoints = connect( state => ({ lists: _.map(state.definition.tags, tag => ({ title: tag.name, description: tag.description, entrypoints: _.filter(state.definition.entrypoints, entrypoint => _.includes(entrypoint.operation.tags, tag.name)), })), }), () => ({}) )(EntrypointList); export default TaggedEntrypoints;
src/index.js
codyloyd/teamup
import React from 'react' import ReactDOM from 'react-dom' import Root from './components/root' import './index.css' import configureFirebase from './configureFirebase' import configureStore from './configureStore' import appReducer from './reducer' // these imports are useful for testing.. but I keep them commented // so that they aren't imported when we aren't using them. // import * as projects from './project/projects-reducer' // import * as roles from './project/roles-reducer' // import * as applications from './application/applications-reducer' import * as users from './user/users-reducer' // import * as api from './api' const store = configureStore(appReducer) configureFirebase(store.dispatch) store.dispatch(users.fetchUser('01')) ReactDOM.render(<Root store={store} />, document.getElementById('root'))
samples/src/components/FormFiddleWrapper/FormFiddleWrapper.react.js
codazen/formulationjs
'use strict'; require('./css/FormFiddleWrapper.less'); import React from 'react'; import Form from '../../../../src/components/Form.react'; import Fiddle from '../Fiddle/Fiddle.react'; class FormFiddleWrapper extends React.Component { constructor(props) { super(props); this.state = { form: this.props.form }; this.fiddleSubmit = this.fiddleSubmit.bind(this); } fiddleSubmit(json) { this.setState({ form: json }); } render() { var { form } = this.state; return ( <div className="wrapper"> <div className="panel left"> <Form form={form} /> </div> <div className="panel"> <Fiddle json={form} fiddleSubmit={this.fiddleSubmit} /> </div> </div> ); } } export default FormFiddleWrapper;
tests/react_children/tabs.js
facebook/flow
// @flow /** * This test represents a pattern which is commonly used to make tab bars, but * this pattern is also used in many other places. */ import React from 'react'; class Tab extends React.Component<{}, void> {} class NotTab extends React.Component<{}, void> {} type TabBarNode = | void | null | boolean | React$Element<typeof Tab> | Array<TabBarNode>; // NOTE: This is intentionally `Array<T>` and not // `Iterable<T>` because `strings` are `Iterable<string>` // which is then `Iterable<Iterable<string>>` recursively // making strings valid children when we use // `Iterable<T>`. class TabBar extends React.Component<{children: TabBarNode}, void> {} <TabBar />; // Error: `children` is required. <TabBar><Tab/></TabBar>; // OK: We can have a single tab. <TabBar><Tab/><Tab/></TabBar>; // OK: We can have two tabs. <TabBar> <Tab/><Tab/></TabBar>; // Error: Spaces are strings. <TabBar><Tab/> <Tab/></TabBar>; // Error: Spaces are strings. <TabBar><Tab/><Tab/> </TabBar>; // Error: Spaces are strings. // OK: We can have a single tab on multiple lines. <TabBar> <Tab/> </TabBar>; // OK: We can have a multiple tabs on multiple lines. <TabBar> <Tab/> <Tab/> <Tab/> </TabBar>; // OK: We can have an array of tabs. <TabBar> {[ <Tab/>, <Tab/>, <Tab/>, ]} </TabBar>; // OK: We can have two arrays of tabs. <TabBar> {[ <Tab/>, <Tab/>, ]} {[ <Tab/>, <Tab/>, ]} </TabBar>; <TabBar><NotTab/></TabBar>; // Error: We can only have tab components. <TabBar><NotTab/><NotTab/></TabBar>; // Error: We can only have tab components. // Error: Nope, can't sneak a non-tab in there. <TabBar> <Tab/> <NotTab/> <Tab/> <Tab/> </TabBar>; // OK: Booleans are allowed in the type. <TabBar> {Math.random() > 0.5 && <Tab/>} </TabBar>; // OK: Booleans are allowed in the type. <TabBar> {Math.random() > 0.5 && <Tab/>} {Math.random() > 0.5 && <Tab/>} </TabBar>;
packages/es-components/src/components/navigation/horizontalnav/HorizontalNav.specs.js
jrios/es-components
/* eslint-env jest */ import React from 'react'; import { renderWithTheme } from '../../util/test-utils'; import HorizontalNav from './HorizontalNav'; let instanceToRender; const onClick = jest.fn(); beforeEach(() => { onClick.mockClear(); instanceToRender = ( <HorizontalNav selected="home"> <HorizontalNav.Item id="home" className="home"> <button type="button" onClick={onClick}> Home </button> </HorizontalNav.Item> <HorizontalNav.Item id="cart"> <button type="button">Cart</button> </HorizontalNav.Item> <HorizontalNav.Item id="external"> <a href="https://google.com">External Link</a> </HorizontalNav.Item> <HorizontalNav.Item id="info" onClick={onClick} isDisabled> <button type="button">Disabled</button> </HorizontalNav.Item> </HorizontalNav> ); }); it('renders as expected', () => { const { container } = renderWithTheme(instanceToRender); expect(container).toMatchSnapshot(); }); it('executes onClick when nav item clicked', () => { const { getByText } = renderWithTheme(instanceToRender); getByText('Home').click(); expect(onClick).toHaveBeenCalled(); }); it('disabled item prevents onclick functions', () => { const { getByText } = renderWithTheme(instanceToRender); getByText('Disabled').click(); expect(onClick).not.toBeCalled(); });
src/control/content/index.js
BuildFire/placesPlugin2
import React from 'react'; import { render } from 'react-dom'; import Content from './content'; const container = document.getElementById('mount'); function renderApp() { render(<Content />, container); } // Setup HMR re-rendering if (module.hot) { module.hot.accept(); module.hot.accept('./content', renderApp); } // Initial render renderApp();
src/views/NotFoundView/NotFoundView.js
jwoods1/xpress
import React from 'react' import '../../../Libs/styles/bootstrap.css' import '../../../Libs/styles/bootstrap-extend.css' import '../../../Libs/styles/site.css' import '../../../Libs/styles/errors.scss' import { Link } from 'react-router' export class NotFoundView extends React.Component { render () { return ( <div className="row text-center"> <div className="col-md-5 col-md-offset-3"> <header> <h1 className="animation-slide-top">404</h1> <p>Page Not Found !</p> </header> <p className="error-advise">YOU SEEM TO BE TRYING TO FIND HIS WAY HOME</p> <Link className="btn btn-primary btn-round" to="/">GO TO HOME PAGE</Link> <footer className="page-copyright"> <p>WEBSITE BY XpressDesign</p> <p>© 2015. All RIGHT RESERVED.</p> </footer> </div> </div> ) } } export default NotFoundView
src/js/app/app.js
dupengdl/kickoffreact
import React, { Component } from 'react'; export default class App extends Component { render() { return ( <div> <h1 className="hello">Hello, world!</h1> <div className="world">test</div> </div> ); } }
js/jqwidgets/demos/react/app/navbar/minimizednavbar/app.js
luissancheza/sice
import React from 'react'; import ReactDOM from 'react-dom'; import JqxNavBar from '../../../jqwidgets-react/react_jqxnavbar.js'; class App extends React.Component { render() { return ( <JqxNavBar height={'auto'} selection={false}> <ul> <li>Minimized NavBar with Vertical Layout <JqxNavBar height={120} selectedItem={0} minimized={true} minimizedHeight={40} orientation={'vertical'} minimizedTitle={'NavBar 1'} > <ul> <li>1</li> <li>2</li> <li>3</li> </ul> </JqxNavBar> </li> <li>Minimized NavBar with Horizontal Layout <JqxNavBar height={120} selectedItem={0} minimized={true} minimizedHeight={40} minimizedTitle={'NavBar 2'} > <ul> <li>1</li> <li>2</li> <li>3</li> </ul> </JqxNavBar> </li> </ul> </JqxNavBar> ) } } ReactDOM.render(<App />, document.getElementById('app'));
app/javascript/flavours/glitch/features/compose/components/dropdown.js
im-in-space/mastodon
// Package imports. import classNames from 'classnames'; import PropTypes from 'prop-types'; import React from 'react'; import Overlay from 'react-overlays/lib/Overlay'; // Components. import IconButton from 'flavours/glitch/components/icon_button'; import DropdownMenu from './dropdown_menu'; // Utils. import { isUserTouching } from 'flavours/glitch/util/is_mobile'; import { assignHandlers } from 'flavours/glitch/util/react_helpers'; // The component. export default class ComposerOptionsDropdown extends React.PureComponent { static propTypes = { active: PropTypes.bool, disabled: PropTypes.bool, icon: PropTypes.string, items: PropTypes.arrayOf(PropTypes.shape({ icon: PropTypes.string, meta: PropTypes.string, name: PropTypes.string.isRequired, text: PropTypes.string, })).isRequired, onModalOpen: PropTypes.func, onModalClose: PropTypes.func, title: PropTypes.string, value: PropTypes.string, onChange: PropTypes.func, container: PropTypes.func, renderItemContents: PropTypes.func, closeOnChange: PropTypes.bool, }; static defaultProps = { closeOnChange: true, }; state = { open: false, openedViaKeyboard: undefined, placement: 'bottom', }; // Toggles opening and closing the dropdown. handleToggle = ({ target, type }) => { const { onModalOpen } = this.props; const { open } = this.state; if (isUserTouching()) { if (this.state.open) { this.props.onModalClose(); } else { const modal = this.handleMakeModal(); if (modal && onModalOpen) { onModalOpen(modal); } } } else { const { top } = target.getBoundingClientRect(); if (this.state.open && this.activeElement) { this.activeElement.focus({ preventScroll: true }); } this.setState({ placement: top * 2 < innerHeight ? 'bottom' : 'top' }); this.setState({ open: !this.state.open, openedViaKeyboard: type !== 'click' }); } } handleKeyDown = (e) => { switch (e.key) { case 'Escape': this.handleClose(); break; } } handleMouseDown = () => { if (!this.state.open) { this.activeElement = document.activeElement; } } handleButtonKeyDown = (e) => { switch(e.key) { case ' ': case 'Enter': this.handleMouseDown(); break; } } handleKeyPress = (e) => { switch(e.key) { case ' ': case 'Enter': this.handleToggle(e); e.stopPropagation(); e.preventDefault(); break; } } handleClose = () => { if (this.state.open && this.activeElement) { this.activeElement.focus({ preventScroll: true }); } this.setState({ open: false }); } handleItemClick = (e) => { const { items, onChange, onModalClose, closeOnChange, } = this.props; const i = Number(e.currentTarget.getAttribute('data-index')); const { name } = items[i]; e.preventDefault(); // Prevents focus from changing if (closeOnChange) onModalClose(); onChange(name); }; // Creates an action modal object. handleMakeModal = () => { const { items, onChange, onModalOpen, onModalClose, value, } = this.props; // Required props. if (!(onChange && onModalOpen && onModalClose && items)) { return null; } // The object. return { renderItemContents: this.props.renderItemContents, onClick: this.handleItemClick, actions: items.map( ({ name, ...rest }) => ({ ...rest, active: value && name === value, name, }) ), }; } // Rendering. render () { const { active, disabled, title, icon, items, onChange, value, container, renderItemContents, closeOnChange, } = this.props; const { open, placement } = this.state; const computedClass = classNames('composer--options--dropdown', { active, open, top: placement === 'top', }); // The result. return ( <div className={computedClass} onKeyDown={this.handleKeyDown} > <IconButton active={open || active} className='value' disabled={disabled} icon={icon} inverted onClick={this.handleToggle} onMouseDown={this.handleMouseDown} onKeyDown={this.handleButtonKeyDown} onKeyPress={this.handleKeyPress} size={18} style={{ height: null, lineHeight: '27px', }} title={title} /> <Overlay containerPadding={20} placement={placement} show={open} target={this} container={container} > <DropdownMenu items={items} renderItemContents={renderItemContents} onChange={onChange} onClose={this.handleClose} value={value} openedViaKeyboard={this.state.openedViaKeyboard} closeOnChange={closeOnChange} /> </Overlay> </div> ); } }
src/app/index.js
ericvandevprod/redux-d3
import React from 'react'; import ReactDOM from 'react-dom'; import { Provider } from 'react-redux'; import { createStore, applyMiddleware } from 'redux'; import ReduxPromise from 'redux-promise'; import AppContainer from './containers/App/App'; import reducers from './reducers'; const rootEl = document.getElementById('app'); const createStoreWithMiddleware = applyMiddleware(ReduxPromise)(createStore); const render = () => { ReactDOM.render( <Provider store={createStoreWithMiddleware(reducers)}> <AppContainer /> </Provider>, rootEl ); }; render();
ajax/libs/yui/3.5.0pr3/event-custom-base/event-custom-base-debug.js
Teino1978-Corp/Teino1978-Corp-cdnjs
YUI.add('event-custom-base', function(Y) { /** * Custom event engine, DOM event listener abstraction layer, synthetic DOM * events. * @module event-custom */ Y.Env.evt = { handles: {}, plugins: {} }; /** * Custom event engine, DOM event listener abstraction layer, synthetic DOM * events. * @module event-custom * @submodule event-custom-base */ /** * Allows for the insertion of methods that are executed before or after * a specified method * @class Do * @static */ var DO_BEFORE = 0, DO_AFTER = 1, DO = { /** * Cache of objects touched by the utility * @property objs * @static */ objs: {}, /** * <p>Execute the supplied method before the specified function. Wrapping * function may optionally return an instance of the following classes to * further alter runtime behavior:</p> * <dl> * <dt></code>Y.Do.Halt(message, returnValue)</code></dt> * <dd>Immediatly stop execution and return * <code>returnValue</code>. No other wrapping functions will be * executed.</dd> * <dt></code>Y.Do.AlterArgs(message, newArgArray)</code></dt> * <dd>Replace the arguments that the original function will be * called with.</dd> * <dt></code>Y.Do.Prevent(message)</code></dt> * <dd>Don't execute the wrapped function. Other before phase * wrappers will be executed.</dd> * </dl> * * @method before * @param fn {Function} the function to execute * @param obj the object hosting the method to displace * @param sFn {string} the name of the method to displace * @param c The execution context for fn * @param arg* {mixed} 0..n additional arguments to supply to the subscriber * when the event fires. * @return {string} handle for the subscription * @static */ before: function(fn, obj, sFn, c) { // Y.log('Do before: ' + sFn, 'info', 'event'); var f = fn, a; if (c) { a = [fn, c].concat(Y.Array(arguments, 4, true)); f = Y.rbind.apply(Y, a); } return this._inject(DO_BEFORE, f, obj, sFn); }, /** * <p>Execute the supplied method after the specified function. Wrapping * function may optionally return an instance of the following classes to * further alter runtime behavior:</p> * <dl> * <dt></code>Y.Do.Halt(message, returnValue)</code></dt> * <dd>Immediatly stop execution and return * <code>returnValue</code>. No other wrapping functions will be * executed.</dd> * <dt></code>Y.Do.AlterReturn(message, returnValue)</code></dt> * <dd>Return <code>returnValue</code> instead of the wrapped * method's original return value. This can be further altered by * other after phase wrappers.</dd> * </dl> * * <p>The static properties <code>Y.Do.originalRetVal</code> and * <code>Y.Do.currentRetVal</code> will be populated for reference.</p> * * @method after * @param fn {Function} the function to execute * @param obj the object hosting the method to displace * @param sFn {string} the name of the method to displace * @param c The execution context for fn * @param arg* {mixed} 0..n additional arguments to supply to the subscriber * @return {string} handle for the subscription * @static */ after: function(fn, obj, sFn, c) { var f = fn, a; if (c) { a = [fn, c].concat(Y.Array(arguments, 4, true)); f = Y.rbind.apply(Y, a); } return this._inject(DO_AFTER, f, obj, sFn); }, /** * Execute the supplied method before or after the specified function. * Used by <code>before</code> and <code>after</code>. * * @method _inject * @param when {string} before or after * @param fn {Function} the function to execute * @param obj the object hosting the method to displace * @param sFn {string} the name of the method to displace * @param c The execution context for fn * @return {string} handle for the subscription * @private * @static */ _inject: function(when, fn, obj, sFn) { // object id var id = Y.stamp(obj), o, sid; if (! this.objs[id]) { // create a map entry for the obj if it doesn't exist this.objs[id] = {}; } o = this.objs[id]; if (! o[sFn]) { // create a map entry for the method if it doesn't exist o[sFn] = new Y.Do.Method(obj, sFn); // re-route the method to our wrapper obj[sFn] = function() { return o[sFn].exec.apply(o[sFn], arguments); }; } // subscriber id sid = id + Y.stamp(fn) + sFn; // register the callback o[sFn].register(sid, fn, when); return new Y.EventHandle(o[sFn], sid); }, /** * Detach a before or after subscription. * * @method detach * @param handle {string} the subscription handle * @static */ detach: function(handle) { if (handle.detach) { handle.detach(); } }, _unload: function(e, me) { } }; Y.Do = DO; ////////////////////////////////////////////////////////////////////////// /** * Contains the return value from the wrapped method, accessible * by 'after' event listeners. * * @property originalRetVal * @static * @since 3.2.0 */ /** * Contains the current state of the return value, consumable by * 'after' event listeners, and updated if an after subscriber * changes the return value generated by the wrapped function. * * @property currentRetVal * @static * @since 3.2.0 */ ////////////////////////////////////////////////////////////////////////// /** * Wrapper for a displaced method with aop enabled * @class Do.Method * @constructor * @param obj The object to operate on * @param sFn The name of the method to displace */ DO.Method = function(obj, sFn) { this.obj = obj; this.methodName = sFn; this.method = obj[sFn]; this.before = {}; this.after = {}; }; /** * Register a aop subscriber * @method register * @param sid {string} the subscriber id * @param fn {Function} the function to execute * @param when {string} when to execute the function */ DO.Method.prototype.register = function (sid, fn, when) { if (when) { this.after[sid] = fn; } else { this.before[sid] = fn; } }; /** * Unregister a aop subscriber * @method delete * @param sid {string} the subscriber id * @param fn {Function} the function to execute * @param when {string} when to execute the function */ DO.Method.prototype._delete = function (sid) { // Y.log('Y.Do._delete: ' + sid, 'info', 'Event'); delete this.before[sid]; delete this.after[sid]; }; /** * <p>Execute the wrapped method. All arguments are passed into the wrapping * functions. If any of the before wrappers return an instance of * <code>Y.Do.Halt</code> or <code>Y.Do.Prevent</code>, neither the wrapped * function nor any after phase subscribers will be executed.</p> * * <p>The return value will be the return value of the wrapped function or one * provided by a wrapper function via an instance of <code>Y.Do.Halt</code> or * <code>Y.Do.AlterReturn</code>. * * @method exec * @param arg* {any} Arguments are passed to the wrapping and wrapped functions * @return {any} Return value of wrapped function unless overwritten (see above) */ DO.Method.prototype.exec = function () { var args = Y.Array(arguments, 0, true), i, ret, newRet, bf = this.before, af = this.after, prevented = false; // execute before for (i in bf) { if (bf.hasOwnProperty(i)) { ret = bf[i].apply(this.obj, args); if (ret) { switch (ret.constructor) { case DO.Halt: return ret.retVal; case DO.AlterArgs: args = ret.newArgs; break; case DO.Prevent: prevented = true; break; default: } } } } // execute method if (!prevented) { ret = this.method.apply(this.obj, args); } DO.originalRetVal = ret; DO.currentRetVal = ret; // execute after methods. for (i in af) { if (af.hasOwnProperty(i)) { newRet = af[i].apply(this.obj, args); // Stop processing if a Halt object is returned if (newRet && newRet.constructor == DO.Halt) { return newRet.retVal; // Check for a new return value } else if (newRet && newRet.constructor == DO.AlterReturn) { ret = newRet.newRetVal; // Update the static retval state DO.currentRetVal = ret; } } } return ret; }; ////////////////////////////////////////////////////////////////////////// /** * Return an AlterArgs object when you want to change the arguments that * were passed into the function. Useful for Do.before subscribers. An * example would be a service that scrubs out illegal characters prior to * executing the core business logic. * @class Do.AlterArgs * @constructor * @param msg {String} (optional) Explanation of the altered return value * @param newArgs {Array} Call parameters to be used for the original method * instead of the arguments originally passed in. */ DO.AlterArgs = function(msg, newArgs) { this.msg = msg; this.newArgs = newArgs; }; /** * Return an AlterReturn object when you want to change the result returned * from the core method to the caller. Useful for Do.after subscribers. * @class Do.AlterReturn * @constructor * @param msg {String} (optional) Explanation of the altered return value * @param newRetVal {any} Return value passed to code that invoked the wrapped * function. */ DO.AlterReturn = function(msg, newRetVal) { this.msg = msg; this.newRetVal = newRetVal; }; /** * Return a Halt object when you want to terminate the execution * of all subsequent subscribers as well as the wrapped method * if it has not exectued yet. Useful for Do.before subscribers. * @class Do.Halt * @constructor * @param msg {String} (optional) Explanation of why the termination was done * @param retVal {any} Return value passed to code that invoked the wrapped * function. */ DO.Halt = function(msg, retVal) { this.msg = msg; this.retVal = retVal; }; /** * Return a Prevent object when you want to prevent the wrapped function * from executing, but want the remaining listeners to execute. Useful * for Do.before subscribers. * @class Do.Prevent * @constructor * @param msg {String} (optional) Explanation of why the termination was done */ DO.Prevent = function(msg) { this.msg = msg; }; /** * Return an Error object when you want to terminate the execution * of all subsequent method calls. * @class Do.Error * @constructor * @param msg {String} (optional) Explanation of the altered return value * @param retVal {any} Return value passed to code that invoked the wrapped * function. * @deprecated use Y.Do.Halt or Y.Do.Prevent */ DO.Error = DO.Halt; ////////////////////////////////////////////////////////////////////////// // Y["Event"] && Y.Event.addListener(window, "unload", Y.Do._unload, Y.Do); /** * Custom event engine, DOM event listener abstraction layer, synthetic DOM * events. * @module event-custom * @submodule event-custom-base */ // var onsubscribeType = "_event:onsub", var AFTER = 'after', CONFIGS = [ 'broadcast', 'monitored', 'bubbles', 'context', 'contextFn', 'currentTarget', 'defaultFn', 'defaultTargetOnly', 'details', 'emitFacade', 'fireOnce', 'async', 'host', 'preventable', 'preventedFn', 'queuable', 'silent', 'stoppedFn', 'target', 'type' ], YUI3_SIGNATURE = 9, YUI_LOG = 'yui:log'; /** * The CustomEvent class lets you define events for your application * that can be subscribed to by one or more independent component. * * @param {String} type The type of event, which is passed to the callback * when the event fires. * @param {object} o configuration object. * @class CustomEvent * @constructor */ Y.CustomEvent = function(type, o) { // if (arguments.length > 2) { // this.log('CustomEvent context and silent are now in the config', 'warn', 'Event'); // } o = o || {}; this.id = Y.stamp(this); /** * The type of event, returned to subscribers when the event fires * @property type * @type string */ this.type = type; /** * The context the the event will fire from by default. Defaults to the YUI * instance. * @property context * @type object */ this.context = Y; /** * Monitor when an event is attached or detached. * * @property monitored * @type boolean */ // this.monitored = false; this.logSystem = (type == YUI_LOG); /** * If 0, this event does not broadcast. If 1, the YUI instance is notified * every time this event fires. If 2, the YUI instance and the YUI global * (if event is enabled on the global) are notified every time this event * fires. * @property broadcast * @type int */ // this.broadcast = 0; /** * By default all custom events are logged in the debug build, set silent * to true to disable debug outpu for this event. * @property silent * @type boolean */ this.silent = this.logSystem; /** * Specifies whether this event should be queued when the host is actively * processing an event. This will effect exectution order of the callbacks * for the various events. * @property queuable * @type boolean * @default false */ // this.queuable = false; /** * The subscribers to this event * @property subscribers * @type Subscriber {} */ this.subscribers = {}; /** * 'After' subscribers * @property afters * @type Subscriber {} */ this.afters = {}; /** * This event has fired if true * * @property fired * @type boolean * @default false; */ // this.fired = false; /** * An array containing the arguments the custom event * was last fired with. * @property firedWith * @type Array */ // this.firedWith; /** * This event should only fire one time if true, and if * it has fired, any new subscribers should be notified * immediately. * * @property fireOnce * @type boolean * @default false; */ // this.fireOnce = false; /** * fireOnce listeners will fire syncronously unless async * is set to true * @property async * @type boolean * @default false */ //this.async = false; /** * Flag for stopPropagation that is modified during fire() * 1 means to stop propagation to bubble targets. 2 means * to also stop additional subscribers on this target. * @property stopped * @type int */ // this.stopped = 0; /** * Flag for preventDefault that is modified during fire(). * if it is not 0, the default behavior for this event * @property prevented * @type int */ // this.prevented = 0; /** * Specifies the host for this custom event. This is used * to enable event bubbling * @property host * @type EventTarget */ // this.host = null; /** * The default function to execute after event listeners * have fire, but only if the default action was not * prevented. * @property defaultFn * @type Function */ // this.defaultFn = null; /** * The function to execute if a subscriber calls * stopPropagation or stopImmediatePropagation * @property stoppedFn * @type Function */ // this.stoppedFn = null; /** * The function to execute if a subscriber calls * preventDefault * @property preventedFn * @type Function */ // this.preventedFn = null; /** * Specifies whether or not this event's default function * can be cancelled by a subscriber by executing preventDefault() * on the event facade * @property preventable * @type boolean * @default true */ this.preventable = true; /** * Specifies whether or not a subscriber can stop the event propagation * via stopPropagation(), stopImmediatePropagation(), or halt() * * Events can only bubble if emitFacade is true. * * @property bubbles * @type boolean * @default true */ this.bubbles = true; /** * Supports multiple options for listener signatures in order to * port YUI 2 apps. * @property signature * @type int * @default 9 */ this.signature = YUI3_SIGNATURE; this.subCount = 0; this.afterCount = 0; // this.hasSubscribers = false; // this.hasAfters = false; /** * If set to true, the custom event will deliver an EventFacade object * that is similar to a DOM event object. * @property emitFacade * @type boolean * @default false */ // this.emitFacade = false; this.applyConfig(o, true); // this.log("Creating " + this.type); }; Y.CustomEvent.prototype = { constructor: Y.CustomEvent, /** * Returns the number of subscribers for this event as the sum of the on() * subscribers and after() subscribers. * * @method hasSubs * @return Number */ hasSubs: function(when) { var s = this.subCount, a = this.afterCount, sib = this.sibling; if (sib) { s += sib.subCount; a += sib.afterCount; } if (when) { return (when == 'after') ? a : s; } return (s + a); }, /** * Monitor the event state for the subscribed event. The first parameter * is what should be monitored, the rest are the normal parameters when * subscribing to an event. * @method monitor * @param what {string} what to monitor ('detach', 'attach', 'publish'). * @return {EventHandle} return value from the monitor event subscription. */ monitor: function(what) { this.monitored = true; var type = this.id + '|' + this.type + '_' + what, args = Y.Array(arguments, 0, true); args[0] = type; return this.host.on.apply(this.host, args); }, /** * Get all of the subscribers to this event and any sibling event * @method getSubs * @return {Array} first item is the on subscribers, second the after. */ getSubs: function() { var s = Y.merge(this.subscribers), a = Y.merge(this.afters), sib = this.sibling; if (sib) { Y.mix(s, sib.subscribers); Y.mix(a, sib.afters); } return [s, a]; }, /** * Apply configuration properties. Only applies the CONFIG whitelist * @method applyConfig * @param o hash of properties to apply. * @param force {boolean} if true, properties that exist on the event * will be overwritten. */ applyConfig: function(o, force) { if (o) { Y.mix(this, o, force, CONFIGS); } }, /** * Create the Subscription for subscribing function, context, and bound * arguments. If this is a fireOnce event, the subscriber is immediately * notified. * * @method _on * @param fn {Function} Subscription callback * @param [context] {Object} Override `this` in the callback * @param [args] {Array} bound arguments that will be passed to the callback after the arguments generated by fire() * @param [when] {String} "after" to slot into after subscribers * @return {EventHandle} * @protected */ _on: function(fn, context, args, when) { if (!fn) { this.log('Invalid callback for CE: ' + this.type); } var s = new Y.Subscriber(fn, context, args, when); if (this.fireOnce && this.fired) { if (this.async) { setTimeout(Y.bind(this._notify, this, s, this.firedWith), 0); } else { this._notify(s, this.firedWith); } } if (when == AFTER) { this.afters[s.id] = s; this.afterCount++; } else { this.subscribers[s.id] = s; this.subCount++; } return new Y.EventHandle(this, s); }, /** * Listen for this event * @method subscribe * @param {Function} fn The function to execute. * @return {EventHandle} Unsubscribe handle. * @deprecated use on. */ subscribe: function(fn, context) { Y.log('ce.subscribe deprecated, use "on"', 'warn', 'deprecated'); var a = (arguments.length > 2) ? Y.Array(arguments, 2, true) : null; return this._on(fn, context, a, true); }, /** * Listen for this event * @method on * @param {Function} fn The function to execute. * @param {object} context optional execution context. * @param {mixed} arg* 0..n additional arguments to supply to the subscriber * when the event fires. * @return {EventHandle} An object with a detach method to detch the handler(s). */ on: function(fn, context) { var a = (arguments.length > 2) ? Y.Array(arguments, 2, true) : null; if (this.host) { this.host._monitor('attach', this.type, { args: arguments }); } return this._on(fn, context, a, true); }, /** * Listen for this event after the normal subscribers have been notified and * the default behavior has been applied. If a normal subscriber prevents the * default behavior, it also prevents after listeners from firing. * @method after * @param {Function} fn The function to execute. * @param {object} context optional execution context. * @param {mixed} arg* 0..n additional arguments to supply to the subscriber * when the event fires. * @return {EventHandle} handle Unsubscribe handle. */ after: function(fn, context) { var a = (arguments.length > 2) ? Y.Array(arguments, 2, true) : null; return this._on(fn, context, a, AFTER); }, /** * Detach listeners. * @method detach * @param {Function} fn The subscribed function to remove, if not supplied * all will be removed. * @param {Object} context The context object passed to subscribe. * @return {int} returns the number of subscribers unsubscribed. */ detach: function(fn, context) { // unsubscribe handle if (fn && fn.detach) { return fn.detach(); } var i, s, found = 0, subs = Y.merge(this.subscribers, this.afters); for (i in subs) { if (subs.hasOwnProperty(i)) { s = subs[i]; if (s && (!fn || fn === s.fn)) { this._delete(s); found++; } } } return found; }, /** * Detach listeners. * @method unsubscribe * @param {Function} fn The subscribed function to remove, if not supplied * all will be removed. * @param {Object} context The context object passed to subscribe. * @return {int|undefined} returns the number of subscribers unsubscribed. * @deprecated use detach. */ unsubscribe: function() { return this.detach.apply(this, arguments); }, /** * Notify a single subscriber * @method _notify * @param {Subscriber} s the subscriber. * @param {Array} args the arguments array to apply to the listener. * @protected */ _notify: function(s, args, ef) { this.log(this.type + '->' + 'sub: ' + s.id); var ret; ret = s.notify(args, this); if (false === ret || this.stopped > 1) { this.log(this.type + ' cancelled by subscriber'); return false; } return true; }, /** * Logger abstraction to centralize the application of the silent flag * @method log * @param {string} msg message to log. * @param {string} cat log category. */ log: function(msg, cat) { if (!this.silent) { Y.log(this.id + ': ' + msg, cat || 'info', 'event'); } }, /** * Notifies the subscribers. The callback functions will be executed * from the context specified when the event was created, and with the * following parameters: * <ul> * <li>The type of event</li> * <li>All of the arguments fire() was executed with as an array</li> * <li>The custom object (if any) that was passed into the subscribe() * method</li> * </ul> * @method fire * @param {Object*} arguments an arbitrary set of parameters to pass to * the handler. * @return {boolean} false if one of the subscribers returned false, * true otherwise. * */ fire: function() { if (this.fireOnce && this.fired) { this.log('fireOnce event: ' + this.type + ' already fired'); return true; } else { var args = Y.Array(arguments, 0, true); // this doesn't happen if the event isn't published // this.host._monitor('fire', this.type, args); this.fired = true; this.firedWith = args; if (this.emitFacade) { return this.fireComplex(args); } else { return this.fireSimple(args); } } }, /** * Set up for notifying subscribers of non-emitFacade events. * * @method fireSimple * @param args {Array} Arguments passed to fire() * @return Boolean false if a subscriber returned false * @protected */ fireSimple: function(args) { this.stopped = 0; this.prevented = 0; if (this.hasSubs()) { // this._procSubs(Y.merge(this.subscribers, this.afters), args); var subs = this.getSubs(); this._procSubs(subs[0], args); this._procSubs(subs[1], args); } this._broadcast(args); return this.stopped ? false : true; }, // Requires the event-custom-complex module for full funcitonality. fireComplex: function(args) { Y.log('Missing event-custom-complex needed to emit a facade for: ' + this.type); args[0] = args[0] || {}; return this.fireSimple(args); }, /** * Notifies a list of subscribers. * * @method _procSubs * @param subs {Array} List of subscribers * @param args {Array} Arguments passed to fire() * @param ef {} * @return Boolean false if a subscriber returns false or stops the event * propagation via e.stopPropagation(), * e.stopImmediatePropagation(), or e.halt() * @private */ _procSubs: function(subs, args, ef) { var s, i; for (i in subs) { if (subs.hasOwnProperty(i)) { s = subs[i]; if (s && s.fn) { if (false === this._notify(s, args, ef)) { this.stopped = 2; } if (this.stopped == 2) { return false; } } } } return true; }, /** * Notifies the YUI instance if the event is configured with broadcast = 1, * and both the YUI instance and Y.Global if configured with broadcast = 2. * * @method _broadcast * @param args {Array} Arguments sent to fire() * @private */ _broadcast: function(args) { if (!this.stopped && this.broadcast) { var a = Y.Array(args); a.unshift(this.type); if (this.host !== Y) { Y.fire.apply(Y, a); } if (this.broadcast == 2) { Y.Global.fire.apply(Y.Global, a); } } }, /** * Removes all listeners * @method unsubscribeAll * @return {int} The number of listeners unsubscribed. * @deprecated use detachAll. */ unsubscribeAll: function() { return this.detachAll.apply(this, arguments); }, /** * Removes all listeners * @method detachAll * @return {int} The number of listeners unsubscribed. */ detachAll: function() { return this.detach(); }, /** * Deletes the subscriber from the internal store of on() and after() * subscribers. * * @method _delete * @param subscriber object. * @private */ _delete: function(s) { if (s) { if (this.subscribers[s.id]) { delete this.subscribers[s.id]; this.subCount--; } if (this.afters[s.id]) { delete this.afters[s.id]; this.afterCount--; } } if (this.host) { this.host._monitor('detach', this.type, { ce: this, sub: s }); } if (s) { // delete s.fn; // delete s.context; s.deleted = true; } } }; /** * Stores the subscriber information to be used when the event fires. * @param {Function} fn The wrapped function to execute. * @param {Object} context The value of the keyword 'this' in the listener. * @param {Array} args* 0..n additional arguments to supply the listener. * * @class Subscriber * @constructor */ Y.Subscriber = function(fn, context, args) { /** * The callback that will be execute when the event fires * This is wrapped by Y.rbind if obj was supplied. * @property fn * @type Function */ this.fn = fn; /** * Optional 'this' keyword for the listener * @property context * @type Object */ this.context = context; /** * Unique subscriber id * @property id * @type String */ this.id = Y.stamp(this); /** * Additional arguments to propagate to the subscriber * @property args * @type Array */ this.args = args; /** * Custom events for a given fire transaction. * @property events * @type {EventTarget} */ // this.events = null; /** * This listener only reacts to the event once * @property once */ // this.once = false; }; Y.Subscriber.prototype = { constructor: Y.Subscriber, _notify: function(c, args, ce) { if (this.deleted && !this.postponed) { if (this.postponed) { delete this.fn; delete this.context; } else { delete this.postponed; return null; } } var a = this.args, ret; switch (ce.signature) { case 0: ret = this.fn.call(c, ce.type, args, c); break; case 1: ret = this.fn.call(c, args[0] || null, c); break; default: if (a || args) { args = args || []; a = (a) ? args.concat(a) : args; ret = this.fn.apply(c, a); } else { ret = this.fn.call(c); } } if (this.once) { ce._delete(this); } return ret; }, /** * Executes the subscriber. * @method notify * @param args {Array} Arguments array for the subscriber. * @param ce {CustomEvent} The custom event that sent the notification. */ notify: function(args, ce) { var c = this.context, ret = true; if (!c) { c = (ce.contextFn) ? ce.contextFn() : ce.context; } // only catch errors if we will not re-throw them. if (Y.config.throwFail) { ret = this._notify(c, args, ce); } else { try { ret = this._notify(c, args, ce); } catch (e) { Y.error(this + ' failed: ' + e.message, e); } } return ret; }, /** * Returns true if the fn and obj match this objects properties. * Used by the unsubscribe method to match the right subscriber. * * @method contains * @param {Function} fn the function to execute. * @param {Object} context optional 'this' keyword for the listener. * @return {boolean} true if the supplied arguments match this * subscriber's signature. */ contains: function(fn, context) { if (context) { return ((this.fn == fn) && this.context == context); } else { return (this.fn == fn); } } }; /** * Return value from all subscribe operations * @class EventHandle * @constructor * @param {CustomEvent} evt the custom event. * @param {Subscriber} sub the subscriber. */ Y.EventHandle = function(evt, sub) { /** * The custom event * * @property evt * @type CustomEvent */ this.evt = evt; /** * The subscriber object * * @property sub * @type Subscriber */ this.sub = sub; }; Y.EventHandle.prototype = { batch: function(f, c) { f.call(c || this, this); if (Y.Lang.isArray(this.evt)) { Y.Array.each(this.evt, function(h) { h.batch.call(c || h, f); }); } }, /** * Detaches this subscriber * @method detach * @return {int} the number of detached listeners */ detach: function() { var evt = this.evt, detached = 0, i; if (evt) { // Y.log('EventHandle.detach: ' + this.sub, 'info', 'Event'); if (Y.Lang.isArray(evt)) { for (i = 0; i < evt.length; i++) { detached += evt[i].detach(); } } else { evt._delete(this.sub); detached = 1; } } return detached; }, /** * Monitor the event state for the subscribed event. The first parameter * is what should be monitored, the rest are the normal parameters when * subscribing to an event. * @method monitor * @param what {string} what to monitor ('attach', 'detach', 'publish'). * @return {EventHandle} return value from the monitor event subscription. */ monitor: function(what) { return this.evt.monitor.apply(this.evt, arguments); } }; /** * Custom event engine, DOM event listener abstraction layer, synthetic DOM * events. * @module event-custom * @submodule event-custom-base */ /** * EventTarget provides the implementation for any object to * publish, subscribe and fire to custom events, and also * alows other EventTargets to target the object with events * sourced from the other object. * EventTarget is designed to be used with Y.augment to wrap * EventCustom in an interface that allows events to be listened to * and fired by name. This makes it possible for implementing code to * subscribe to an event that either has not been created yet, or will * not be created at all. * @class EventTarget * @param opts a configuration object * @config emitFacade {boolean} if true, all events will emit event * facade payloads by default (default false) * @config prefix {String} the prefix to apply to non-prefixed event names */ var L = Y.Lang, PREFIX_DELIMITER = ':', CATEGORY_DELIMITER = '|', AFTER_PREFIX = '~AFTER~', YArray = Y.Array, _wildType = Y.cached(function(type) { return type.replace(/(.*)(:)(.*)/, "*$2$3"); }), /** * If the instance has a prefix attribute and the * event type is not prefixed, the instance prefix is * applied to the supplied type. * @method _getType * @private */ _getType = Y.cached(function(type, pre) { if (!pre || !L.isString(type) || type.indexOf(PREFIX_DELIMITER) > -1) { return type; } return pre + PREFIX_DELIMITER + type; }), /** * Returns an array with the detach key (if provided), * and the prefixed event name from _getType * Y.on('detachcategory| menu:click', fn) * @method _parseType * @private */ _parseType = Y.cached(function(type, pre) { var t = type, detachcategory, after, i; if (!L.isString(t)) { return t; } i = t.indexOf(AFTER_PREFIX); if (i > -1) { after = true; t = t.substr(AFTER_PREFIX.length); // Y.log(t); } i = t.indexOf(CATEGORY_DELIMITER); if (i > -1) { detachcategory = t.substr(0, (i)); t = t.substr(i+1); if (t == '*') { t = null; } } // detach category, full type with instance prefix, is this an after listener, short type return [detachcategory, (pre) ? _getType(t, pre) : t, after, t]; }), ET = function(opts) { // Y.log('EventTarget constructor executed: ' + this._yuid); var o = (L.isObject(opts)) ? opts : {}; this._yuievt = this._yuievt || { id: Y.guid(), events: {}, targets: {}, config: o, chain: ('chain' in o) ? o.chain : Y.config.chain, bubbling: false, defaults: { context: o.context || this, host: this, emitFacade: o.emitFacade, fireOnce: o.fireOnce, queuable: o.queuable, monitored: o.monitored, broadcast: o.broadcast, defaultTargetOnly: o.defaultTargetOnly, bubbles: ('bubbles' in o) ? o.bubbles : true } }; }; ET.prototype = { constructor: ET, /** * Listen to a custom event hosted by this object one time. * This is the equivalent to <code>on</code> except the * listener is immediatelly detached when it is executed. * @method once * @param {String} type The name of the event * @param {Function} fn The callback to execute in response to the event * @param {Object} [context] Override `this` object in callback * @param {Any} [arg*] 0..n additional arguments to supply to the subscriber * @return {EventHandle} A subscription handle capable of detaching the * subscription */ once: function() { var handle = this.on.apply(this, arguments); handle.batch(function(hand) { if (hand.sub) { hand.sub.once = true; } }); return handle; }, /** * Listen to a custom event hosted by this object one time. * This is the equivalent to <code>after</code> except the * listener is immediatelly detached when it is executed. * @method onceAfter * @param {String} type The name of the event * @param {Function} fn The callback to execute in response to the event * @param {Object} [context] Override `this` object in callback * @param {Any} [arg*] 0..n additional arguments to supply to the subscriber * @return {EventHandle} A subscription handle capable of detaching that * subscription */ onceAfter: function() { var handle = this.after.apply(this, arguments); handle.batch(function(hand) { if (hand.sub) { hand.sub.once = true; } }); return handle; }, /** * Takes the type parameter passed to 'on' and parses out the * various pieces that could be included in the type. If the * event type is passed without a prefix, it will be expanded * to include the prefix one is supplied or the event target * is configured with a default prefix. * @method parseType * @param {String} type the type * @param {String} [pre=this._yuievt.config.prefix] the prefix * @since 3.3.0 * @return {Array} an array containing: * * the detach category, if supplied, * * the prefixed event type, * * whether or not this is an after listener, * * the supplied event type */ parseType: function(type, pre) { return _parseType(type, pre || this._yuievt.config.prefix); }, /** * Subscribe a callback function to a custom event fired by this object or * from an object that bubbles its events to this object. * * Callback functions for events published with `emitFacade = true` will * receive an `EventFacade` as the first argument (typically named "e"). * These callbacks can then call `e.preventDefault()` to disable the * behavior published to that event's `defaultFn`. See the `EventFacade` * API for all available properties and methods. Subscribers to * non-`emitFacade` events will receive the arguments passed to `fire()` * after the event name. * * To subscribe to multiple events at once, pass an object as the first * argument, where the key:value pairs correspond to the eventName:callback, * or pass an array of event names as the first argument to subscribe to * all listed events with the same callback. * * Returning `false` from a callback is supported as an alternative to * calling `e.preventDefault(); e.stopPropagation();`. However, it is * recommended to use the event methods whenever possible. * * @method on * @param {String} type The name of the event * @param {Function} fn The callback to execute in response to the event * @param {Object} [context] Override `this` object in callback * @param {Any} [arg*] 0..n additional arguments to supply to the subscriber * @return {EventHandle} A subscription handle capable of detaching that * subscription */ on: function(type, fn, context) { var parts = _parseType(type, this._yuievt.config.prefix), f, c, args, ret, ce, detachcategory, handle, store = Y.Env.evt.handles, after, adapt, shorttype, Node = Y.Node, n, domevent, isArr; // full name, args, detachcategory, after this._monitor('attach', parts[1], { args: arguments, category: parts[0], after: parts[2] }); if (L.isObject(type)) { if (L.isFunction(type)) { return Y.Do.before.apply(Y.Do, arguments); } f = fn; c = context; args = YArray(arguments, 0, true); ret = []; if (L.isArray(type)) { isArr = true; } after = type._after; delete type._after; Y.each(type, function(v, k) { if (L.isObject(v)) { f = v.fn || ((L.isFunction(v)) ? v : f); c = v.context || c; } var nv = (after) ? AFTER_PREFIX : ''; args[0] = nv + ((isArr) ? v : k); args[1] = f; args[2] = c; ret.push(this.on.apply(this, args)); }, this); return (this._yuievt.chain) ? this : new Y.EventHandle(ret); } detachcategory = parts[0]; after = parts[2]; shorttype = parts[3]; // extra redirection so we catch adaptor events too. take a look at this. if (Node && Y.instanceOf(this, Node) && (shorttype in Node.DOM_EVENTS)) { args = YArray(arguments, 0, true); args.splice(2, 0, Node.getDOMNode(this)); // Y.log("Node detected, redirecting with these args: " + args); return Y.on.apply(Y, args); } type = parts[1]; if (Y.instanceOf(this, YUI)) { adapt = Y.Env.evt.plugins[type]; args = YArray(arguments, 0, true); args[0] = shorttype; if (Node) { n = args[2]; if (Y.instanceOf(n, Y.NodeList)) { n = Y.NodeList.getDOMNodes(n); } else if (Y.instanceOf(n, Node)) { n = Node.getDOMNode(n); } domevent = (shorttype in Node.DOM_EVENTS); // Captures both DOM events and event plugins. if (domevent) { args[2] = n; } } // check for the existance of an event adaptor if (adapt) { Y.log('Using adaptor for ' + shorttype + ', ' + n, 'info', 'event'); handle = adapt.on.apply(Y, args); } else if ((!type) || domevent) { handle = Y.Event._attach(args); } } if (!handle) { ce = this._yuievt.events[type] || this.publish(type); handle = ce._on(fn, context, (arguments.length > 3) ? YArray(arguments, 3, true) : null, (after) ? 'after' : true); } if (detachcategory) { store[detachcategory] = store[detachcategory] || {}; store[detachcategory][type] = store[detachcategory][type] || []; store[detachcategory][type].push(handle); } return (this._yuievt.chain) ? this : handle; }, /** * subscribe to an event * @method subscribe * @deprecated use on */ subscribe: function() { Y.log('EventTarget subscribe() is deprecated, use on()', 'warn', 'deprecated'); return this.on.apply(this, arguments); }, /** * Detach one or more listeners the from the specified event * @method detach * @param type {string|Object} Either the handle to the subscriber or the * type of event. If the type * is not specified, it will attempt to remove * the listener from all hosted events. * @param fn {Function} The subscribed function to unsubscribe, if not * supplied, all subscribers will be removed. * @param context {Object} The custom object passed to subscribe. This is * optional, but if supplied will be used to * disambiguate multiple listeners that are the same * (e.g., you subscribe many object using a function * that lives on the prototype) * @return {EventTarget} the host */ detach: function(type, fn, context) { var evts = this._yuievt.events, i, Node = Y.Node, isNode = Node && (Y.instanceOf(this, Node)); // detachAll disabled on the Y instance. if (!type && (this !== Y)) { for (i in evts) { if (evts.hasOwnProperty(i)) { evts[i].detach(fn, context); } } if (isNode) { Y.Event.purgeElement(Node.getDOMNode(this)); } return this; } var parts = _parseType(type, this._yuievt.config.prefix), detachcategory = L.isArray(parts) ? parts[0] : null, shorttype = (parts) ? parts[3] : null, adapt, store = Y.Env.evt.handles, detachhost, cat, args, ce, keyDetacher = function(lcat, ltype, host) { var handles = lcat[ltype], ce, i; if (handles) { for (i = handles.length - 1; i >= 0; --i) { ce = handles[i].evt; if (ce.host === host || ce.el === host) { handles[i].detach(); } } } }; if (detachcategory) { cat = store[detachcategory]; type = parts[1]; detachhost = (isNode) ? Y.Node.getDOMNode(this) : this; if (cat) { if (type) { keyDetacher(cat, type, detachhost); } else { for (i in cat) { if (cat.hasOwnProperty(i)) { keyDetacher(cat, i, detachhost); } } } return this; } // If this is an event handle, use it to detach } else if (L.isObject(type) && type.detach) { type.detach(); return this; // extra redirection so we catch adaptor events too. take a look at this. } else if (isNode && ((!shorttype) || (shorttype in Node.DOM_EVENTS))) { args = YArray(arguments, 0, true); args[2] = Node.getDOMNode(this); Y.detach.apply(Y, args); return this; } adapt = Y.Env.evt.plugins[shorttype]; // The YUI instance handles DOM events and adaptors if (Y.instanceOf(this, YUI)) { args = YArray(arguments, 0, true); // use the adaptor specific detach code if if (adapt && adapt.detach) { adapt.detach.apply(Y, args); return this; // DOM event fork } else if (!type || (!adapt && Node && (type in Node.DOM_EVENTS))) { args[0] = type; Y.Event.detach.apply(Y.Event, args); return this; } } // ce = evts[type]; ce = evts[parts[1]]; if (ce) { ce.detach(fn, context); } return this; }, /** * detach a listener * @method unsubscribe * @deprecated use detach */ unsubscribe: function() { Y.log('EventTarget unsubscribe() is deprecated, use detach()', 'warn', 'deprecated'); return this.detach.apply(this, arguments); }, /** * Removes all listeners from the specified event. If the event type * is not specified, all listeners from all hosted custom events will * be removed. * @method detachAll * @param type {String} The type, or name of the event */ detachAll: function(type) { return this.detach(type); }, /** * Removes all listeners from the specified event. If the event type * is not specified, all listeners from all hosted custom events will * be removed. * @method unsubscribeAll * @param type {String} The type, or name of the event * @deprecated use detachAll */ unsubscribeAll: function() { Y.log('EventTarget unsubscribeAll() is deprecated, use detachAll()', 'warn', 'deprecated'); return this.detachAll.apply(this, arguments); }, /** * Creates a new custom event of the specified type. If a custom event * by that name already exists, it will not be re-created. In either * case the custom event is returned. * * @method publish * * @param type {String} the type, or name of the event * @param opts {object} optional config params. Valid properties are: * * <ul> * <li> * 'broadcast': whether or not the YUI instance and YUI global are notified when the event is fired (false) * </li> * <li> * 'bubbles': whether or not this event bubbles (true) * Events can only bubble if emitFacade is true. * </li> * <li> * 'context': the default execution context for the listeners (this) * </li> * <li> * 'defaultFn': the default function to execute when this event fires if preventDefault was not called * </li> * <li> * 'emitFacade': whether or not this event emits a facade (false) * </li> * <li> * 'prefix': the prefix for this targets events, e.g., 'menu' in 'menu:click' * </li> * <li> * 'fireOnce': if an event is configured to fire once, new subscribers after * the fire will be notified immediately. * </li> * <li> * 'async': fireOnce event listeners will fire synchronously if the event has already * fired unless async is true. * </li> * <li> * 'preventable': whether or not preventDefault() has an effect (true) * </li> * <li> * 'preventedFn': a function that is executed when preventDefault is called * </li> * <li> * 'queuable': whether or not this event can be queued during bubbling (false) * </li> * <li> * 'silent': if silent is true, debug messages are not provided for this event. * </li> * <li> * 'stoppedFn': a function that is executed when stopPropagation is called * </li> * * <li> * 'monitored': specifies whether or not this event should send notifications about * when the event has been attached, detached, or published. * </li> * <li> * 'type': the event type (valid option if not provided as the first parameter to publish) * </li> * </ul> * * @return {CustomEvent} the custom event * */ publish: function(type, opts) { var events, ce, ret, defaults, edata = this._yuievt, pre = edata.config.prefix; if (L.isObject(type)) { ret = {}; Y.each(type, function(v, k) { ret[k] = this.publish(k, v || opts); }, this); return ret; } type = (pre) ? _getType(type, pre) : type; this._monitor('publish', type, { args: arguments }); events = edata.events; ce = events[type]; if (ce) { // ce.log("publish applying new config to published event: '"+type+"' exists", 'info', 'event'); if (opts) { ce.applyConfig(opts, true); } } else { defaults = edata.defaults; // apply defaults ce = new Y.CustomEvent(type, (opts) ? Y.merge(defaults, opts) : defaults); events[type] = ce; } // make sure we turn the broadcast flag off if this // event was published as a result of bubbling // if (opts instanceof Y.CustomEvent) { // events[type].broadcast = false; // } return events[type]; }, /** * This is the entry point for the event monitoring system. * You can monitor 'attach', 'detach', 'fire', and 'publish'. * When configured, these events generate an event. click -> * click_attach, click_detach, click_publish -- these can * be subscribed to like other events to monitor the event * system. Inividual published events can have monitoring * turned on or off (publish can't be turned off before it * it published) by setting the events 'monitor' config. * * @method _monitor * @param what {String} 'attach', 'detach', 'fire', or 'publish' * @param type {String} Name of the event being monitored * @param o {Object} Information about the event interaction, such as * fire() args, subscription category, publish config * @private */ _monitor: function(what, type, o) { var monitorevt, ce = this.getEvent(type); if ((this._yuievt.config.monitored && (!ce || ce.monitored)) || (ce && ce.monitored)) { monitorevt = type + '_' + what; // Y.log('monitoring: ' + monitorevt); o.monitored = what; this.fire.call(this, monitorevt, o); } }, /** * Fire a custom event by name. The callback functions will be executed * from the context specified when the event was created, and with the * following parameters. * * If the custom event object hasn't been created, then the event hasn't * been published and it has no subscribers. For performance sake, we * immediate exit in this case. This means the event won't bubble, so * if the intention is that a bubble target be notified, the event must * be published on this object first. * * The first argument is the event type, and any additional arguments are * passed to the listeners as parameters. If the first of these is an * object literal, and the event is configured to emit an event facade, * that object is mixed into the event facade and the facade is provided * in place of the original object. * * @method fire * @param type {String|Object} The type of the event, or an object that contains * a 'type' property. * @param arguments {Object*} an arbitrary set of parameters to pass to * the handler. If the first of these is an object literal and the event is * configured to emit an event facade, the event facade will replace that * parameter after the properties the object literal contains are copied to * the event facade. * @return {EventTarget} the event host * */ fire: function(type) { var typeIncluded = L.isString(type), t = (typeIncluded) ? type : (type && type.type), ce, ret, pre = this._yuievt.config.prefix, ce2, args = (typeIncluded) ? YArray(arguments, 1, true) : arguments; t = (pre) ? _getType(t, pre) : t; this._monitor('fire', t, { args: args }); ce = this.getEvent(t, true); ce2 = this.getSibling(t, ce); if (ce2 && !ce) { ce = this.publish(t); } // this event has not been published or subscribed to if (!ce) { if (this._yuievt.hasTargets) { return this.bubble({ type: t }, args, this); } // otherwise there is nothing to be done ret = true; } else { ce.sibling = ce2; ret = ce.fire.apply(ce, args); } return (this._yuievt.chain) ? this : ret; }, getSibling: function(type, ce) { var ce2; // delegate to *:type events if there are subscribers if (type.indexOf(PREFIX_DELIMITER) > -1) { type = _wildType(type); // console.log(type); ce2 = this.getEvent(type, true); if (ce2) { // console.log("GOT ONE: " + type); ce2.applyConfig(ce); ce2.bubbles = false; ce2.broadcast = 0; // ret = ce2.fire.apply(ce2, a); } } return ce2; }, /** * Returns the custom event of the provided type has been created, a * falsy value otherwise * @method getEvent * @param type {String} the type, or name of the event * @param prefixed {String} if true, the type is prefixed already * @return {CustomEvent} the custom event or null */ getEvent: function(type, prefixed) { var pre, e; if (!prefixed) { pre = this._yuievt.config.prefix; type = (pre) ? _getType(type, pre) : type; } e = this._yuievt.events; return e[type] || null; }, /** * Subscribe to a custom event hosted by this object. The * supplied callback will execute after any listeners add * via the subscribe method, and after the default function, * if configured for the event, has executed. * * @method after * @param {String} type The name of the event * @param {Function} fn The callback to execute in response to the event * @param {Object} [context] Override `this` object in callback * @param {Any} [arg*] 0..n additional arguments to supply to the subscriber * @return {EventHandle} A subscription handle capable of detaching the * subscription */ after: function(type, fn) { var a = YArray(arguments, 0, true); switch (L.type(type)) { case 'function': return Y.Do.after.apply(Y.Do, arguments); case 'array': // YArray.each(a[0], function(v) { // v = AFTER_PREFIX + v; // }); // break; case 'object': a[0]._after = true; break; default: a[0] = AFTER_PREFIX + type; } return this.on.apply(this, a); }, /** * Executes the callback before a DOM event, custom event * or method. If the first argument is a function, it * is assumed the target is a method. For DOM and custom * events, this is an alias for Y.on. * * For DOM and custom events: * type, callback, context, 0-n arguments * * For methods: * callback, object (method host), methodName, context, 0-n arguments * * @method before * @return detach handle */ before: function() { return this.on.apply(this, arguments); } }; Y.EventTarget = ET; // make Y an event target Y.mix(Y, ET.prototype); ET.call(Y, { bubbles: false }); YUI.Env.globalEvents = YUI.Env.globalEvents || new ET(); /** * Hosts YUI page level events. This is where events bubble to * when the broadcast config is set to 2. This property is * only available if the custom event module is loaded. * @property Global * @type EventTarget * @for YUI */ Y.Global = YUI.Env.globalEvents; // @TODO implement a global namespace function on Y.Global? /** `Y.on()` can do many things: <ul> <li>Subscribe to custom events `publish`ed and `fire`d from Y</li> <li>Subscribe to custom events `publish`ed with `broadcast` 1 or 2 and `fire`d from any object in the YUI instance sandbox</li> <li>Subscribe to DOM events</li> <li>Subscribe to the execution of a method on any object, effectively treating that method as an event</li> </ul> For custom event subscriptions, pass the custom event name as the first argument and callback as the second. The `this` object in the callback will be `Y` unless an override is passed as the third argument. Y.on('io:complete', function () { Y.MyApp.updateStatus('Transaction complete'); }); To subscribe to DOM events, pass the name of a DOM event as the first argument and a CSS selector string as the third argument after the callback function. Alternately, the third argument can be a `Node`, `NodeList`, `HTMLElement`, array, or simply omitted (the default is the `window` object). Y.on('click', function (e) { e.preventDefault(); // proceed with ajax form submission var url = this.get('action'); ... }, '#my-form'); The `this` object in DOM event callbacks will be the `Node` targeted by the CSS selector or other identifier. `on()` subscribers for DOM events or custom events `publish`ed with a `defaultFn` can prevent the default behavior with `e.preventDefault()` from the event object passed as the first parameter to the subscription callback. To subscribe to the execution of an object method, pass arguments corresponding to the call signature for <a href="../classes/Do.html#methods_before">`Y.Do.before(...)`</a>. NOTE: The formal parameter list below is for events, not for function injection. See `Y.Do.before` for that signature. @method on @param {String} type DOM or custom event name @param {Function} fn The callback to execute in response to the event @param {Object} [context] Override `this` object in callback @param {Any} [arg*] 0..n additional arguments to supply to the subscriber @return {EventHandle} A subscription handle capable of detaching the subscription @see Do.before @for YUI **/ /** Listen for an event one time. Equivalent to `on()`, except that the listener is immediately detached when executed. See the <a href="#methods_on">`on()` method</a> for additional subscription options. @see on @method once @param {String} type DOM or custom event name @param {Function} fn The callback to execute in response to the event @param {Object} [context] Override `this` object in callback @param {Any} [arg*] 0..n additional arguments to supply to the subscriber @return {EventHandle} A subscription handle capable of detaching the subscription @for YUI **/ /** Listen for an event one time. Equivalent to `once()`, except, like `after()`, the subscription callback executes after all `on()` subscribers and the event's `defaultFn` (if configured) have executed. Like `after()` if any `on()` phase subscriber calls `e.preventDefault()`, neither the `defaultFn` nor the `after()` subscribers will execute. The listener is immediately detached when executed. See the <a href="#methods_on">`on()` method</a> for additional subscription options. @see once @method onceAfter @param {String} type The custom event name @param {Function} fn The callback to execute in response to the event @param {Object} [context] Override `this` object in callback @param {Any} [arg*] 0..n additional arguments to supply to the subscriber @return {EventHandle} A subscription handle capable of detaching the subscription @for YUI **/ /** Like `on()`, this method creates a subscription to a custom event or to the execution of a method on an object. For events, `after()` subscribers are executed after the event's `defaultFn` unless `e.preventDefault()` was called from an `on()` subscriber. See the <a href="#methods_on">`on()` method</a> for additional subscription options. NOTE: The subscription signature shown is for events, not for function injection. See <a href="../classes/Do.html#methods_after">`Y.Do.after`</a> for that signature. @see on @see Do.after @method after @param {String} type The custom event name @param {Function} fn The callback to execute in response to the event @param {Object} [context] Override `this` object in callback @param {Any} [args*] 0..n additional arguments to supply to the subscriber @return {EventHandle} A subscription handle capable of detaching the subscription @for YUI **/ }, '@VERSION@' ,{requires:['oop']});
fields/components/Checkbox.js
dvdcastro/keystone
import React from 'react'; import blacklist from 'blacklist'; import classnames from 'classnames'; import { darken, fade } from '../../admin/client/utils/color'; import E from '../../admin/client/constants'; var Checkbox = React.createClass({ displayName: 'Checkbox', propTypes: { checked: React.PropTypes.bool, component: React.PropTypes.node, onChange: React.PropTypes.func, readonly: React.PropTypes.bool, }, getDefaultProps () { return { component: 'button', }; }, getInitialState () { return { active: null, focus: null, hover: null, }; }, componentDidMount () { window.addEventListener('mouseup', this.handleMouseUp, false); }, componentWillUnmount () { window.removeEventListener('mouseup', this.handleMouseUp, false); }, getStyles () { const { checked, readonly } = this.props; const { active, focus, hover } = this.state; const checkedColor = '#3999fc'; let background = (checked && !readonly) ? checkedColor : 'white'; let borderColor = (checked && !readonly) ? 'rgba(0,0,0,0.15) rgba(0,0,0,0.1) rgba(0,0,0,0.05)' : 'rgba(0,0,0,0.3) rgba(0,0,0,0.2) rgba(0,0,0,0.15)'; let boxShadow = (checked && !readonly) ? '0 1px 0 rgba(255,255,255,0.33)' : 'inset 0 1px 0 rgba(0,0,0,0.06)'; let color = (checked && !readonly) ? 'white' : '#bbb'; const textShadow = (checked && !readonly) ? '0 1px 0 rgba(0,0,0,0.2)' : null; // pseudo state if (hover && !focus && !readonly) { borderColor = (checked) ? 'rgba(0,0,0,0.1) rgba(0,0,0,0.15) rgba(0,0,0,0.2)' : 'rgba(0,0,0,0.35) rgba(0,0,0,0.3) rgba(0,0,0,0.25)'; } if (active) { background = (checked && !readonly) ? darken(checkedColor, 20) : '#eee'; borderColor = (checked && !readonly) ? 'rgba(0,0,0,0.25) rgba(0,0,0,0.3) rgba(0,0,0,0.35)' : 'rgba(0,0,0,0.4) rgba(0,0,0,0.35) rgba(0,0,0,0.3)'; boxShadow = (checked && !readonly) ? '0 1px 0 rgba(255,255,255,0.33)' : 'inset 0 1px 3px rgba(0,0,0,0.2)'; } if (focus && !active) { borderColor = (checked && !readonly) ? 'rgba(0,0,0,0.25) rgba(0,0,0,0.3) rgba(0,0,0,0.35)' : checkedColor; boxShadow = (checked && !readonly) ? `0 0 0 3px ${fade(checkedColor, 15)}` : `inset 0 1px 2px rgba(0,0,0,0.15), 0 0 0 3px ${fade(checkedColor, 15)}`; } // noedit if (readonly) { background = 'rgba(255,255,255,0.5)'; borderColor = 'rgba(0,0,0,0.1)'; boxShadow = 'none'; color = checked ? checkedColor : '#bbb'; } return { alignItems: 'center', background: background, border: '1px solid', borderColor: borderColor, borderRadius: E.borderRadius.sm, boxShadow: boxShadow, color: color, display: 'inline-block', fontSize: 14, height: 16, lineHeight: '15px', outline: 'none', padding: 0, textAlign: 'center', textShadow: textShadow, verticalAlign: 'middle', width: 16, msTransition: 'all 120ms ease-out', MozTransition: 'all 120ms ease-out', WebkitTransition: 'all 120ms ease-out', transition: 'all 120ms ease-out', }; }, handleKeyDown (e) { if (e.keyCode !== 32) return; this.toggleActive(true); }, handleKeyUp () { this.toggleActive(false); }, handleMouseOver () { this.toggleHover(true); }, handleMouseDown () { this.toggleActive(true); this.toggleFocus(true); }, handleMouseUp () { this.toggleActive(false); }, handleMouseOut () { this.toggleHover(false); }, toggleActive (pseudo) { this.setState({ active: pseudo }); }, toggleHover (pseudo) { this.setState({ hover: pseudo }); }, toggleFocus (pseudo) { this.setState({ focus: pseudo }); }, handleChange () { this.props.onChange(!this.props.checked); }, render () { const { checked, readonly } = this.props; const props = blacklist(this.props, 'checked', 'component', 'onChange', 'readonly'); props.style = this.getStyles(); props.ref = 'checkbox'; props.className = classnames('octicon', { 'octicon-check': checked, 'octicon-x': (typeof checked === 'boolean') && !checked && readonly, }); props.type = readonly ? null : 'button'; props.onKeyDown = this.handleKeyDown; props.onKeyUp = this.handleKeyUp; props.onMouseDown = this.handleMouseDown; props.onMouseUp = this.handleMouseUp; props.onMouseOver = this.handleMouseOver; props.onMouseOut = this.handleMouseOut; props.onClick = readonly ? null : this.handleChange; props.onFocus = readonly ? null : () => this.toggleFocus(true); props.onBlur = readonly ? null : () => this.toggleFocus(false); const node = readonly ? 'span' : this.props.component; return React.createElement(node, props); }, }); module.exports = Checkbox;
ui/src/pages/404.js
danielbh/danielhollcraft.com-gatsbyjs
import React from 'react' export default ({ data }) => { return ( <section id="one"> <div className="container"> <header className="major" style={{paddingBottom: '45vh'}}> <h2>404 error!</h2> </header> </div> </section> ) }
app/app.js
luandro/luandro.me
/** * app.js * * This is the entry file for the application, only setup and boilerplate * code. */ import 'babel-polyfill'; /* eslint-disable import/no-unresolved */ // Load the manifest.json file and the .htaccess file import '!file?name=[name].[ext]!./manifest.json'; import 'file?name=[name].[ext]!./.htaccess'; /* eslint-enable import/no-unresolved */ // Import all the third party stuff import React from 'react'; import ReactDOM from 'react-dom'; import { Provider } from 'react-redux'; import { applyRouterMiddleware, Router, browserHistory } from 'react-router'; import { syncHistoryWithStore } from 'react-router-redux'; import useScroll from 'react-router-scroll'; import FontFaceObserver from 'fontfaceobserver'; import LanguageProvider from 'containers/LanguageProvider'; import configureStore from './store'; const ubuntuObserver = new FontFaceObserver('Ubuntu', {}); const ebGaramondObserver = new FontFaceObserver('EB Garamond', {}); // When Open Sans is loaded, add a font-family using Open Sans to the body import styles from 'containers/App/styles.css'; ubuntuObserver.load().then(() => { // console.log('font loaded'); document.body.classList.add(styles.fontLoaded); }, () => { document.body.classList.remove(styles.fontLoaded); }); ebGaramondObserver.load().then(() => { // console.log('Garamond font loaded'); }); // Import i18n messages import { translationMessages } from './i18n'; // Import the CSS reset, which HtmlWebpackPlugin transfers to the build folder import 'sanitize.css/sanitize.css'; // Create redux store with history // this uses the singleton browserHistory provided by react-router // Optionally, this could be changed to leverage a created history // e.g. `const browserHistory = useRouterHistory(createBrowserHistory)();` const initialState = {}; const store = configureStore(initialState, browserHistory); // Sync history and store, as the react-router-redux reducer // is under the non-default key ("routing"), selectLocationState // must be provided for resolving how to retrieve the "route" in the state import { selectLocationState } from 'containers/App/selectors'; const history = syncHistoryWithStore(browserHistory, store, { selectLocationState: selectLocationState(), }); // Set up the router, wrapping all Routes in the App component import App from 'containers/App'; import createRoutes from './routes'; const rootRoute = { component: App, childRoutes: createRoutes(store), }; const render = (translatedMessages) => { ReactDOM.render( <Provider store={store}> <LanguageProvider messages={translatedMessages}> <Router history={history} routes={rootRoute} render={ // Scroll to top when going to a new page, imitating default browser // behaviour applyRouterMiddleware(useScroll()) } /> </LanguageProvider> </Provider>, document.getElementById('app') ); }; // Hot reloadable translation json files if (module.hot) { // modules.hot.accept does not accept dynamic dependencies, // have to be constants at compile-time module.hot.accept('./i18n', () => { render(translationMessages); }); } // Chunked polyfill for browsers without Intl support if (!window.Intl) { Promise.all([ System.import('intl'), System.import('intl/locale-data/jsonp/en.js'), ]).then(() => render(translationMessages)); } else { render(translationMessages); } // Install ServiceWorker and AppCache in the end since // it's not most important operation and if main code fails, // we do not want it installed import { install } from 'offline-plugin/runtime'; install();
ui/src/containers/Routes.js
mozilla/splice
import React, { Component } from 'react'; import { Router, Route, Redirect } from 'react-router'; import App from './App' import WebtilesPreviewer from './WebtilesPreviewer'; export default class Routes extends Component { render() { return ( <Router> <Redirect from="/" to="/distributions" /> <Route path="/" component={App}> <Route path="distributions" component={WebtilesPreviewer} /> </Route> </Router> ); } }
ajax/libs/forerunnerdb/1.3.832/fdb-core+persist.js
Amomo/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_('./core'), Persist = _dereq_('../lib/Persist'); if (typeof window !== 'undefined') { window.ForerunnerDB = Core; } module.exports = Core; },{"../lib/Persist":29,"./core":2}],2:[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":8,"../lib/Shim.IE8":35}],3:[function(_dereq_,module,exports){ "use strict"; var Shared = _dereq_('./Shared'), Path = _dereq_('./Path'), sharedPathSolver = new Path(); var BinaryTree = function (data, compareFunc, hashFunc) { this.init.apply(this, arguments); }; BinaryTree.prototype.init = function (data, index, primaryKey, compareFunc, hashFunc) { this._store = []; this._keys = []; if (primaryKey !== undefined) { this.primaryKey(primaryKey); } if (index !== undefined) { this.index(index); } if (compareFunc !== undefined) { this.compareFunc(compareFunc); } if (hashFunc !== undefined) { this.hashFunc(hashFunc); } if (data !== undefined) { this.data(data); } }; Shared.addModule('BinaryTree', BinaryTree); Shared.mixin(BinaryTree.prototype, 'Mixin.ChainReactor'); Shared.mixin(BinaryTree.prototype, 'Mixin.Sorting'); Shared.mixin(BinaryTree.prototype, 'Mixin.Common'); Shared.synthesize(BinaryTree.prototype, 'compareFunc'); Shared.synthesize(BinaryTree.prototype, 'hashFunc'); Shared.synthesize(BinaryTree.prototype, 'indexDir'); Shared.synthesize(BinaryTree.prototype, 'primaryKey'); Shared.synthesize(BinaryTree.prototype, 'keys'); Shared.synthesize(BinaryTree.prototype, 'index', function (index) { if (index !== undefined) { if (this.debug()) { console.log('Setting index', index, sharedPathSolver.parse(index, true)); } // Convert the index object to an array of key val objects this.keys(sharedPathSolver.parse(index, true)); } return this.$super.call(this, index); }); /** * Remove all data from the binary tree. */ BinaryTree.prototype.clear = function () { delete this._data; delete this._left; delete this._right; this._store = []; }; /** * Sets this node's data object. All further inserted documents that * match this node's key and value will be pushed via the push() * method into the this._store array. When deciding if a new data * should be created left, right or middle (pushed) of this node the * new data is checked against the data set via this method. * @param val * @returns {*} */ BinaryTree.prototype.data = function (val) { if (val !== undefined) { this._data = val; if (this._hashFunc) { this._hash = this._hashFunc(val); } return this; } return this._data; }; /** * Pushes an item to the binary tree node's store array. * @param {*} val The item to add to the store. * @returns {*} */ BinaryTree.prototype.push = function (val) { if (val !== undefined) { this._store.push(val); return this; } return false; }; /** * Pulls an item from the binary tree node's store array. * @param {*} val The item to remove from the store. * @returns {*} */ BinaryTree.prototype.pull = function (val) { if (val !== undefined) { var index = this._store.indexOf(val); if (index > -1) { this._store.splice(index, 1); return this; } } return false; }; /** * Default compare method. Can be overridden. * @param a * @param b * @returns {number} * @private */ BinaryTree.prototype._compareFunc = function (a, b) { // Loop the index array var i, indexData, result = 0; for (i = 0; i < this._keys.length; i++) { indexData = this._keys[i]; if (indexData.value === 1) { result = this.sortAsc(sharedPathSolver.get(a, indexData.path), sharedPathSolver.get(b, indexData.path)); } else if (indexData.value === -1) { result = this.sortDesc(sharedPathSolver.get(a, indexData.path), sharedPathSolver.get(b, indexData.path)); } if (this.debug()) { console.log('Compared %s with %s order %d in path %s and result was %d', sharedPathSolver.get(a, indexData.path), sharedPathSolver.get(b, indexData.path), indexData.value, indexData.path, result); } if (result !== 0) { if (this.debug()) { console.log('Retuning result %d', result); } return result; } } if (this.debug()) { console.log('Retuning result %d', result); } return result; }; /** * Default hash function. Can be overridden. * @param obj * @private */ BinaryTree.prototype._hashFunc = function (obj) { /*var i, indexData, hash = ''; for (i = 0; i < this._keys.length; i++) { indexData = this._keys[i]; if (hash) { hash += '_'; } hash += obj[indexData.path]; } return hash;*/ return obj[this._keys[0].path]; }; /** * Removes (deletes reference to) either left or right child if the passed * node matches one of them. * @param {BinaryTree} node The node to remove. */ BinaryTree.prototype.removeChildNode = function (node) { if (this._left === node) { // Remove left delete this._left; } else if (this._right === node) { // Remove right delete this._right; } }; /** * Returns the branch this node matches (left or right). * @param node * @returns {String} */ BinaryTree.prototype.nodeBranch = function (node) { if (this._left === node) { return 'left'; } else if (this._right === node) { return 'right'; } }; /** * Inserts a document into the binary tree. * @param data * @returns {*} */ BinaryTree.prototype.insert = function (data) { var result, inserted, failed, i; if (data instanceof Array) { // Insert array of data inserted = []; failed = []; for (i = 0; i < data.length; i++) { if (this.insert(data[i])) { inserted.push(data[i]); } else { failed.push(data[i]); } } return { inserted: inserted, failed: failed }; } if (this.debug()) { console.log('Inserting', data); } if (!this._data) { if (this.debug()) { console.log('Node has no data, setting data', data); } // Insert into this node (overwrite) as there is no data this.data(data); //this.push(data); return true; } result = this._compareFunc(this._data, data); if (result === 0) { if (this.debug()) { console.log('Data is equal (currrent, new)', this._data, data); } //this.push(data); // Less than this node if (this._left) { // Propagate down the left branch this._left.insert(data); } else { // Assign to left branch this._left = new BinaryTree(data, this._index, this._binaryTree, this._compareFunc, this._hashFunc); this._left._parent = this; } return true; } if (result === -1) { if (this.debug()) { console.log('Data is greater (currrent, new)', this._data, data); } // Greater than this node if (this._right) { // Propagate down the right branch this._right.insert(data); } else { // Assign to right branch this._right = new BinaryTree(data, this._index, this._binaryTree, this._compareFunc, this._hashFunc); this._right._parent = this; } return true; } if (result === 1) { if (this.debug()) { console.log('Data is less (currrent, new)', this._data, data); } // Less than this node if (this._left) { // Propagate down the left branch this._left.insert(data); } else { // Assign to left branch this._left = new BinaryTree(data, this._index, this._binaryTree, this._compareFunc, this._hashFunc); this._left._parent = this; } return true; } return false; }; BinaryTree.prototype.remove = function (data) { var pk = this.primaryKey(), result, removed, i; if (data instanceof Array) { // Insert array of data removed = []; for (i = 0; i < data.length; i++) { if (this.remove(data[i])) { removed.push(data[i]); } } return removed; } if (this.debug()) { console.log('Removing', data); } if (this._data[pk] === data[pk]) { // Remove this node return this._remove(this); } // Compare the data to work out which branch to send the remove command down result = this._compareFunc(this._data, data); if (result === -1 && this._right) { return this._right.remove(data); } if (result === 1 && this._left) { return this._left.remove(data); } return false; }; BinaryTree.prototype._remove = function (node) { var leftNode, rightNode; if (this._left) { // Backup branch data leftNode = this._left; rightNode = this._right; // Copy data from left node this._left = leftNode._left; this._right = leftNode._right; this._data = leftNode._data; this._store = leftNode._store; if (rightNode) { // Attach the rightNode data to the right-most node // of the leftNode leftNode.rightMost()._right = rightNode; } } else if (this._right) { // Backup branch data rightNode = this._right; // Copy data from right node this._left = rightNode._left; this._right = rightNode._right; this._data = rightNode._data; this._store = rightNode._store; } else { this.clear(); } return true; }; BinaryTree.prototype.leftMost = function () { if (!this._left) { return this; } else { return this._left.leftMost(); } }; BinaryTree.prototype.rightMost = function () { if (!this._right) { return this; } else { return this._right.rightMost(); } }; /** * Searches the binary tree for all matching documents based on the data * passed (query). * @param {Object} data The data / document to use for lookups. * @param {Object} options An options object. * @param {Operation} op An optional operation instance. Pass undefined * if not being used. * @param {Array=} resultArr The results passed between recursive calls. * Do not pass anything into this argument when calling externally. * @returns {*|Array} */ BinaryTree.prototype.lookup = function (data, options, op, resultArr) { var result = this._compareFunc(this._data, data); resultArr = resultArr || []; if (result === 0) { if (this._left) { this._left.lookup(data, options, op, resultArr); } resultArr.push(this._data); if (this._right) { this._right.lookup(data, options, op, resultArr); } } if (result === -1) { if (this._right) { this._right.lookup(data, options, op, resultArr); } } if (result === 1) { if (this._left) { this._left.lookup(data, options, op, resultArr); } } return resultArr; }; /** * Returns the entire binary tree ordered. * @param {String} type * @param resultArr * @returns {*|Array} */ BinaryTree.prototype.inOrder = function (type, resultArr) { resultArr = resultArr || []; if (this._left) { this._left.inOrder(type, resultArr); } switch (type) { case 'hash': resultArr.push(this._hash); break; case 'data': resultArr.push(this._data); break; default: resultArr.push({ key: this._data, arr: this._store }); break; } if (this._right) { this._right.inOrder(type, resultArr); } return resultArr; }; /** * Searches the binary tree for all matching documents based on the regular * expression passed. * @param path * @param val * @param regex * @param {Array=} resultArr The results passed between recursive calls. * Do not pass anything into this argument when calling externally. * @returns {*|Array} */ BinaryTree.prototype.startsWith = function (path, val, regex, resultArr) { var reTest, thisDataPathVal = sharedPathSolver.get(this._data, path), thisDataPathValSubStr = thisDataPathVal.substr(0, val.length), result; //regex = regex || new RegExp('^' + val); resultArr = resultArr || []; if (resultArr._visitedCount === undefined) { resultArr._visitedCount = 0; } resultArr._visitedCount++; resultArr._visitedNodes = resultArr._visitedNodes || []; resultArr._visitedNodes.push(thisDataPathVal); result = this.sortAsc(thisDataPathValSubStr, val); reTest = thisDataPathValSubStr === val; if (result === 0) { if (this._left) { this._left.startsWith(path, val, regex, resultArr); } if (reTest) { resultArr.push(this._data); } if (this._right) { this._right.startsWith(path, val, regex, resultArr); } } if (result === -1) { if (reTest) { resultArr.push(this._data); } if (this._right) { this._right.startsWith(path, val, regex, resultArr); } } if (result === 1) { if (this._left) { this._left.startsWith(path, val, regex, resultArr); } if (reTest) { resultArr.push(this._data); } } return resultArr; }; /*BinaryTree.prototype.find = function (type, search, resultArr) { resultArr = resultArr || []; if (this._left) { this._left.find(type, search, resultArr); } // Check if this node's data is greater or less than the from value var fromResult = this.sortAsc(this._data[key], from), toResult = this.sortAsc(this._data[key], to); if ((fromResult === 0 || fromResult === 1) && (toResult === 0 || toResult === -1)) { // This data node is greater than or equal to the from value, // and less than or equal to the to value so include it switch (type) { case 'hash': resultArr.push(this._hash); break; case 'data': resultArr.push(this._data); break; default: resultArr.push({ key: this._data, arr: this._store }); break; } } if (this._right) { this._right.find(type, search, resultArr); } return resultArr; };*/ /** * * @param {String} type * @param {String} key The data key / path to range search against. * @param {Number} from Range search from this value (inclusive) * @param {Number} to Range search to this value (inclusive) * @param {Array=} resultArr Leave undefined when calling (internal use), * passes the result array between recursive calls to be returned when * the recursion chain completes. * @param {Path=} pathResolver Leave undefined when calling (internal use), * caches the path resolver instance for performance. * @returns {Array} Array of matching document objects */ BinaryTree.prototype.findRange = function (type, key, from, to, resultArr, pathResolver) { resultArr = resultArr || []; pathResolver = pathResolver || new Path(key); if (this._left) { this._left.findRange(type, key, from, to, resultArr, pathResolver); } // Check if this node's data is greater or less than the from value var pathVal = pathResolver.value(this._data), fromResult = this.sortAsc(pathVal, from), toResult = this.sortAsc(pathVal, to); if ((fromResult === 0 || fromResult === 1) && (toResult === 0 || toResult === -1)) { // This data node is greater than or equal to the from value, // and less than or equal to the to value so include it switch (type) { case 'hash': resultArr.push(this._hash); break; case 'data': resultArr.push(this._data); break; default: resultArr.push({ key: this._data, arr: this._store }); break; } } if (this._right) { this._right.findRange(type, key, from, to, resultArr, pathResolver); } return resultArr; }; /*BinaryTree.prototype.findRegExp = function (type, key, pattern, resultArr) { resultArr = resultArr || []; if (this._left) { this._left.findRegExp(type, key, pattern, resultArr); } // Check if this node's data is greater or less than the from value var fromResult = this.sortAsc(this._data[key], from), toResult = this.sortAsc(this._data[key], to); if ((fromResult === 0 || fromResult === 1) && (toResult === 0 || toResult === -1)) { // This data node is greater than or equal to the from value, // and less than or equal to the to value so include it switch (type) { case 'hash': resultArr.push(this._hash); break; case 'data': resultArr.push(this._data); break; default: resultArr.push({ key: this._data, arr: this._store }); break; } } if (this._right) { this._right.findRegExp(type, key, pattern, resultArr); } return resultArr; };*/ /** * Determines if the passed query and options object will be served * by this index successfully or not and gives a score so that the * DB search system can determine how useful this index is in comparison * to other indexes on the same collection. * @param query * @param queryOptions * @param matchOptions * @returns {{matchedKeys: Array, totalKeyCount: Number, score: number}} */ BinaryTree.prototype.match = function (query, queryOptions, matchOptions) { // Check if the passed query has data in the keys our index // operates on and if so, is the query sort matching our order var indexKeyArr, queryArr, matchedKeys = [], matchedKeyCount = 0, i; indexKeyArr = sharedPathSolver.parseArr(this._index, { verbose: true }); queryArr = sharedPathSolver.parseArr(query, matchOptions && matchOptions.pathOptions ? matchOptions.pathOptions : { ignore:/\$/, verbose: true }); // Loop the query array and check the order of keys against the // index key array to see if this index can be used for (i = 0; i < indexKeyArr.length; i++) { if (queryArr[i] === indexKeyArr[i]) { matchedKeyCount++; matchedKeys.push(queryArr[i]); } } return { matchedKeys: matchedKeys, totalKeyCount: queryArr.length, score: matchedKeyCount }; //return sharedPathSolver.countObjectPaths(this._keys, query); }; Shared.finishModule('BinaryTree'); module.exports = BinaryTree; },{"./Path":28,"./Shared":34}],4:[function(_dereq_,module,exports){ "use strict"; var crcTable, checksum; crcTable = (function () { var crcTable = [], c, n, k; for (n = 0; n < 256; n++) { c = n; for (k = 0; k < 8; k++) { c = ((c & 1) ? (0xEDB88320 ^ (c >>> 1)) : (c >>> 1)); // jshint ignore:line } crcTable[n] = c; } return crcTable; }()); /** * Returns a checksum of a string. * @param {String} str The string to checksum. * @return {Number} The checksum generated. */ checksum = function(str) { var crc = 0 ^ (-1), // jshint ignore:line i; for (i = 0; i < str.length; i++) { crc = (crc >>> 8) ^ crcTable[(crc ^ str.charCodeAt(i)) & 0xFF]; // jshint ignore:line } return (crc ^ (-1)) >>> 0; // jshint ignore:line }; module.exports = checksum; },{}],5:[function(_dereq_,module,exports){ "use strict"; var Shared, Db, Metrics, KeyValueStore, Path, IndexHashMap, IndexBinaryTree, Index2d, Overload, ReactorIO, Condition, sharedPathSolver; Shared = _dereq_('./Shared'); /** * Creates a new collection. Collections store multiple documents and * handle CRUD against those documents. * @constructor */ var Collection = function (name, options) { this.init.apply(this, arguments); }; Collection.prototype.init = function (name, options) { this.sharedPathSolver = sharedPathSolver; this._primaryKey = '_id'; this._primaryIndex = new KeyValueStore('primary'); this._primaryCrc = new KeyValueStore('primaryCrc'); this._crcLookup = new KeyValueStore('crcLookup'); this._name = name; this._data = []; this._metrics = new Metrics(); this._options = options || { changeTimestamp: false }; if (this._options.db) { this.db(this._options.db); } // Create an object to store internal protected data this._metaData = {}; this._deferQueue = { insert: [], update: [], remove: [], upsert: [], async: [] }; this._deferThreshold = { insert: 100, update: 100, remove: 100, upsert: 100 }; this._deferTime = { insert: 1, update: 1, remove: 1, upsert: 1 }; this._deferredCalls = true; // Set the subset to itself since it is the root collection this.subsetOf(this); }; Shared.addModule('Collection', Collection); Shared.mixin(Collection.prototype, 'Mixin.Common'); Shared.mixin(Collection.prototype, 'Mixin.Events'); Shared.mixin(Collection.prototype, 'Mixin.ChainReactor'); Shared.mixin(Collection.prototype, 'Mixin.CRUD'); Shared.mixin(Collection.prototype, 'Mixin.Constants'); Shared.mixin(Collection.prototype, 'Mixin.Triggers'); Shared.mixin(Collection.prototype, 'Mixin.Sorting'); Shared.mixin(Collection.prototype, 'Mixin.Matching'); Shared.mixin(Collection.prototype, 'Mixin.Updating'); Shared.mixin(Collection.prototype, 'Mixin.Tags'); Metrics = _dereq_('./Metrics'); KeyValueStore = _dereq_('./KeyValueStore'); Path = _dereq_('./Path'); IndexHashMap = _dereq_('./IndexHashMap'); IndexBinaryTree = _dereq_('./IndexBinaryTree'); Index2d = _dereq_('./Index2d'); Db = Shared.modules.Db; Overload = _dereq_('./Overload'); ReactorIO = _dereq_('./ReactorIO'); Condition = _dereq_('./Condition'); sharedPathSolver = new Path(); /** * Gets / sets the deferred calls flag. If set to true (default) * then operations on large data sets can be broken up and done * over multiple CPU cycles (creating an async state). For purely * synchronous behaviour set this to false. * @param {Boolean=} val The value to set. * @returns {Boolean} */ Shared.synthesize(Collection.prototype, 'deferredCalls'); /** * Gets / sets the current state. * @param {String=} val The name of the state to set. * @returns {*} */ Shared.synthesize(Collection.prototype, 'state'); /** * Gets / sets the name of the collection. * @param {String=} val The name of the collection to set. * @returns {*} */ Shared.synthesize(Collection.prototype, 'name'); /** * Gets / sets the metadata stored in the collection. * @param {Object=} val The data to set. * @returns {*} */ Shared.synthesize(Collection.prototype, 'metaData'); /** * Gets / sets boolean to determine if the collection should be * capped or not. * @param {Boolean=} val The value to set. * @returns {*} */ Shared.synthesize(Collection.prototype, 'capped'); /** * Gets / sets capped collection size. This is the maximum number * of records that the capped collection will store. * @param {Number=} val The value to set. * @returns {*} */ Shared.synthesize(Collection.prototype, 'cappedSize'); /** * Adds a job id to the async queue to signal to other parts * of the application that some async work is currently being * done. * @param {String} key The id of the async job. * @private */ Collection.prototype._asyncPending = function (key) { this._deferQueue.async.push(key); }; /** * Removes a job id from the async queue to signal to other * parts of the application that some async work has been * completed. If no further async jobs exist on the queue then * the "ready" event is emitted from this collection instance. * @param {String} key The id of the async job. * @private */ Collection.prototype._asyncComplete = function (key) { // Remove async flag for this type var index = this._deferQueue.async.indexOf(key); while (index > -1) { this._deferQueue.async.splice(index, 1); index = this._deferQueue.async.indexOf(key); } if (this._deferQueue.async.length === 0) { this.deferEmit('ready'); } }; /** * Get the data array that represents the collection's data. * This data is returned by reference and should not be altered outside * of the provided CRUD functionality of the collection as doing so * may cause unstable index behaviour within the collection. * @returns {Array} */ Collection.prototype.data = function () { return this._data; }; /** * Drops a collection and all it's stored data from the database. * @param {Function=} callback A callback method to call once the * operation has completed. * @returns {boolean} True on success, false on failure. */ Collection.prototype.drop = function (callback) { var key; if (!this.isDropped()) { if (this._db && this._db._collection && this._name) { if (this.debug()) { console.log(this.logIdentifier() + ' Dropping'); } this._state = 'dropped'; this.emit('drop', this); delete this._db._collection[this._name]; // Remove any reactor IO chain links if (this._collate) { for (key in this._collate) { if (this._collate.hasOwnProperty(key)) { this.collateRemove(key); } } } delete this._primaryKey; delete this._primaryIndex; delete this._primaryCrc; delete this._crcLookup; delete this._data; delete this._metrics; delete this._listeners; if (callback) { callback.call(this, false, true); } return true; } } else { if (callback) { callback.call(this, false, true); } return true; } if (callback) { callback.call(this, false, true); } return false; }; /** * Gets / sets the primary key for this collection. * @param {String=} keyName The name of the primary key. * @returns {*} */ Collection.prototype.primaryKey = function (keyName) { if (keyName !== undefined) { if (this._primaryKey !== keyName) { var oldKey = this._primaryKey; this._primaryKey = keyName; // Set the primary key index primary key this._primaryIndex.primaryKey(keyName); // Rebuild the primary key index this.rebuildPrimaryKeyIndex(); // Propagate change down the chain this.chainSend('primaryKey', { keyName: keyName, oldData: oldKey }); } return this; } return this._primaryKey; }; /** * Handles insert events and routes changes to binds and views as required. * @param {Array} inserted An array of inserted documents. * @param {Array} failed An array of documents that failed to insert. * @private */ Collection.prototype._onInsert = function (inserted, failed) { this.emit('insert', inserted, failed); }; /** * Handles update events and routes changes to binds and views as required. * @param {Array} items An array of updated documents. * @private */ Collection.prototype._onUpdate = function (items) { this.emit('update', items); }; /** * Handles remove events and routes changes to binds and views as required. * @param {Array} items An array of removed documents. * @private */ Collection.prototype._onRemove = function (items) { this.emit('remove', items); }; /** * Handles any change to the collection by updating the * lastChange timestamp on the collection's metaData. This * only happens if the changeTimestamp option is enabled * on the collection (it is disabled by default). * @private */ Collection.prototype._onChange = function () { if (this._options.changeTimestamp) { // Record the last change timestamp this._metaData.lastChange = this.serialiser.convert(new Date()); } }; /** * Gets / sets the db instance this class instance belongs to. * @param {Db=} db The db instance. * @returns {*} */ Shared.synthesize(Collection.prototype, 'db', function (db) { if (db) { if (this.primaryKey() === '_id') { // Set primary key to the db's key by default this.primaryKey(db.primaryKey()); // Apply the same debug settings this.debug(db.debug()); } } return this.$super.apply(this, arguments); }); /** * Gets / sets mongodb emulation mode. * @param {Boolean=} val True to enable, false to disable. * @returns {*} */ Shared.synthesize(Collection.prototype, 'mongoEmulation'); Collection.prototype.setData = new Overload('Collection.prototype.setData', { /** * Sets the collection's data to the array / documents passed. If any * data already exists in the collection it will be removed before the * new data is set via the remove() method, and the remove event will * fire as well. * @name setData * @param {Array|Object} data The array of documents or a single document * that will be set as the collections data. */ '*': function (data) { return this.$main.call(this, data, {}); }, /** * Sets the collection's data to the array / documents passed. If any * data already exists in the collection it will be removed before the * new data is set via the remove() method, and the remove event will * fire as well. * @name setData * @param {Array|Object} data The array of documents or a single document * that will be set as the collections data. * @param {Object} options Optional options object. */ '*, object': function (data, options) { return this.$main.call(this, data, options); }, /** * Sets the collection's data to the array / documents passed. If any * data already exists in the collection it will be removed before the * new data is set via the remove() method, and the remove event will * fire as well. * @name setData * @param {Array|Object} data The array of documents or a single document * that will be set as the collections data. * @param {Function} callback Optional callback function. */ '*, function': function (data, callback) { return this.$main.call(this, data, {}, callback); }, /** * Sets the collection's data to the array / documents passed. If any * data already exists in the collection it will be removed before the * new data is set via the remove() method, and the remove event will * fire as well. * @name setData * @param {Array|Object} data The array of documents or a single document * that will be set as the collections data. * @param {*} options Optional options object. * @param {Function} callback Optional callback function. */ '*, *, function': function (data, options, callback) { return this.$main.call(this, data, options, callback); }, /** * Sets the collection's data to the array / documents passed. If any * data already exists in the collection it will be removed before the * new data is set via the remove() method, and the remove event will * fire as well. * @name setData * @param {Array|Object} data The array of documents or a single document * that will be set as the collections data. * @param {*} options Optional options object. * @param {*} callback Optional callback function. */ '*, *, *': function (data, options, callback) { return this.$main.call(this, data, options, callback); }, /** * Sets the collection's data to the array / documents passed. If any * data already exists in the collection it will be removed before the * new data is set via the remove() method, and the remove event will * fire as well. * @name setData * @param {Array|Object} data The array of documents or a single document * that will be set as the collections data. * @param {Object} options Optional options object. * @param {Function} callback Optional callback function. */ '$main': function (data, options, callback) { if (this.isDropped()) { throw(this.logIdentifier() + ' Cannot operate in a dropped state!'); } if (data) { var deferredSetting = this.deferredCalls(), oldData = [].concat(this._data); // Switch off deferred calls since setData should be // a synchronous call this.deferredCalls(false); options = this.options(options); if (options.$decouple) { data = this.decouple(data); } if (!(data instanceof Array)) { data = [data]; } // Remove all items from the collection this.remove({}); // Insert the new data this.insert(data); // Switch deferred calls back to previous settings this.deferredCalls(deferredSetting); this._onChange(); this.emit('setData', this._data, oldData); } if (callback) { callback.call(this); } return this; } }); /** * Drops and rebuilds the primary key index for all documents * in the collection. * @param {Object=} options An optional options object. * @private */ Collection.prototype.rebuildPrimaryKeyIndex = function (options) { options = options || { $ensureKeys: undefined, $violationCheck: undefined }; var ensureKeys = options && options.$ensureKeys !== undefined ? options.$ensureKeys : true, violationCheck = options && options.$violationCheck !== undefined ? options.$violationCheck : true, arr, arrCount, arrItem, pIndex = this._primaryIndex, crcIndex = this._primaryCrc, crcLookup = this._crcLookup, pKey = this._primaryKey, jString; // Drop the existing primary index pIndex.truncate(); crcIndex.truncate(); crcLookup.truncate(); // Loop the data and check for a primary key in each object arr = this._data; arrCount = arr.length; while (arrCount--) { arrItem = arr[arrCount]; if (ensureKeys) { // Make sure the item has a primary key this.ensurePrimaryKey(arrItem); } if (violationCheck) { // Check for primary key violation if (!pIndex.uniqueSet(arrItem[pKey], arrItem)) { // Primary key violation throw(this.logIdentifier() + ' Call to setData on collection failed because your data violates the primary key unique constraint. One or more documents are using the same primary key: ' + arrItem[this._primaryKey]); } } else { pIndex.set(arrItem[pKey], arrItem); } // Generate a hash string jString = this.hash(arrItem); crcIndex.set(arrItem[pKey], jString); crcLookup.set(jString, arrItem); } }; /** * Checks for a primary key on the document and assigns one if none * currently exists. * @param {Object} obj The object to check a primary key against. * @private */ Collection.prototype.ensurePrimaryKey = function (obj) { if (obj[this._primaryKey] === undefined) { // Assign a primary key automatically obj[this._primaryKey] = this.objectId(); } }; /** * Clears all data from the collection. * @returns {Collection} */ Collection.prototype.truncate = function () { if (this.isDropped()) { throw(this.logIdentifier() + ' Cannot operate in a dropped state!'); } // TODO: This should use remove so that chain reactor events are properly // TODO: handled, but ensure that chunking is switched off this.emit('truncate', this._data); // Clear all the data from the collection this._data.length = 0; // Re-create the primary index data this._primaryIndex = new KeyValueStore('primary'); this._primaryCrc = new KeyValueStore('primaryCrc'); this._crcLookup = new KeyValueStore('crcLookup'); this._onChange(); this.emit('immediateChange', {type: 'truncate'}); this.deferEmit('change', {type: 'truncate'}); return this; }; /** * Inserts a new document or updates an existing document in a * collection depending on if a matching primary key exists in * the collection already or not. * * 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 * document and the document is inserted. * * @param {Object} obj The document object to upsert or an array * containing documents to upsert. * @param {Function=} callback Optional callback method. * @returns {Object} An object containing two keys, "op" contains * either "insert" or "update" depending on the type of operation * that was performed and "result" contains the return data from * the operation used. */ Collection.prototype.upsert = function (obj, callback) { if (this.isDropped()) { throw(this.logIdentifier() + ' Cannot operate in a dropped state!'); } if (obj) { var queue = this._deferQueue.upsert, deferThreshold = this._deferThreshold.upsert, returnData = {}, query, i; // Determine if the object passed is an array or not if (obj instanceof Array) { if (this._deferredCalls && obj.length > deferThreshold) { // Break up upsert into blocks this._deferQueue.upsert = queue.concat(obj); this._asyncPending('upsert'); // Fire off the insert queue handler this.processQueue('upsert', callback); return {}; } else { // Loop the array and upsert each item returnData = []; for (i = 0; i < obj.length; i++) { returnData.push(this.upsert(obj[i])); } if (callback) { callback.call(this); } return returnData; } } // Determine if the operation is an insert or an update if (obj[this._primaryKey]) { // Check if an object with this primary key already exists query = {}; query[this._primaryKey] = obj[this._primaryKey]; if (this._primaryIndex.lookup(query)[0]) { // The document already exists with this id, this operation is an update returnData.op = 'update'; } else { // No document with this id exists, this operation is an insert returnData.op = 'insert'; } } else { // The document passed does not contain an id, this operation is an insert returnData.op = 'insert'; } switch (returnData.op) { case 'insert': returnData.result = this.insert(obj, callback); break; case 'update': returnData.result = this.update(query, obj, {}, callback); break; default: break; } return returnData; } else { if (callback) { callback.call(this); } } return {}; }; /** * Executes a method against each document that matches query and returns an * array of documents that may have been modified by the method. * @param {Object} query The query object. * @param {Function} func The method that each document is passed to. If this method * returns false for a particular document it is excluded from the results. * @param {Object=} options Optional options object. * @returns {Array} */ Collection.prototype.filter = function (query, func, options) { return (this.find(query, options)).filter(func); }; /** * Executes a method against each document that matches query and then executes * an update based on the return data of the method. * @param {Object} query The query object. * @param {Function} func The method that each document is passed to. If this method * returns false for a particular document it is excluded from the update. * @param {Object=} options Optional options object passed to the initial find call. * @returns {Array} */ Collection.prototype.filterUpdate = function (query, func, options) { var items = this.find(query, options), results = [], singleItem, singleQuery, singleUpdate, pk = this.primaryKey(), i; for (i = 0; i < items.length; i++) { singleItem = items[i]; singleUpdate = func(singleItem); if (singleUpdate) { singleQuery = {}; singleQuery[pk] = singleItem[pk]; results.push(this.update(singleQuery, singleUpdate)); } } return results; }; /** * Modifies an existing document or documents in a collection. * This will update all matches for 'query' with the data held * in 'update'. It will not overwrite the matched documents * with the update document. * * @param {Object} query The query that must be matched for a * document to be operated on. * @param {Object} update The object containing updated * key/values. Any keys that match keys on the existing document * will be overwritten with this data. Any keys that do not * currently exist on the document will be added to the document. * @param {Object=} options An options object. * @param {Function=} callback The callback method to call when * the update is complete. * @returns {Array} The items that were updated. */ Collection.prototype.update = function (query, update, options, callback) { if (this.isDropped()) { throw(this.logIdentifier() + ' Cannot operate in a dropped state!'); } // Convert queries from mongo dot notation to forerunner queries if (this.mongoEmulation()) { this.convertToFdb(query); this.convertToFdb(update); } else { // Decouple the update data update = this.decouple(update); } // Handle transform update = this.transformIn(update); return this._handleUpdate(query, update, options, callback); }; /** * Handles the update operation that was initiated by a call to update(). * @param {Object} query The query that must be matched for a * document to be operated on. * @param {Object} update The object containing updated * key/values. Any keys that match keys on the existing document * will be overwritten with this data. Any keys that do not * currently exist on the document will be added to the document. * @param {Object=} options An options object. * @param {Function=} callback The callback method to call when * the update is complete. * @returns {Array} The items that were updated. * @private */ Collection.prototype._handleUpdate = function (query, update, options, callback) { var self = this, op = this._metrics.create('update'), dataSet, updated, updateCall = function (referencedDoc) { var oldDoc = self.decouple(referencedDoc), newDoc, triggerOperation, result; if (self.willTrigger(self.TYPE_UPDATE, self.PHASE_BEFORE) || self.willTrigger(self.TYPE_UPDATE, self.PHASE_AFTER)) { newDoc = self.decouple(referencedDoc); triggerOperation = { type: 'update', query: self.decouple(query), update: self.decouple(update), options: self.decouple(options), op: op }; // Update newDoc with the update criteria so we know what the data will look // like AFTER the update is processed result = self.updateObject(newDoc, triggerOperation.update, triggerOperation.query, triggerOperation.options, ''); if (self.processTrigger(triggerOperation, self.TYPE_UPDATE, self.PHASE_BEFORE, referencedDoc, newDoc) !== false) { // No triggers complained so let's execute the replacement of the existing // object with the new one result = self.updateObject(referencedDoc, newDoc, triggerOperation.query, triggerOperation.options, ''); // NOTE: If for some reason we would only like to fire this event if changes are actually going // to occur on the object from the proposed update then we can add "result &&" to the if self.processTrigger(triggerOperation, self.TYPE_UPDATE, self.PHASE_AFTER, oldDoc, newDoc); } else { // Trigger cancelled operation so tell result that it was not updated result = false; } } else { // No triggers complained so let's execute the replacement of the existing // object with the new one result = self.updateObject(referencedDoc, update, query, options, ''); } // Inform indexes of the change self._updateIndexes(oldDoc, referencedDoc); return result; }; op.start(); op.time('Retrieve documents to update'); dataSet = this.find(query, {$decouple: false}); op.time('Retrieve documents to update'); if (dataSet.length) { op.time('Update documents'); updated = dataSet.filter(updateCall); op.time('Update documents'); if (updated.length) { if (this.debug()) { console.log(this.logIdentifier() + ' Updated some data'); } op.time('Resolve chains'); if (this.chainWillSend()) { this.chainSend('update', { query: query, update: update, dataSet: this.decouple(updated) }, options); } op.time('Resolve chains'); this._onUpdate(updated); this._onChange(); if (callback) { callback.call(this, updated || []); } this.emit('immediateChange', {type: 'update', data: updated}); this.deferEmit('change', {type: 'update', data: updated}); } else { if (callback) { callback.call(this, updated || []); } } } else { if (callback) { callback.call(this, updated || []); } } op.stop(); // TODO: Should we decouple the updated array before return by default? return updated || []; }; /** * Replaces an existing object with data from the new object without * breaking data references. It does this by removing existing keys * from the base object and then adding the passed object's keys to * the existing base object, thereby maintaining any references to * the existing base object but effectively replacing the object with * the new one. * @param {Object} currentObj The base object to alter. * @param {Object} newObj The new object to overwrite the existing one * with. * @returns {*} Chain. * @private */ Collection.prototype._replaceObj = function (currentObj, newObj) { var i; // Check if the new document has a different primary key value from the existing one // Remove item from indexes this._removeFromIndexes(currentObj); // Remove existing keys from current object for (i in currentObj) { if (currentObj.hasOwnProperty(i)) { delete currentObj[i]; } } // Add new keys to current object for (i in newObj) { if (newObj.hasOwnProperty(i)) { currentObj[i] = newObj[i]; } } // Update the item in the primary index if (!this._insertIntoIndexes(currentObj)) { throw(this.logIdentifier() + ' Primary key violation in update! Key violated: ' + currentObj[this._primaryKey]); } // Update the object in the collection data //this._data.splice(this._data.indexOf(currentObj), 1, newObj); return this; }; /** * Helper method to update a document via it's id. * @param {String} id The id of the document. * @param {Object} update The object containing the key/values to * update to. * @returns {Object} The document that was updated or undefined * if no document was updated. */ Collection.prototype.updateById = function (id, update) { var searchObj = {}; searchObj[this._primaryKey] = id; return this.update(searchObj, update)[0]; }; /** * Internal method for document updating. * @param {Object} doc The document to update. * @param {Object} update The object with key/value pairs to update * the document with. * @param {Object} query The query object that we need to match to * perform an update. * @param {Object} options An options object. * @param {String} path The current recursive path. * @param {String} opType The type of update operation to perform, * if none is specified default is to set new data against matching * fields. * @returns {Boolean} True if the document was updated with new / * changed data or false if it was not updated because the data was * the same. * @private */ Collection.prototype.updateObject = function (doc, update, query, options, path, opType) { // TODO: This method is long, try to break it into smaller pieces update = this.decouple(update); // Clear leading dots from path path = path || ''; if (path.substr(0, 1) === '.') { path = path.substr(1, path.length -1); } //var oldDoc = this.decouple(doc), var updated = false, recurseUpdated = false, operation, tmpArray, tmpIndex, tmpCount, tempIndex, tempKey, replaceObj, pk, pathInstance, sourceIsArray, updateIsArray, i; // Loop each key in the update object for (i in update) { if (update.hasOwnProperty(i)) { // Reset operation flag operation = false; // Check if the property starts with a dollar (function) if (i.substr(0, 1) === '$') { // Check for commands switch (i) { case '$key': case '$index': case '$data': case '$min': case '$max': // Ignore some operators operation = true; break; case '$each': operation = true; // Loop over the array of updates and run each one tmpCount = update.$each.length; for (tmpIndex = 0; tmpIndex < tmpCount; tmpIndex++) { recurseUpdated = this.updateObject(doc, update.$each[tmpIndex], query, options, path); if (recurseUpdated) { updated = true; } } updated = updated || recurseUpdated; break; case '$replace': operation = true; replaceObj = update.$replace; pk = this.primaryKey(); // Loop the existing item properties and compare with // the replacement (never remove primary key) for (tempKey in doc) { if (doc.hasOwnProperty(tempKey) && tempKey !== pk) { if (replaceObj[tempKey] === undefined) { // The new document doesn't have this field, remove it from the doc this._updateUnset(doc, tempKey); updated = true; } } } // Loop the new item props and update the doc for (tempKey in replaceObj) { if (replaceObj.hasOwnProperty(tempKey) && tempKey !== pk) { this._updateOverwrite(doc, tempKey, replaceObj[tempKey]); updated = true; } } break; default: operation = true; // Now run the operation recurseUpdated = this.updateObject(doc, update[i], query, options, path, i); updated = updated || recurseUpdated; break; } } // Check if the key has a .$ at the end, denoting an array lookup if (this._isPositionalKey(i)) { operation = true; // Modify i to be the name of the field i = i.substr(0, i.length - 2); pathInstance = new Path(path + '.' + i); // Check if the key is an array and has items if (doc[i] && doc[i] instanceof Array && doc[i].length) { tmpArray = []; // Loop the array and find matches to our search for (tmpIndex = 0; tmpIndex < doc[i].length; tmpIndex++) { if (this._match(doc[i][tmpIndex], pathInstance.value(query)[0], options, '', {})) { tmpArray.push(tmpIndex); } } // Loop the items that matched and update them for (tmpIndex = 0; tmpIndex < tmpArray.length; tmpIndex++) { recurseUpdated = this.updateObject(doc[i][tmpArray[tmpIndex]], update[i + '.$'], query, options, path + '.' + i, opType); updated = updated || recurseUpdated; } } } if (!operation) { if (!opType && typeof(update[i]) === 'object') { if (doc[i] !== null && typeof(doc[i]) === 'object') { // Check if we are dealing with arrays sourceIsArray = doc[i] instanceof Array; updateIsArray = update[i] instanceof Array; if (sourceIsArray || updateIsArray) { // Check if the update is an object and the doc is an array if (!updateIsArray && sourceIsArray) { // Update is an object, source is an array so match the array items // with our query object to find the one to update inside this array // Loop the array and find matches to our search for (tmpIndex = 0; tmpIndex < doc[i].length; tmpIndex++) { recurseUpdated = this.updateObject(doc[i][tmpIndex], update[i], query, options, path + '.' + i, opType); updated = updated || recurseUpdated; } } else { // Either both source and update are arrays or the update is // an array and the source is not, so set source to update if (doc[i] !== update[i]) { this._updateProperty(doc, i, update[i]); updated = true; } } } else { // The doc key is an object so traverse the // update further recurseUpdated = this.updateObject(doc[i], update[i], query, options, path + '.' + i, opType); updated = updated || recurseUpdated; } } else { if (doc[i] !== update[i]) { this._updateProperty(doc, i, update[i]); updated = true; } } } else { switch (opType) { case '$inc': var doUpdate = true; // Check for a $min / $max operator if (update[i] > 0) { if (update.$max) { // Check current value if (doc[i] >= update.$max) { // Don't update doUpdate = false; } } } else if (update[i] < 0) { if (update.$min) { // Check current value if (doc[i] <= update.$min) { // Don't update doUpdate = false; } } } if (doUpdate) { this._updateIncrement(doc, i, update[i]); updated = true; } break; case '$cast': // Casts a property to the type specified if it is not already // that type. If the cast is an array or an object and the property // is not already that type a new array or object is created and // set to the property, overwriting the previous value switch (update[i]) { case 'array': if (!(doc[i] instanceof Array)) { // Cast to an array this._updateProperty(doc, i, update.$data || []); updated = true; } break; case 'object': if (!(doc[i] instanceof Object) || (doc[i] instanceof Array)) { // Cast to an object this._updateProperty(doc, i, update.$data || {}); updated = true; } break; case 'number': if (typeof doc[i] !== 'number') { // Cast to a number this._updateProperty(doc, i, Number(doc[i])); updated = true; } break; case 'string': if (typeof doc[i] !== 'string') { // Cast to a string this._updateProperty(doc, i, String(doc[i])); updated = true; } break; default: throw(this.logIdentifier() + ' Cannot update cast to unknown type: ' + update[i]); } break; case '$push': // Check if the target key is undefined and if so, create an array if (doc[i] === undefined) { // Initialise a new array this._updateProperty(doc, i, []); } // Check that the target key is an array if (doc[i] instanceof Array) { // Check for a $position modifier with an $each if (update[i].$position !== undefined && update[i].$each instanceof Array) { // Grab the position to insert at tempIndex = update[i].$position; // Loop the each array and push each item tmpCount = update[i].$each.length; for (tmpIndex = 0; tmpIndex < tmpCount; tmpIndex++) { this._updateSplicePush(doc[i], tempIndex + tmpIndex, update[i].$each[tmpIndex]); } } else if (update[i].$each instanceof Array) { // Do a loop over the each to push multiple items tmpCount = update[i].$each.length; for (tmpIndex = 0; tmpIndex < tmpCount; tmpIndex++) { this._updatePush(doc[i], update[i].$each[tmpIndex]); } } else { // Do a standard push this._updatePush(doc[i], update[i]); } updated = true; } else { throw(this.logIdentifier() + ' Cannot push to a key that is not an array! (' + i + ')'); } break; case '$pull': if (doc[i] instanceof Array) { tmpArray = []; // Loop the array and find matches to our search for (tmpIndex = 0; tmpIndex < doc[i].length; tmpIndex++) { if (this._match(doc[i][tmpIndex], update[i], options, '', {})) { tmpArray.push(tmpIndex); } } tmpCount = tmpArray.length; // Now loop the pull array and remove items to be pulled while (tmpCount--) { this._updatePull(doc[i], tmpArray[tmpCount]); updated = true; } } break; case '$pullAll': if (doc[i] instanceof Array) { if (update[i] instanceof Array) { tmpArray = doc[i]; tmpCount = tmpArray.length; if (tmpCount > 0) { // Now loop the pull array and remove items to be pulled while (tmpCount--) { for (tempIndex = 0; tempIndex < update[i].length; tempIndex++) { if (tmpArray[tmpCount] === update[i][tempIndex]) { this._updatePull(doc[i], tmpCount); tmpCount--; updated = true; } } if (tmpCount < 0) { break; } } } } else { throw(this.logIdentifier() + ' Cannot pullAll without being given an array of values to pull! (' + i + ')'); } } break; case '$addToSet': // Check if the target key is undefined and if so, create an array if (doc[i] === undefined) { // Initialise a new array this._updateProperty(doc, i, []); } // Check that the target key is an array if (doc[i] instanceof Array) { // Loop the target array and check for existence of item var targetArr = doc[i], targetArrIndex, targetArrCount = targetArr.length, objHash, addObj = true, optionObj = (options && options.$addToSet), hashMode, pathSolver; // Check if we have an options object for our operation if (update[i].$key) { hashMode = false; pathSolver = new Path(update[i].$key); objHash = pathSolver.value(update[i])[0]; // Remove the key from the object before we add it delete update[i].$key; } else if (optionObj && optionObj.key) { hashMode = false; pathSolver = new Path(optionObj.key); objHash = pathSolver.value(update[i])[0]; } else { objHash = this.jStringify(update[i]); hashMode = true; } for (targetArrIndex = 0; targetArrIndex < targetArrCount; targetArrIndex++) { if (hashMode) { // Check if objects match via a string hash (JSON) if (this.jStringify(targetArr[targetArrIndex]) === objHash) { // The object already exists, don't add it addObj = false; break; } } else { // Check if objects match based on the path if (objHash === pathSolver.value(targetArr[targetArrIndex])[0]) { // The object already exists, don't add it addObj = false; break; } } } if (addObj) { this._updatePush(doc[i], update[i]); updated = true; } } else { throw(this.logIdentifier() + ' Cannot addToSet on a key that is not an array! (' + i + ')'); } break; case '$splicePush': // Check if the target key is undefined and if so, create an array if (doc[i] === undefined) { // Initialise a new array this._updateProperty(doc, i, []); } // Check that the target key is an array if (doc[i] instanceof Array) { tempIndex = update.$index; if (tempIndex !== undefined) { delete update.$index; // Check for out of bounds index if (tempIndex > doc[i].length) { tempIndex = doc[i].length; } this._updateSplicePush(doc[i], tempIndex, update[i]); updated = true; } else { throw(this.logIdentifier() + ' Cannot splicePush without a $index integer value!'); } } else { throw(this.logIdentifier() + ' Cannot splicePush with a key that is not an array! (' + i + ')'); } break; case '$splicePull': // Check that the target key is not undefined if (doc[i] !== undefined) { // Check that the target key is an array if (doc[i] instanceof Array) { tempIndex = update[i].$index; if (tempIndex !== undefined) { // Check for in bounds index if (tempIndex < doc[i].length) { this._updateSplicePull(doc[i], tempIndex); updated = true; } } else { throw(this.logIdentifier() + ' Cannot splicePull without a $index integer value!'); } } else { throw(this.logIdentifier() + ' Cannot splicePull from a key that is not an array! (' + i + ')'); } } break; case '$move': if (doc[i] instanceof Array) { // Loop the array and find matches to our search for (tmpIndex = 0; tmpIndex < doc[i].length; tmpIndex++) { if (this._match(doc[i][tmpIndex], update[i], options, '', {})) { var moveToIndex = update.$index; if (moveToIndex !== undefined) { delete update.$index; this._updateSpliceMove(doc[i], tmpIndex, moveToIndex); updated = true; } else { throw(this.logIdentifier() + ' Cannot move without a $index integer value!'); } break; } } } else { throw(this.logIdentifier() + ' Cannot move on a key that is not an array! (' + i + ')'); } break; case '$mul': this._updateMultiply(doc, i, update[i]); updated = true; break; case '$rename': this._updateRename(doc, i, update[i]); updated = true; break; case '$overwrite': this._updateOverwrite(doc, i, update[i]); updated = true; break; case '$unset': this._updateUnset(doc, i); updated = true; break; case '$clear': this._updateClear(doc, i); updated = true; break; case '$pop': if (doc[i] instanceof Array) { if (this._updatePop(doc[i], update[i])) { updated = true; } } else { throw(this.logIdentifier() + ' Cannot pop from a key that is not an array! (' + i + ')'); } break; case '$toggle': // Toggle the boolean property between true and false this._updateProperty(doc, i, !doc[i]); updated = true; break; default: if (doc[i] !== update[i]) { this._updateProperty(doc, i, update[i]); updated = true; } break; } } } } } return updated; }; /** * Determines if the passed key has an array positional mark * (a dollar at the end of its name). * @param {String} key The key to check. * @returns {Boolean} True if it is a positional or false if not. * @private */ Collection.prototype._isPositionalKey = function (key) { return key.substr(key.length - 2, 2) === '.$'; }; /** * Removes any documents from the collection that match the search * query key/values. * @param {Object} query The query object. * @param {Object=} options An options object. * @param {Function=} callback A callback method. * @returns {Array} An array of the documents that were removed. */ Collection.prototype.remove = function (query, options, callback) { if (this.isDropped()) { throw(this.logIdentifier() + ' Cannot operate in a dropped state!'); } var self = this, dataSet, index, arrIndex, returnArr, removeMethod, triggerOperation, doc, newDoc; if (typeof(options) === 'function') { callback = options; options = {}; } // Convert queries from mongo dot notation to forerunner queries if (this.mongoEmulation()) { this.convertToFdb(query); } if (query instanceof Array) { returnArr = []; for (arrIndex = 0; arrIndex < query.length; arrIndex++) { returnArr.push(this.remove(query[arrIndex], {noEmit: true})); } if (!options || (options && !options.noEmit)) { this._onRemove(returnArr); } if (callback) { callback.call(this, false, returnArr); } return returnArr; } else { returnArr = []; dataSet = this.find(query, {$decouple: false}); if (dataSet.length) { removeMethod = function (dataItem) { // Remove the item from the collection's indexes self._removeFromIndexes(dataItem); // Remove data from internal stores index = self._data.indexOf(dataItem); self._dataRemoveAtIndex(index); returnArr.push(dataItem); }; // Remove the data from the collection for (var i = 0; i < dataSet.length; i++) { doc = dataSet[i]; if (self.willTrigger(self.TYPE_REMOVE, self.PHASE_BEFORE) || self.willTrigger(self.TYPE_REMOVE, self.PHASE_AFTER)) { triggerOperation = { type: 'remove' }; newDoc = self.decouple(doc); if (self.processTrigger(triggerOperation, self.TYPE_REMOVE, self.PHASE_BEFORE, newDoc, newDoc) !== false) { // The trigger didn't ask to cancel so execute the removal method removeMethod(doc); self.processTrigger(triggerOperation, self.TYPE_REMOVE, self.PHASE_AFTER, newDoc, newDoc); } } else { // No triggers to execute removeMethod(doc); } } if (returnArr.length) { //op.time('Resolve chains'); self.chainSend('remove', { query: query, dataSet: returnArr }, options); //op.time('Resolve chains'); if (!options || (options && !options.noEmit)) { this._onRemove(returnArr); } this._onChange(); this.emit('immediateChange', {type: 'remove', data: returnArr}); this.deferEmit('change', {type: 'remove', data: returnArr}); } } if (callback) { callback.call(this, false, returnArr); } return returnArr; } }; /** * Helper method that removes a document that matches the given id. * @param {String} id The id of the document to remove. * @returns {Object} The document that was removed or undefined if * nothing was removed. */ Collection.prototype.removeById = function (id) { var searchObj = {}; searchObj[this._primaryKey] = id; return this.remove(searchObj)[0]; }; /** * Processes a deferred action queue. * @param {String} type The queue name to process. * @param {Function} callback A method to call when the queue has processed. * @param {Object=} resultObj A temp object to hold results in. */ Collection.prototype.processQueue = function (type, callback, resultObj) { var self = this, queue = this._deferQueue[type], deferThreshold = this._deferThreshold[type], deferTime = this._deferTime[type], dataArr, result; resultObj = resultObj || { deferred: true }; if (queue.length) { // Process items up to the threshold if (queue.length > deferThreshold) { // Grab items up to the threshold value dataArr = queue.splice(0, deferThreshold); } else { // Grab all the remaining items dataArr = queue.splice(0, queue.length); } result = self[type](dataArr); switch (type) { case 'insert': resultObj.inserted = resultObj.inserted || []; resultObj.failed = resultObj.failed || []; resultObj.inserted = resultObj.inserted.concat(result.inserted); resultObj.failed = resultObj.failed.concat(result.failed); break; } // Queue another process setTimeout(function () { self.processQueue.call(self, type, callback, resultObj); }, deferTime); } else { if (callback) { callback.call(this, resultObj); } this._asyncComplete(type); } // Check if all queues are complete if (!this.isProcessingQueue()) { this.deferEmit('queuesComplete'); } }; /** * Checks if any CRUD operations have been deferred and are still waiting to * be processed. * @returns {Boolean} True if there are still deferred CRUD operations to process * or false if all queues are clear. */ Collection.prototype.isProcessingQueue = function () { var i; for (i in this._deferQueue) { if (this._deferQueue.hasOwnProperty(i)) { if (this._deferQueue[i].length) { return true; } } } return false; }; /** * Inserts a document or array of documents into the collection. * @param {Object|Array} data Either a document object or array of document * @param {Number=} index Optional index to insert the record at. * @param {Collection~insertCallback=} callback Optional callback called * once the insert is complete. */ Collection.prototype.insert = function (data, index, callback) { if (this.isDropped()) { throw(this.logIdentifier() + ' Cannot operate in a dropped state!'); } if (typeof(index) === 'function') { callback = index; index = this._data.length; } else if (index === undefined) { index = this._data.length; } data = this.transformIn(data); return this._insertHandle(data, index, callback); }; /** * The insert operation's callback. * @callback Collection~insertCallback * @param {Object} result The result object will contain two arrays (inserted * and failed) which represent the documents that did get inserted and those * that didn't for some reason (usually index violation). Failed items also * contain a reason. Inspect the failed array for further information. * * A third field called "deferred" is a boolean value to indicate if the * insert operation was deferred across more than one CPU cycle (to avoid * blocking the main thread). */ /** * 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 {Collection~insertCallback=} callback Optional callback called * once the insert is complete. */ Collection.prototype._insertHandle = function (data, index, callback) { var //self = this, queue = this._deferQueue.insert, deferThreshold = this._deferThreshold.insert, //deferTime = this._deferTime.insert, inserted = [], failed = [], insertResult, resultObj, i; if (data instanceof Array) { // Check if there are more insert items than the insert defer // threshold, if so, break up inserts so we don't tie up the // ui or thread if (this._deferredCalls && data.length > deferThreshold) { // Break up insert into blocks this._deferQueue.insert = queue.concat(data); this._asyncPending('insert'); // Fire off the insert queue handler this.processQueue('insert', callback); return; } else { // Loop the array and add items for (i = 0; i < data.length; i++) { insertResult = this._insert(data[i], index + i); if (insertResult === true) { inserted.push(data[i]); } else { failed.push({ doc: data[i], reason: insertResult }); } } } } else { // Store the data item insertResult = this._insert(data, index); if (insertResult === true) { inserted.push(data); } else { failed.push({ doc: data, reason: insertResult }); } } resultObj = { deferred: false, inserted: inserted, failed: failed }; this._onInsert(inserted, failed); if (callback) { callback.call(this, resultObj); } this._onChange(); this.emit('immediateChange', {type: 'insert', data: inserted, failed: failed}); this.deferEmit('change', {type: 'insert', data: inserted, failed: failed}); return resultObj; }; /** * Internal method to insert a document into the collection. Will * check for index violations before allowing the document to be inserted. * @param {Object} doc The document to insert after passing index violation * tests. * @param {Number=} index Optional index to insert the document at. * @returns {Boolean|Object} True on success, false if no document passed, * or an object containing details about an index violation if one occurred. * @private */ Collection.prototype._insert = function (doc, index) { if (doc) { var self = this, indexViolation, triggerOperation, insertMethod, newDoc, capped = this.capped(), cappedSize = this.cappedSize(); this.ensurePrimaryKey(doc); // Check indexes are not going to be broken by the document indexViolation = this.insertIndexViolation(doc); insertMethod = function (doc) { // Add the item to the collection's indexes self._insertIntoIndexes(doc); // Check index overflow if (index > self._data.length) { index = self._data.length; } // Insert the document self._dataInsertAtIndex(index, doc); // Check capped collection status and remove first record // if we are over the threshold if (capped && self._data.length > cappedSize) { // Remove the first item in the data array self.removeById(self._data[0][self._primaryKey]); } //op.time('Resolve chains'); if (self.chainWillSend()) { self.chainSend('insert', { dataSet: self.decouple([doc]) }, { index: index }); } //op.time('Resolve chains'); }; if (!indexViolation) { if (self.willTrigger(self.TYPE_INSERT, self.PHASE_BEFORE) || self.willTrigger(self.TYPE_INSERT, self.PHASE_AFTER)) { triggerOperation = { type: 'insert' }; if (self.processTrigger(triggerOperation, self.TYPE_INSERT, self.PHASE_BEFORE, {}, doc) !== false) { insertMethod(doc); if (self.willTrigger(self.TYPE_INSERT, self.PHASE_AFTER)) { // Clone the doc so that the programmer cannot update the internal document // on the "after" phase trigger newDoc = self.decouple(doc); self.processTrigger(triggerOperation, self.TYPE_INSERT, self.PHASE_AFTER, {}, newDoc); } } else { // The trigger just wants to cancel the operation return 'Trigger cancelled operation'; } } else { // No triggers to execute insertMethod(doc); } return true; } else { return 'Index violation in index: ' + indexViolation; } } return 'No document passed to insert'; }; /** * Inserts a document into the internal collection data array at * Inserts a document into the internal collection data array at * the specified index. * @param {number} index The index to insert at. * @param {object} doc The document to insert. * @private */ Collection.prototype._dataInsertAtIndex = function (index, doc) { this._data.splice(index, 0, doc); }; /** * Removes a document from the internal collection data array at * the specified index. * @param {number} index The index to remove from. * @private */ Collection.prototype._dataRemoveAtIndex = function (index) { this._data.splice(index, 1); }; /** * Replaces all data in the collection's internal data array with * the passed array of data. * @param {array} data The array of data to replace existing data with. * @private */ Collection.prototype._dataReplace = function (data) { // Clear the array - using a while loop with pop is by far the // fastest way to clear an array currently while (this._data.length) { this._data.pop(); } // Append new items to the array this._data = this._data.concat(data); }; /** * Inserts a document into the collection indexes. * @param {Object} doc The document to insert. * @private */ Collection.prototype._insertIntoIndexes = function (doc) { var arr = this._indexByName, arrIndex, violated, hash = this.hash(doc), pk = this._primaryKey; // Insert to primary key index violated = this._primaryIndex.uniqueSet(doc[pk], doc); this._primaryCrc.uniqueSet(doc[pk], hash); this._crcLookup.uniqueSet(hash, doc); // Insert into other indexes for (arrIndex in arr) { if (arr.hasOwnProperty(arrIndex)) { arr[arrIndex].insert(doc); } } return violated; }; /** * Removes a document from the collection indexes. * @param {Object} doc The document to remove. * @private */ Collection.prototype._removeFromIndexes = function (doc) { var arr = this._indexByName, arrIndex, hash = this.hash(doc), pk = this._primaryKey; // Remove from primary key index this._primaryIndex.unSet(doc[pk]); this._primaryCrc.unSet(doc[pk]); this._crcLookup.unSet(hash); // Remove from other indexes for (arrIndex in arr) { if (arr.hasOwnProperty(arrIndex)) { arr[arrIndex].remove(doc); } } }; /** * Updates collection index data for the passed document. * @param {Object} oldDoc The old document as it was before the update. * @param {Object} newDoc The document as it now is after the update. * @private */ Collection.prototype._updateIndexes = function (oldDoc, newDoc) { this._removeFromIndexes(oldDoc); this._insertIntoIndexes(newDoc); }; /** * Rebuild collection indexes. * @private */ Collection.prototype._rebuildIndexes = function () { var arr = this._indexByName, arrIndex; // Remove from other indexes for (arrIndex in arr) { if (arr.hasOwnProperty(arrIndex)) { arr[arrIndex].rebuild(); } } }; /** * Uses the passed query to generate a new collection with results * matching the query parameters. * * @param {Object} query The query object to generate the subset with. * @param {Object=} options An options object. * @returns {*} */ Collection.prototype.subset = function (query, options) { var result = this.find(query, options), coll; coll = new Collection(); coll.db(this._db); coll.subsetOf(this) .primaryKey(this._primaryKey) .setData(result); return coll; }; /** * Gets / sets the collection that this collection is a subset of. * @param {Collection=} collection The collection to set as the parent of this subset. * @returns {Collection} */ Shared.synthesize(Collection.prototype, 'subsetOf'); /** * Checks if the collection is a subset of the passed collection. * @param {Collection} collection The collection to test against. * @returns {Boolean} True if the passed collection is the parent of * the current collection. */ Collection.prototype.isSubsetOf = function (collection) { return this._subsetOf === collection; }; /** * Find the distinct values for a specified field across a single collection and * returns the results in an array. * @param {String} key The field path to return distinct values for e.g. "person.name". * @param {Object=} query The query to use to filter the documents used to return values from. * @param {Object=} options The query options to use when running the query. * @returns {Array} */ Collection.prototype.distinct = function (key, query, options) { if (this.isDropped()) { throw(this.logIdentifier() + ' Cannot operate in a dropped state!'); } var data = this.find(query, options), pathSolver = new Path(key), valueUsed = {}, distinctValues = [], value, i; // Loop the data and build array of distinct values for (i = 0; i < data.length; i++) { value = pathSolver.value(data[i])[0]; if (value && !valueUsed[value]) { valueUsed[value] = true; distinctValues.push(value); } } return distinctValues; }; /** * Helper method to find a document by it's id. * @param {String} id The id of the document. * @param {Object=} options The options object, allowed keys are sort and limit. * @returns {Array} The items that were updated. */ Collection.prototype.findById = function (id, options) { var searchObj = {}; searchObj[this._primaryKey] = id; return this.find(searchObj, options)[0]; }; /** * Finds all documents that contain the passed string or search object * regardless of where the string might occur within the document. This * will match strings from the start, middle or end of the document's * string (partial match). * @param {String} search The string to search for. Case sensitive. * @param {Object=} options A standard find() options object. * @returns {Array} An array of documents that matched the search string. */ Collection.prototype.peek = function (search, options) { // Loop all items var arr = this._data, arrCount = arr.length, arrIndex, arrItem, tempColl = new Collection(), typeOfSearch = typeof search; if (typeOfSearch === 'string') { for (arrIndex = 0; arrIndex < arrCount; arrIndex++) { // Get json representation of object arrItem = this.jStringify(arr[arrIndex]); // Check if string exists in object json if (arrItem.indexOf(search) > -1) { // Add this item to the temp collection tempColl.insert(arr[arrIndex]); } } return tempColl.find({}, options); } else { return this.find(search, options); } }; /** * Provides a query plan / operations log for a query. * @param {Object} query The query to execute. * @param {Object=} options Optional options object. * @returns {Object} The query plan. */ Collection.prototype.explain = function (query, options) { var result = this.find(query, options); return result.__fdbOp._data; }; /** * Generates an options object with default values or adds default * values to a passed object if those values are not currently set * to anything. * @param {object=} obj Optional options object to modify. * @returns {object} The options object. */ Collection.prototype.options = function (obj) { obj = obj || {}; obj.$decouple = obj.$decouple !== undefined ? obj.$decouple : true; obj.$explain = obj.$explain !== undefined ? obj.$explain : false; return obj; }; /** * Queries the collection based on the query object passed. * @param {Object} query The query key/values that a document must match in * order for it to be returned in the result array. * @param {Object=} options An optional options object. * @param {Function=} callback !! DO NOT USE, THIS IS NON-OPERATIONAL !! * Optional callback. If specified the find process * will not return a value and will assume that you wish to operate under an * async mode. This will break up large find requests into smaller chunks and * process them in a non-blocking fashion allowing large datasets to be queried * without causing the browser UI to pause. Results from this type of operation * will be passed back to the callback once completed. * * @returns {Array} The results array from the find operation, containing all * documents that matched the query. */ Collection.prototype.find = function (query, options, callback) { // Convert queries from mongo dot notation to forerunner queries if (this.mongoEmulation()) { this.convertToFdb(query); } if (callback) { // Check the size of the collection's data array // Split operation into smaller tasks and callback when complete callback.call(this, 'Callbacks for the find() operation are not yet implemented!', []); return []; } return this._find.call(this, query, options, callback); }; Collection.prototype._find = function (query, options) { if (this.isDropped()) { throw(this.logIdentifier() + ' Cannot operate in a dropped state!'); } // TODO: This method is quite long, break into smaller pieces query = query || {}; var op = this._metrics.create('find'), pk = this.primaryKey(), self = this, analysis, scanLength, requiresTableScan = true, resultArr, joinIndex, joinSource = {}, joinQuery, joinPath, joinSourceKey, joinSourceType, joinSourceIdentifier, joinSourceData, resultRemove = [], i, j, k, fieldListOn = [], fieldListOff = [], elemMatchPathSolver, elemMatchSubArr, elemMatchSpliceArr, matcherTmpOptions = {}, result, cursor = {}, pathSolver, waterfallCollection, matcher; if (!(options instanceof Array)) { options = this.options(options); } matcher = function (doc) { return self._match(doc, query, options, 'and', matcherTmpOptions); }; op.start(); if (query) { // Check if the query is an array (multi-operation waterfall query) if (query instanceof Array) { waterfallCollection = this; // Loop the query operations for (i = 0; i < query.length; i++) { // Execute each operation and pass the result into the next // query operation waterfallCollection = waterfallCollection.subset(query[i], options && options[i] ? options[i] : {}); } return waterfallCollection.find(); } // Pre-process any data-changing query operators first if (query.$findSub) { // Check we have all the parts we need if (!query.$findSub.$path) { throw('$findSub missing $path property!'); } return this.findSub( query.$findSub.$query, query.$findSub.$path, query.$findSub.$subQuery, query.$findSub.$subOptions ); } if (query.$findSubOne) { // Check we have all the parts we need if (!query.$findSubOne.$path) { throw('$findSubOne missing $path property!'); } return this.findSubOne( query.$findSubOne.$query, query.$findSubOne.$path, query.$findSubOne.$subQuery, query.$findSubOne.$subOptions ); } // Get query analysis to execute best optimised code path op.time('analyseQuery'); analysis = this._analyseQuery(self.decouple(query), options, op); op.time('analyseQuery'); op.data('analysis', analysis); // Check if the query tries to limit by data that would only exist after // the join operation has been completed if (analysis.hasJoin && analysis.queriesJoin) { // The query has a join and tries to limit by it's joined data // Get references to the join sources op.time('joinReferences'); for (joinIndex = 0; joinIndex < analysis.joinsOn.length; joinIndex++) { joinSourceData = analysis.joinsOn[joinIndex]; joinSourceKey = joinSourceData.key; joinSourceType = joinSourceData.type; joinSourceIdentifier = joinSourceData.id; joinPath = new Path(analysis.joinQueries[joinSourceKey]); joinQuery = joinPath.value(query)[0]; joinSource[joinSourceIdentifier] = this._db[joinSourceType](joinSourceKey).subset(joinQuery); // Remove join clause from main query delete query[analysis.joinQueries[joinSourceKey]]; } op.time('joinReferences'); } // Check if an index lookup can be used to return this result if (analysis.indexMatch.length && (!options || (options && !options.$skipIndex))) { op.data('index.potential', analysis.indexMatch); op.data('index.used', analysis.indexMatch[0].index); // Get the data from the index op.time('indexLookup'); resultArr = analysis.indexMatch[0].lookup || []; op.time('indexLookup'); // Check if the index coverage is all keys, if not we still need to table scan it if (analysis.indexMatch[0].keyData.totalKeyCount === analysis.indexMatch[0].keyData.score) { // Don't require a table scan to find relevant documents requiresTableScan = false; } } else { op.flag('usedIndex', false); } if (requiresTableScan) { if (resultArr && resultArr.length) { scanLength = resultArr.length; op.time('tableScan: ' + scanLength); // Filter the source data and return the result resultArr = resultArr.filter(matcher); } else { // Filter the source data and return the result scanLength = this._data.length; op.time('tableScan: ' + scanLength); resultArr = this._data.filter(matcher); } op.time('tableScan: ' + scanLength); } // Order the array if we were passed a sort clause if (options.$orderBy) { op.time('sort'); resultArr = this.sort(options.$orderBy, resultArr); op.time('sort'); } if (options.$page !== undefined && options.$limit !== undefined) { // Record paging data cursor.page = options.$page; cursor.pages = Math.ceil(resultArr.length / options.$limit); cursor.records = resultArr.length; // Check if we actually need to apply the paging logic if (options.$page && options.$limit > 0) { op.data('cursor', cursor); // Skip to the page specified based on limit resultArr.splice(0, options.$page * options.$limit); } } if (options.$skip) { cursor.skip = options.$skip; // Skip past the number of records specified resultArr.splice(0, options.$skip); op.data('skip', options.$skip); } if (options.$limit && resultArr && resultArr.length > options.$limit) { cursor.limit = options.$limit; resultArr.length = options.$limit; op.data('limit', options.$limit); } if (options.$decouple) { // Now decouple the data from the original objects op.time('decouple'); resultArr = this.decouple(resultArr); op.time('decouple'); op.data('flag.decouple', true); } // Now process any joins on the final data if (options.$join) { resultRemove = resultRemove.concat(this.applyJoin(resultArr, options.$join, joinSource)); op.data('flag.join', true); } // Process removal queue if (resultRemove.length) { op.time('removalQueue'); this.spliceArrayByIndexList(resultArr, resultRemove); op.time('removalQueue'); } if (options.$transform) { op.time('transform'); for (i = 0; i < resultArr.length; i++) { resultArr.splice(i, 1, options.$transform(resultArr[i])); } op.time('transform'); op.data('flag.transform', true); } // Process transforms if (this._transformEnabled && this._transformOut) { op.time('transformOut'); resultArr = this.transformOut(resultArr); op.time('transformOut'); } op.data('results', resultArr.length); } else { resultArr = []; } // Check for an $as operator in the options object and if it exists // iterate over the fields and generate a rename function that will // operate over the entire returned data array and rename each object's // fields to their new names // TODO: Enable $as in collection find to allow renaming fields /*if (options.$as) { renameFieldPath = new Path(); renameFieldMethod = function (obj, oldFieldPath, newFieldName) { renameFieldPath.path(oldFieldPath); renameFieldPath.rename(newFieldName); }; for (i in options.$as) { if (options.$as.hasOwnProperty(i)) { } } }*/ if (!options.$aggregate) { // Generate a list of fields to limit data by // Each property starts off being enabled by default (= 1) then // if any property is explicitly specified as 1 then all switch to // zero except _id. // // Any that are explicitly set to zero are switched off. op.time('scanFields'); for (i in options) { if (options.hasOwnProperty(i) && i.indexOf('$') !== 0) { if (options[i] === 1) { fieldListOn.push(i); } else if (options[i] === 0) { fieldListOff.push(i); } } } op.time('scanFields'); // Limit returned fields by the options data if (fieldListOn.length || fieldListOff.length) { op.data('flag.limitFields', true); op.data('limitFields.on', fieldListOn); op.data('limitFields.off', fieldListOff); op.time('limitFields'); // We have explicit fields switched on or off for (i = 0; i < resultArr.length; i++) { result = resultArr[i]; for (j in result) { if (result.hasOwnProperty(j)) { if (fieldListOn.length) { // We have explicit fields switched on so remove all fields // that are not explicitly switched on // Check if the field name is not the primary key if (j !== pk) { if (fieldListOn.indexOf(j) === -1) { // This field is not in the on list, remove it delete result[j]; } } } if (fieldListOff.length) { // We have explicit fields switched off so remove fields // that are explicitly switched off if (fieldListOff.indexOf(j) > -1) { // This field is in the off list, remove it delete result[j]; } } } } } op.time('limitFields'); } // Now run any projections on the data required if (options.$elemMatch) { op.data('flag.elemMatch', true); op.time('projection-elemMatch'); for (i in options.$elemMatch) { if (options.$elemMatch.hasOwnProperty(i)) { elemMatchPathSolver = new Path(i); // Loop the results array for (j = 0; j < resultArr.length; j++) { elemMatchSubArr = elemMatchPathSolver.value(resultArr[j])[0]; // Check we have a sub-array to loop if (elemMatchSubArr && elemMatchSubArr.length) { // Loop the sub-array and check for projection query matches for (k = 0; k < elemMatchSubArr.length; k++) { // Check if the current item in the sub-array matches the projection query if (self._match(elemMatchSubArr[k], options.$elemMatch[i], options, '', {})) { // The item matches the projection query so set the sub-array // to an array that ONLY contains the matching item and then // exit the loop since we only want to match the first item elemMatchPathSolver.set(resultArr[j], i, [elemMatchSubArr[k]]); break; } } } } } } op.time('projection-elemMatch'); } if (options.$elemsMatch) { op.data('flag.elemsMatch', true); op.time('projection-elemsMatch'); for (i in options.$elemsMatch) { if (options.$elemsMatch.hasOwnProperty(i)) { elemMatchPathSolver = new Path(i); // Loop the results array for (j = 0; j < resultArr.length; j++) { elemMatchSubArr = elemMatchPathSolver.value(resultArr[j])[0]; // Check we have a sub-array to loop if (elemMatchSubArr && elemMatchSubArr.length) { elemMatchSpliceArr = []; // Loop the sub-array and check for projection query matches for (k = 0; k < elemMatchSubArr.length; k++) { // Check if the current item in the sub-array matches the projection query if (self._match(elemMatchSubArr[k], options.$elemsMatch[i], options, '', {})) { // The item matches the projection query so add it to the final array elemMatchSpliceArr.push(elemMatchSubArr[k]); } } // Now set the final sub-array to the matched items elemMatchPathSolver.set(resultArr[j], i, elemMatchSpliceArr); } } } } op.time('projection-elemsMatch'); } } // Process aggregation if (options.$aggregate) { op.data('flag.aggregate', true); op.time('aggregate'); pathSolver = new Path(options.$aggregate); resultArr = pathSolver.value(resultArr); op.time('aggregate'); } // Now process any $groupBy clause if (options.$groupBy) { op.data('flag.group', true); op.time('group'); resultArr = this.group(options.$groupBy, resultArr); op.time('group'); } op.stop(); resultArr.__fdbOp = op; resultArr.$cursor = cursor; return resultArr; }; /** * Returns one document that satisfies the specified query criteria. If multiple * documents satisfy the query, this method returns the first document to match * the query. * @returns {*} */ Collection.prototype.findOne = function () { return (this.find.apply(this, arguments))[0]; }; /** * Gets the index in the collection data array of the first item matched by * the passed query object. * @param {Object} query The query to run to find the item to return the index of. * @param {Object=} options An options object. * @returns {Number} */ Collection.prototype.indexOf = function (query, options) { var item = this.find(query, {$decouple: false})[0], sortedData; if (item) { if (!options || options && !options.$orderBy) { // Basic lookup from order of insert return this._data.indexOf(item); } else { // Trying to locate index based on query with sort order options.$decouple = false; sortedData = this.find(query, options); return sortedData.indexOf(item); } } return -1; }; /** * Returns the index of the document identified by the passed item's primary key. * @param {*} itemLookup The document whose primary key should be used to lookup * or the id to lookup. * @param {Object=} options An options object. * @returns {Number} The index the item with the matching primary key is occupying. */ Collection.prototype.indexOfDocById = function (itemLookup, options) { var item, sortedData; if (typeof itemLookup !== 'object') { item = this._primaryIndex.get(itemLookup); } else { item = this._primaryIndex.get(itemLookup[this._primaryKey]); } if (item) { if (!options || options && !options.$orderBy) { // Basic lookup return this._data.indexOf(item); } else { // Sorted lookup options.$decouple = false; sortedData = this.find({}, options); return sortedData.indexOf(item); } } return -1; }; /** * Removes a document from the collection by it's index in the collection's * data array. * @param {Number} index The index of the document to remove. * @returns {Object} The document that has been removed or false if none was * removed. */ Collection.prototype.removeByIndex = function (index) { var doc, docId; doc = this._data[index]; if (doc !== undefined) { doc = this.decouple(doc); docId = doc[this.primaryKey()]; return this.removeById(docId); } return false; }; /** * Gets / sets the collection transform options. * @param {Object} obj A collection transform options object. * @returns {*} */ Collection.prototype.transform = function (obj) { if (obj !== undefined) { if (typeof obj === "object") { if (obj.enabled !== undefined) { this._transformEnabled = obj.enabled; } if (obj.dataIn !== undefined) { this._transformIn = obj.dataIn; } if (obj.dataOut !== undefined) { this._transformOut = obj.dataOut; } } else { this._transformEnabled = obj !== false; } return this; } return { enabled: this._transformEnabled, dataIn: this._transformIn, dataOut: this._transformOut }; }; /** * Transforms data using the set transformIn method. * @param {Object} data The data to transform. * @returns {*} */ Collection.prototype.transformIn = function (data) { if (this._transformEnabled && this._transformIn) { if (data instanceof Array) { var finalArr = [], transformResult, i; for (i = 0; i < data.length; i++) { transformResult = this._transformIn(data[i]); // Support transforms returning multiple items if (transformResult instanceof Array) { finalArr = finalArr.concat(transformResult); } else { finalArr.push(transformResult); } } return finalArr; } else { return this._transformIn(data); } } return data; }; /** * Transforms data using the set transformOut method. * @param {Object} data The data to transform. * @returns {*} */ Collection.prototype.transformOut = function (data) { if (this._transformEnabled && this._transformOut) { if (data instanceof Array) { var finalArr = [], transformResult, i; for (i = 0; i < data.length; i++) { transformResult = this._transformOut(data[i]); // Support transforms returning multiple items if (transformResult instanceof Array) { finalArr = finalArr.concat(transformResult); } else { finalArr.push(transformResult); } } return finalArr; } else { return this._transformOut(data); } } return data; }; /** * Sorts an array of documents by the given sort path. * @param {*} sortObj The keys and orders the array objects should be sorted by. * @param {Array} arr The array of documents to sort. * @returns {Array} */ Collection.prototype.sort = function (sortObj, arr) { // Convert the index object to an array of key val objects var self = this, keys = sharedPathSolver.parse(sortObj, true); if (keys.length) { // Execute sort arr.sort(function (a, b) { // Loop the index array var i, indexData, result = 0; for (i = 0; i < keys.length; i++) { indexData = keys[i]; if (indexData.value === 1) { result = self.sortAsc(sharedPathSolver.get(a, indexData.path), sharedPathSolver.get(b, indexData.path)); } else if (indexData.value === -1) { result = self.sortDesc(sharedPathSolver.get(a, indexData.path), sharedPathSolver.get(b, indexData.path)); } if (result !== 0) { return result; } } return result; }); } return arr; }; /** * Groups an array of documents into multiple array fields, named by the value * of the given group path. * @param {*} groupObj The key path the array objects should be grouped by. * @param {Array} arr The array of documents to group. * @returns {Object} */ Collection.prototype.group = function (groupObj, arr) { // Convert the index object to an array of key val objects var keys = sharedPathSolver.parse(groupObj, true), groupPathSolver = new Path(), groupValue, groupResult = {}, keyIndex, i; if (keys.length) { for (keyIndex = 0; keyIndex < keys.length; keyIndex++) { groupPathSolver.path(keys[keyIndex].path); // Execute group for (i = 0; i < arr.length; i++) { groupValue = groupPathSolver.get(arr[i]); groupResult[groupValue] = groupResult[groupValue] || []; groupResult[groupValue].push(arr[i]); } } } return groupResult; }; // Commented as we have a new method that was originally implemented for binary trees. // This old method actually has problems with nested sort objects /*Collection.prototype.sortold = function (sortObj, arr) { // Make sure we have an array object arr = arr || []; var sortArr = [], sortKey, sortSingleObj; for (sortKey in sortObj) { if (sortObj.hasOwnProperty(sortKey)) { sortSingleObj = {}; sortSingleObj[sortKey] = sortObj[sortKey]; sortSingleObj.___fdbKey = String(sortKey); sortArr.push(sortSingleObj); } } if (sortArr.length < 2) { // There is only one sort criteria, do a simple sort and return it return this._sort(sortObj, arr); } else { return this._bucketSort(sortArr, arr); } };*/ /** * REMOVED AS SUPERCEDED BY BETTER SORT SYSTEMS * Takes array of sort paths and sorts them into buckets before returning final * array fully sorted by multi-keys. * @param keyArr * @param arr * @returns {*} * @private */ /*Collection.prototype._bucketSort = function (keyArr, arr) { var keyObj = keyArr.shift(), arrCopy, bucketData, bucketOrder, bucketKey, buckets, i, finalArr = []; if (keyArr.length > 0) { // Sort array by bucket key arr = this._sort(keyObj, arr); // Split items into buckets bucketData = this.bucket(keyObj.___fdbKey, arr); bucketOrder = bucketData.order; buckets = bucketData.buckets; // Loop buckets and sort contents for (i = 0; i < bucketOrder.length; i++) { bucketKey = bucketOrder[i]; arrCopy = [].concat(keyArr); finalArr = finalArr.concat(this._bucketSort(arrCopy, buckets[bucketKey])); } return finalArr; } else { return this._sort(keyObj, arr); } };*/ /** * Takes an array of objects and returns a new object with the array items * split into buckets by the passed key. * @param {String} key The key to split the array into buckets by. * @param {Array} arr An array of objects. * @returns {Object} */ /*Collection.prototype.bucket = function (key, arr) { var i, oldField, field, fieldArr = [], buckets = {}; for (i = 0; i < arr.length; i++) { field = String(arr[i][key]); if (oldField !== field) { fieldArr.push(field); oldField = field; } buckets[field] = buckets[field] || []; buckets[field].push(arr[i]); } return { buckets: buckets, order: fieldArr }; };*/ /** * Sorts array by individual sort path. * @param {String} key The path to sort by. * @param {Array} arr The array of objects to sort. * @returns {Array|*} * @private */ Collection.prototype._sort = function (key, arr) { var self = this, sorterMethod, pathSolver = new Path(), dataPath = pathSolver.parse(key, true)[0]; pathSolver.path(dataPath.path); if (dataPath.value === 1) { // Sort ascending sorterMethod = function (a, b) { var valA = pathSolver.value(a)[0], valB = pathSolver.value(b)[0]; return self.sortAsc(valA, valB); }; } else if (dataPath.value === -1) { // Sort descending sorterMethod = function (a, b) { var valA = pathSolver.value(a)[0], valB = pathSolver.value(b)[0]; return self.sortDesc(valA, valB); }; } else { throw(this.logIdentifier() + ' $orderBy clause has invalid direction: ' + dataPath.value + ', accepted values are 1 or -1 for ascending or descending!'); } return arr.sort(sorterMethod); }; /** * Internal method that takes a search query and options and * returns an object containing details about the query which * can be used to optimise the search. * * @param {Object} query The search query to analyse. * @param {Object} options The query options object. * @param {Operation} op The instance of the Operation class that * this operation is using to track things like performance and steps * taken etc. * @returns {Object} * @private */ Collection.prototype._analyseQuery = function (query, options, op) { var analysis = { queriesOn: [{id: '$collection.' + this._name, type: 'colletion', key: this._name}], indexMatch: [], hasJoin: false, queriesJoin: false, joinQueries: {}, query: query, options: options }, joinSourceIndex, joinSourceKey, joinSourceType, joinSourceIdentifier, joinMatch, joinSources = [], joinSourceReferences = [], queryPath, index, indexMatchData, indexRef, indexRefName, indexLookup, pathSolver, queryKeyCount, pkQueryType, lookupResult, i; // Check if the query is a primary key lookup op.time('checkIndexes'); pathSolver = new Path(); queryKeyCount = pathSolver.parseArr(query, { ignore:/\$/, verbose: true }).length; if (queryKeyCount) { if (query[this._primaryKey] !== undefined) { // Check suitability of querying key value index pkQueryType = typeof query[this._primaryKey]; if (pkQueryType === 'string' || pkQueryType === 'number' || query[this._primaryKey] instanceof Array) { // Return item via primary key possible op.time('checkIndexMatch: Primary Key'); lookupResult = this._primaryIndex.lookup(query, options, op); analysis.indexMatch.push({ lookup: lookupResult, keyData: { matchedKeys: [this._primaryKey], totalKeyCount: queryKeyCount, score: 1 }, index: this._primaryIndex }); op.time('checkIndexMatch: Primary Key'); } } // Check if an index can speed up the query for (i in this._indexById) { if (this._indexById.hasOwnProperty(i)) { indexRef = this._indexById[i]; indexRefName = indexRef.name(); op.time('checkIndexMatch: ' + indexRefName); indexMatchData = indexRef.match(query, options); if (indexMatchData.score > 0) { // This index can be used, store it indexLookup = indexRef.lookup(query, options, op); analysis.indexMatch.push({ lookup: indexLookup, keyData: indexMatchData, index: indexRef }); } op.time('checkIndexMatch: ' + indexRefName); if (indexMatchData.score === queryKeyCount) { // Found an optimal index, do not check for any more break; } } } op.time('checkIndexes'); // Sort array descending on index key count (effectively a measure of relevance to the query) if (analysis.indexMatch.length > 1) { op.time('findOptimalIndex'); analysis.indexMatch.sort(function (a, b) { if (a.keyData.score > b.keyData.score) { // This index has a higher score than the other return -1; } if (a.keyData.score < b.keyData.score) { // This index has a lower score than the other return 1; } // The indexes have the same score but can still be compared by the number of records // they return from the query. The fewer records they return the better so order by // record count if (a.keyData.score === b.keyData.score) { return a.lookup.length - b.lookup.length; } }); op.time('findOptimalIndex'); } } // Check for join data if (options.$join) { analysis.hasJoin = true; // Loop all join operations for (joinSourceIndex = 0; joinSourceIndex < options.$join.length; joinSourceIndex++) { // Loop the join sources and keep a reference to them for (joinSourceKey in options.$join[joinSourceIndex]) { if (options.$join[joinSourceIndex].hasOwnProperty(joinSourceKey)) { joinMatch = options.$join[joinSourceIndex][joinSourceKey]; joinSourceType = joinMatch.$sourceType || 'collection'; joinSourceIdentifier = '$' + joinSourceType + '.' + joinSourceKey; joinSources.push({ id: joinSourceIdentifier, type: joinSourceType, key: joinSourceKey }); // Check if the join uses an $as operator if (options.$join[joinSourceIndex][joinSourceKey].$as !== undefined) { joinSourceReferences.push(options.$join[joinSourceIndex][joinSourceKey].$as); } else { joinSourceReferences.push(joinSourceKey); } } } } // Loop the join source references and determine if the query references // any of the sources that are used in the join. If there no queries against // joined sources the find method can use a code path optimised for this. // Queries against joined sources requires the joined sources to be filtered // first and then joined so requires a little more work. for (index = 0; index < joinSourceReferences.length; index++) { // Check if the query references any source data that the join will create queryPath = this._queryReferencesSource(query, joinSourceReferences[index], ''); if (queryPath) { analysis.joinQueries[joinSources[index].key] = queryPath; analysis.queriesJoin = true; } } analysis.joinsOn = joinSources; analysis.queriesOn = analysis.queriesOn.concat(joinSources); } return analysis; }; /** * Checks if the passed query references a source object (such * as a collection) by name. * @param {Object} query The query object to scan. * @param {String} sourceName The source name to scan for in the query. * @param {String=} path The path to scan from. * @returns {*} * @private */ Collection.prototype._queryReferencesSource = function (query, sourceName, path) { var i; for (i in query) { if (query.hasOwnProperty(i)) { // Check if this key is a reference match if (i === sourceName) { if (path) { path += '.'; } return path + i; } else { if (typeof(query[i]) === 'object') { // Recurse if (path) { path += '.'; } path += i; return this._queryReferencesSource(query[i], sourceName, path); } } } } return false; }; /** * Returns the number of documents currently in the collection. * @returns {Number} */ Collection.prototype.count = function (query, options) { if (!query) { return this._data.length; } else { // Run query and return count return this.find(query, options).length; } }; /** * Finds sub-documents from the collection's documents. * @param {Object} match The query object to use when matching * parent documents from which the sub-documents are queried. * @param {String} path The path string used to identify the * key in which sub-documents are stored in parent documents. * @param {Object=} subDocQuery The query to use when matching * which sub-documents to return. * @param {Object=} subDocOptions The options object to use * when querying for sub-documents. * @returns {*} */ Collection.prototype.findSub = function (match, path, subDocQuery, subDocOptions) { return this._findSub(this.find(match), path, subDocQuery, subDocOptions); }; Collection.prototype._findSub = function (docArr, path, subDocQuery, subDocOptions) { var pathHandler = new Path(path), docCount = docArr.length, docIndex, subDocArr, subDocCollection = new Collection('__FDB_temp_' + this.objectId()).db(this._db), subDocResults, resultObj = { parents: docCount, subDocTotal: 0, subDocs: [], pathFound: false, err: '' }; subDocOptions = subDocOptions || {}; for (docIndex = 0; docIndex < docCount; docIndex++) { subDocArr = pathHandler.value(docArr[docIndex])[0]; if (subDocArr) { subDocCollection.setData(subDocArr); subDocResults = subDocCollection.find(subDocQuery, subDocOptions); if (subDocOptions.returnFirst && subDocResults.length) { return subDocResults[0]; } if (subDocOptions.$split) { resultObj.subDocs.push(subDocResults); } else { resultObj.subDocs = resultObj.subDocs.concat(subDocResults); } resultObj.subDocTotal += subDocResults.length; resultObj.pathFound = true; } } // Drop the sub-document collection subDocCollection.drop(); if (!resultObj.pathFound) { resultObj.err = 'No objects found in the parent documents with a matching path of: ' + path; } // Check if the call should not return stats, if so return only subDocs array if (subDocOptions.$stats) { return resultObj; } else { return resultObj.subDocs; } }; /** * Finds the first sub-document from the collection's documents * that matches the subDocQuery parameter. * @param {Object} match The query object to use when matching * parent documents from which the sub-documents are queried. * @param {String} path The path string used to identify the * key in which sub-documents are stored in parent documents. * @param {Object=} subDocQuery The query to use when matching * which sub-documents to return. * @param {Object=} subDocOptions The options object to use * when querying for sub-documents. * @returns {Object} */ Collection.prototype.findSubOne = function (match, path, subDocQuery, subDocOptions) { return this.findSub(match, path, subDocQuery, subDocOptions)[0]; }; /** * Checks that the passed document will not violate any index rules if * inserted into the collection. * @param {Object} doc The document to check indexes against. * @returns {Boolean} Either false (no violation occurred) or true if * a violation was detected. */ Collection.prototype.insertIndexViolation = function (doc) { var indexViolated, arr = this._indexByName, arrIndex, arrItem; // Check the item's primary key is not already in use if (this._primaryIndex.get(doc[this._primaryKey])) { indexViolated = this._primaryIndex; } else { // Check violations of other indexes for (arrIndex in arr) { if (arr.hasOwnProperty(arrIndex)) { arrItem = arr[arrIndex]; if (arrItem.unique()) { if (arrItem.violation(doc)) { indexViolated = arrItem; break; } } } } } return indexViolated ? indexViolated.name() : false; }; /** * Creates an index on the specified keys. * @param {Object} keys The object containing keys to index. * @param {Object} options An options object. * @returns {*} */ Collection.prototype.ensureIndex = function (keys, options) { if (this.isDropped()) { throw(this.logIdentifier() + ' Cannot operate in a dropped state!'); } this._indexByName = this._indexByName || {}; this._indexById = this._indexById || {}; var index, time = { start: new Date().getTime() }; if (options) { if (options.type) { // Check if the specified type is available if (Shared.index[options.type]) { // We found the type, generate it index = new Shared.index[options.type](keys, options, this); } else { throw(this.logIdentifier() + ' Cannot create index of type "' + options.type + '", type not found in the index type register (Shared.index)'); } } else { // Create default index type index = new IndexHashMap(keys, options, this); } } else { // Default index = new IndexHashMap(keys, options, this); } // Check the index does not already exist if (this._indexByName[index.name()]) { // Index already exists return { err: 'Index with that name already exists' }; } /*if (this._indexById[index.id()]) { // Index already exists return { err: 'Index with those keys already exists' }; }*/ // Create the index index.rebuild(); // Add the index this._indexByName[index.name()] = index; this._indexById[index.id()] = index; time.end = new Date().getTime(); time.total = time.end - time.start; this._lastOp = { type: 'ensureIndex', stats: { time: time } }; return { index: index, id: index.id(), name: index.name(), state: index.state() }; }; /** * Gets an index by it's name. * @param {String} name The name of the index to retreive. * @returns {*} */ Collection.prototype.index = function (name) { if (this._indexByName) { return this._indexByName[name]; } }; /** * Gets the last reporting operation's details such as run time. * @returns {Object} */ Collection.prototype.lastOp = function () { return this._metrics.list(); }; /** * Generates a difference object that contains insert, update and remove arrays * representing the operations to execute to make this collection have the same * data as the one passed. * @param {Collection} collection The collection to diff against. * @returns {{}} */ Collection.prototype.diff = function (collection) { var diff = { insert: [], update: [], remove: [] }; var pk = this.primaryKey(), arr, arrIndex, arrItem, arrCount; // Check if the primary key index of each collection can be utilised if (pk !== collection.primaryKey()) { throw(this.logIdentifier() + ' Diffing requires that both collections have the same primary key!'); } // Use the collection primary key index to do the diff (super-fast) arr = collection._data; // Check if we have an array or another collection while (arr && !(arr instanceof Array)) { // We don't have an array, assign collection and get data collection = arr; arr = collection._data; } arrCount = arr.length; // Loop the collection's data array and check for matching items for (arrIndex = 0; arrIndex < arrCount; arrIndex++) { arrItem = arr[arrIndex]; // Check for a matching item in this collection if (this._primaryIndex.get(arrItem[pk])) { // Matching item exists, check if the data is the same if (this._primaryCrc.get(arrItem[pk]) !== collection._primaryCrc.get(arrItem[pk])) { // The documents exist in both collections but data differs, update required diff.update.push(arrItem); } } else { // The document is missing from this collection, insert required diff.insert.push(arrItem); } } // Now loop this collection's data and check for matching items arr = this._data; arrCount = arr.length; for (arrIndex = 0; arrIndex < arrCount; arrIndex++) { arrItem = arr[arrIndex]; if (!collection._primaryIndex.get(arrItem[pk])) { // The document does not exist in the other collection, remove required diff.remove.push(arrItem); } } return diff; }; Collection.prototype.collateAdd = new Overload('Collection.prototype.collateAdd', { /** * Adds a data source to collate data from and specifies the * key name to collate data to. * @func collateAdd * @memberof Collection * @param {Collection} collection The collection to collate data from. * @param {String=} keyName Optional name of the key to collate data to. * If none is provided the record CRUD is operated on the root collection * data. */ 'object, string': function (collection, keyName) { var self = this; self.collateAdd(collection, function (packet) { var obj1, obj2; switch (packet.type) { case 'insert': if (keyName) { obj1 = { $push: {} }; obj1.$push[keyName] = self.decouple(packet.data.dataSet); self.update({}, obj1); } else { self.insert(packet.data.dataSet); } break; case 'update': if (keyName) { obj1 = {}; obj2 = {}; obj1[keyName] = packet.data.query; obj2[keyName + '.$'] = packet.data.update; self.update(obj1, obj2); } else { self.update(packet.data.query, packet.data.update); } break; case 'remove': if (keyName) { obj1 = { $pull: {} }; obj1.$pull[keyName] = {}; obj1.$pull[keyName][self.primaryKey()] = packet.data.dataSet[0][collection.primaryKey()]; self.update({}, obj1); } else { self.remove(packet.data.dataSet); } break; default: } }); }, /** * Adds a data source to collate data from and specifies a process * method that will handle the collation functionality (for custom * collation). * @func collateAdd * @memberof Collection * @param {Collection} collection The collection to collate data from. * @param {Function} process The process method. */ 'object, function': function (collection, process) { if (typeof collection === 'string') { // The collection passed is a name, not a reference so get // the reference from the name collection = this._db.collection(collection, { autoCreate: false, throwError: false }); } if (collection) { this._collate = this._collate || {}; this._collate[collection.name()] = new ReactorIO(collection, this, process); return this; } else { throw('Cannot collate from a non-existent collection!'); } } }); Collection.prototype.collateRemove = function (collection) { if (typeof collection === 'object') { // We need to have the name of the collection to remove it collection = collection.name(); } if (collection) { // Drop the reactor IO chain node this._collate[collection].drop(); // Remove the collection data from the collate object delete this._collate[collection]; return this; } else { throw('No collection name passed to collateRemove() or collection not found!'); } }; /** * Creates a condition handler that will react to changes in data on the * collection. * @example Create a condition handler that reacts when data changes. * var coll = db.collection('test'), * condition = coll.when({_id: 'test1', val: 1}) * .then(function () { * console.log('Condition met!'); * }) * .else(function () { * console.log('Condition un-met'); * }); * * coll.insert({_id: 'test1', val: 1}); * * @see Condition * @param {Object} query The query that will trigger the condition's then() * callback. * @returns {Condition} */ Collection.prototype.when = function (query) { var queryId = this.objectId(); this._when = this._when || {}; this._when[queryId] = this._when[queryId] || new Condition(this, queryId, query); return this._when[queryId]; }; Db.prototype.collection = new Overload('Db.prototype.collection', { /** * Get a collection with no name (generates a random name). If the * collection does not already exist then one is created for that * name automatically. * @func collection * @memberof Db * @returns {Collection} */ '': function () { return this.$main.call(this, { name: this.objectId() }); }, /** * Get a collection by name. If the collection does not already exist * then one is created for that name automatically. * @func collection * @memberof Db * @param {Object} data An options object or a collection instance. * @returns {Collection} */ 'object': function (data) { // Handle being passed an instance if (data instanceof Collection) { if (data.state() !== 'droppped') { return data; } else { return this.$main.call(this, { name: data.name() }); } } return this.$main.call(this, data); }, /** * Get a collection by name. If the collection does not already exist * then one is created for that name automatically. * @func collection * @memberof Db * @param {String} collectionName The name of the collection. * @returns {Collection} */ 'string': function (collectionName) { return this.$main.call(this, { name: collectionName }); }, /** * Get a collection by name. If the collection does not already exist * then one is created for that name automatically. * @func collection * @memberof Db * @param {String} collectionName The name of the collection. * @param {String} primaryKey Optional primary key to specify the * primary key field on the collection objects. Defaults to "_id". * @returns {Collection} */ 'string, string': function (collectionName, primaryKey) { return this.$main.call(this, { name: collectionName, primaryKey: primaryKey }); }, /** * Get a collection by name. If the collection does not already exist * then one is created for that name automatically. * @func collection * @memberof Db * @param {String} collectionName The name of the collection. * @param {Object} options An options object. * @returns {Collection} */ 'string, object': function (collectionName, options) { options.name = collectionName; return this.$main.call(this, options); }, /** * Get a collection by name. If the collection does not already exist * then one is created for that name automatically. * @func collection * @memberof Db * @param {String} collectionName The name of the collection. * @param {String} primaryKey Optional primary key to specify the * primary key field on the collection objects. Defaults to "_id". * @param {Object} options An options object. * @returns {Collection} */ 'string, string, object': function (collectionName, primaryKey, options) { options.name = collectionName; options.primaryKey = primaryKey; return this.$main.call(this, options); }, /** * The main handler method. This gets called by all the other * variants and handles the actual logic of the overloaded method. * @func collection * @memberof Db * @param {Object} options An options object. * @returns {*} */ '$main': function (options) { var self = this, name = options.name; if (name) { if (this._collection[name]) { return this._collection[name]; } else { if (options && options.autoCreate === false) { if (options && options.throwError !== false) { throw(this.logIdentifier() + ' Cannot get collection ' + name + ' because it does not exist and auto-create has been disabled!'); } return undefined; } if (this.debug()) { console.log(this.logIdentifier() + ' Creating collection ' + name); } } this._collection[name] = this._collection[name] || new Collection(name, options).db(this); this._collection[name].mongoEmulation(this.mongoEmulation()); if (options.primaryKey !== undefined) { this._collection[name].primaryKey(options.primaryKey); } if (options.capped !== undefined) { // Check we have a size if (options.size !== undefined) { this._collection[name].capped(options.capped); this._collection[name].cappedSize(options.size); } else { throw(this.logIdentifier() + ' Cannot create a capped collection without specifying a size!'); } } // Listen for events on this collection so we can fire global events // on the database in response to it self._collection[name].on('change', function () { self.emit('change', self._collection[name], 'collection', name); }); self.emit('create', self._collection[name], 'collection', name); return this._collection[name]; } else { if (!options || (options && options.throwError !== false)) { throw(this.logIdentifier() + ' Cannot get collection with undefined name!'); } } } }); /** * Determine if a collection with the passed name already exists. * @memberof Db * @param {String} viewName The name of the collection to check for. * @returns {boolean} */ Db.prototype.collectionExists = function (viewName) { return Boolean(this._collection[viewName]); }; /** * Returns an array of collections the DB currently has. * @memberof Db * @param {String|RegExp=} search The optional search string or * regular expression to use to match collection names against. * @returns {Array} An array of objects containing details of each * collection the database is currently managing. */ Db.prototype.collections = function (search) { var arr = [], collections = this._collection, collection, i; if (search) { if (!(search instanceof RegExp)) { // Turn the search into a regular expression search = new RegExp(search); } } for (i in collections) { if (collections.hasOwnProperty(i)) { collection = collections[i]; if (search) { if (search.exec(i)) { arr.push({ name: i, count: collection.count(), linked: collection.isLinked !== undefined ? collection.isLinked() : false }); } } else { arr.push({ name: i, count: collection.count(), linked: collection.isLinked !== undefined ? collection.isLinked() : false }); } } } arr.sort(function (a, b) { return a.name.localeCompare(b.name); }); return arr; }; Shared.finishModule('Collection'); module.exports = Collection; },{"./Condition":7,"./Index2d":11,"./IndexBinaryTree":12,"./IndexHashMap":13,"./KeyValueStore":14,"./Metrics":15,"./Overload":27,"./Path":28,"./ReactorIO":32,"./Shared":34}],6:[function(_dereq_,module,exports){ "use strict"; // Import external names locally var Shared, Db, DbInit, Collection; Shared = _dereq_('./Shared'); /** * Creates a new collection group. Collection groups allow single operations to be * propagated to multiple collections at once. CRUD operations against a collection * group are in fed to the group's collections. Useful when separating out slightly * different data into multiple collections but querying as one collection. * @constructor */ var CollectionGroup = function () { this.init.apply(this, arguments); }; CollectionGroup.prototype.init = function (name) { var self = this; self._name = name; self._data = new Collection('__FDB__cg_data_' + self._name); self._collections = []; self._view = []; }; Shared.addModule('CollectionGroup', CollectionGroup); Shared.mixin(CollectionGroup.prototype, 'Mixin.Common'); Shared.mixin(CollectionGroup.prototype, 'Mixin.ChainReactor'); Shared.mixin(CollectionGroup.prototype, 'Mixin.Constants'); Shared.mixin(CollectionGroup.prototype, 'Mixin.Triggers'); Shared.mixin(CollectionGroup.prototype, 'Mixin.Tags'); Shared.mixin(CollectionGroup.prototype, 'Mixin.Events'); Collection = _dereq_('./Collection'); Db = Shared.modules.Db; DbInit = Shared.modules.Db.prototype.init; CollectionGroup.prototype.on = function () { this._data.on.apply(this._data, arguments); }; CollectionGroup.prototype.off = function () { this._data.off.apply(this._data, arguments); }; CollectionGroup.prototype.emit = function () { this._data.emit.apply(this._data, arguments); }; /** * Gets / sets the primary key for this collection group. * @param {String=} keyName The name of the primary key. * @returns {*} */ CollectionGroup.prototype.primaryKey = function (keyName) { if (keyName !== undefined) { this._primaryKey = keyName; return this; } return this._primaryKey; }; /** * Gets / sets the current state. * @param {String=} val The name of the state to set. * @returns {*} */ Shared.synthesize(CollectionGroup.prototype, 'state'); /** * Gets / sets the db instance the collection group belongs to. * @param {Db=} db The db instance. * @returns {*} */ Shared.synthesize(CollectionGroup.prototype, 'db'); /** * Gets / sets the instance name. * @param {String=} name The new name to set. * @returns {*} */ Shared.synthesize(CollectionGroup.prototype, 'name'); CollectionGroup.prototype.addCollection = function (collection) { if (collection) { if (this._collections.indexOf(collection) === -1) { //var self = this; // Check for compatible primary keys if (this._collections.length) { if (this._primaryKey !== collection.primaryKey()) { throw(this.logIdentifier() + ' All collections in a collection group must have the same primary key!'); } } else { // Set the primary key to the first collection added this.primaryKey(collection.primaryKey()); } // Add the collection this._collections.push(collection); collection._groups = collection._groups || []; collection._groups.push(this); collection.chain(this); // Hook the collection's drop event to destroy group data collection.on('drop', function () { // Remove collection from any group associations if (collection._groups && collection._groups.length) { var groupArr = [], i; // Copy the group array because if we call removeCollection on a group // it will alter the groups array of this collection mid-loop! for (i = 0; i < collection._groups.length; i++) { groupArr.push(collection._groups[i]); } // Loop any groups we are part of and remove ourselves from them for (i = 0; i < groupArr.length; i++) { collection._groups[i].removeCollection(collection); } } delete collection._groups; }); // Add collection's data this._data.insert(collection.find()); } } return this; }; CollectionGroup.prototype.removeCollection = function (collection) { if (collection) { var collectionIndex = this._collections.indexOf(collection), groupIndex; if (collectionIndex !== -1) { collection.unChain(this); this._collections.splice(collectionIndex, 1); collection._groups = collection._groups || []; groupIndex = collection._groups.indexOf(this); if (groupIndex !== -1) { collection._groups.splice(groupIndex, 1); } collection.off('drop'); } if (this._collections.length === 0) { // Wipe the primary key delete this._primaryKey; } } return this; }; CollectionGroup.prototype._chainHandler = function (chainPacket) { //sender = chainPacket.sender; switch (chainPacket.type) { case 'setData': // Decouple the data to ensure we are working with our own copy chainPacket.data.dataSet = this.decouple(chainPacket.data.dataSet); // Remove old data this._data.remove(chainPacket.data.oldData); // Add new data this._data.insert(chainPacket.data.dataSet); break; case 'insert': // Decouple the data to ensure we are working with our own copy chainPacket.data.dataSet = this.decouple(chainPacket.data.dataSet); // Add new data this._data.insert(chainPacket.data.dataSet); break; case 'update': // Update data this._data.update(chainPacket.data.query, chainPacket.data.update, chainPacket.options); break; case 'remove': this._data.remove(chainPacket.data.query, chainPacket.options); break; default: break; } }; CollectionGroup.prototype.insert = function () { this._collectionsRun('insert', arguments); }; CollectionGroup.prototype.update = function () { this._collectionsRun('update', arguments); }; CollectionGroup.prototype.updateById = function () { this._collectionsRun('updateById', arguments); }; CollectionGroup.prototype.remove = function () { this._collectionsRun('remove', arguments); }; CollectionGroup.prototype._collectionsRun = function (type, args) { for (var i = 0; i < this._collections.length; i++) { this._collections[i][type].apply(this._collections[i], args); } }; CollectionGroup.prototype.find = function (query, options) { return this._data.find(query, options); }; /** * Helper method that removes a document that matches the given id. * @param {String} id The id of the document to remove. */ CollectionGroup.prototype.removeById = function (id) { // Loop the collections in this group and apply the remove for (var i = 0; i < this._collections.length; i++) { this._collections[i].removeById(id); } }; /** * Uses the passed query to generate a new collection with results * matching the query parameters. * * @param query * @param options * @returns {*} */ CollectionGroup.prototype.subset = function (query, options) { var result = this.find(query, options); return new Collection() .subsetOf(this) .primaryKey(this._primaryKey) .setData(result); }; /** * Drops a collection group from the database. * @returns {boolean} True on success, false on failure. */ CollectionGroup.prototype.drop = function (callback) { if (!this.isDropped()) { var i, collArr, viewArr; if (this._debug) { console.log(this.logIdentifier() + ' Dropping'); } this._state = 'dropped'; if (this._collections && this._collections.length) { collArr = [].concat(this._collections); for (i = 0; i < collArr.length; i++) { this.removeCollection(collArr[i]); } } if (this._view && this._view.length) { viewArr = [].concat(this._view); for (i = 0; i < viewArr.length; i++) { this._removeView(viewArr[i]); } } this.emit('drop', this); delete this._listeners; if (callback) { callback(false, true); } } return true; }; // Extend DB to include collection groups Db.prototype.init = function () { this._collectionGroup = {}; DbInit.apply(this, arguments); }; /** * Creates a new collectionGroup instance or returns an existing * instance if one already exists with the passed name. * @func collectionGroup * @memberOf Db * @param {String} name The name of the instance. * @returns {*} */ Db.prototype.collectionGroup = function (name) { var self = this; if (name) { // Handle being passed an instance if (name instanceof CollectionGroup) { return name; } if (this._collectionGroup && this._collectionGroup[name]) { return this._collectionGroup[name]; } this._collectionGroup[name] = new CollectionGroup(name).db(this); self.emit('create', self._collectionGroup[name], 'collectionGroup', name); return this._collectionGroup[name]; } else { // Return an object of collection data return this._collectionGroup; } }; /** * Returns an array of collection groups the DB currently has. * @returns {Array} An array of objects containing details of each collection group * the database is currently managing. */ Db.prototype.collectionGroups = function () { var arr = [], i; for (i in this._collectionGroup) { if (this._collectionGroup.hasOwnProperty(i)) { arr.push({ name: i }); } } return arr; }; module.exports = CollectionGroup; },{"./Collection":5,"./Shared":34}],7:[function(_dereq_,module,exports){ "use strict"; /** * The condition class monitors a data source and updates it's internal * state depending on clauses that it has been given. When all clauses * are satisfied the then() callback is fired. If conditions were met * but data changed that made them un-met, the else() callback is fired. */ var //Overload = require('./Overload'), Shared, Condition; Shared = _dereq_('./Shared'); /** * Create a constructor method that calls the instance's init method. * This allows the constructor to be overridden by other modules because * they can override the init method with their own. */ Condition = function () { this.init.apply(this, arguments); }; Condition.prototype.init = function (dataSource, id, clause) { this._dataSource = dataSource; this._id = id; this._query = [clause]; this._started = false; this._state = [false]; this._satisfied = false; // Set this to true by default for faster performance this.earlyExit(true); }; // Tell ForerunnerDB about our new module Shared.addModule('Condition', Condition); // Mixin some commonly used methods Shared.mixin(Condition.prototype, 'Mixin.Common'); Shared.mixin(Condition.prototype, 'Mixin.ChainReactor'); Shared.synthesize(Condition.prototype, 'id'); Shared.synthesize(Condition.prototype, 'then'); Shared.synthesize(Condition.prototype, 'else'); Shared.synthesize(Condition.prototype, 'earlyExit'); Shared.synthesize(Condition.prototype, 'debug'); /** * Adds a new clause to the condition. * @param {Object} clause The query clause to add to the condition. * @returns {Condition} */ Condition.prototype.and = function (clause) { this._query.push(clause); this._state.push(false); return this; }; /** * Starts the condition so that changes to data will call callback * methods according to clauses being met. * @param {*} initialState Initial state of condition. * @returns {Condition} */ Condition.prototype.start = function (initialState) { if (!this._started) { var self = this; if (arguments.length !== 0) { this._satisfied = initialState; } // Resolve the current state this._updateStates(); self._onChange = function () { self._updateStates(); }; // Create a chain reactor link to the data source so we start receiving CRUD ops from it this._dataSource.on('change', self._onChange); this._started = true; } return this; }; /** * Updates the internal status of all the clauses against the underlying * data source. * @private */ Condition.prototype._updateStates = function () { var satisfied = true, i; for (i = 0; i < this._query.length; i++) { this._state[i] = this._dataSource.count(this._query[i]) > 0; if (this._debug) { console.log(this.logIdentifier() + ' Evaluating', this._query[i], '=', this._query[i]); } if (!this._state[i]) { satisfied = false; // Early exit since we have found a state that is not true if (this._earlyExit) { break; } } } if (this._satisfied !== satisfied) { // Our state has changed, fire the relevant operation if (satisfied) { // Fire the "then" operation if (this._then) { this._then(); } } else { // Fire the "else" operation if (this._else) { this._else(); } } this._satisfied = satisfied; } }; /** * Stops the condition so that callbacks will no longer fire. * @returns {Condition} */ Condition.prototype.stop = function () { if (this._started) { this._dataSource.off('change', this._onChange); delete this._onChange; this._started = false; } return this; }; /** * Drops the condition and removes it from memory. * @returns {Condition} */ Condition.prototype.drop = function () { this.stop(); delete this._dataSource.when[this._id]; return this; }; // Tell ForerunnerDB that our module has finished loading Shared.finishModule('Condition'); module.exports = Condition; },{"./Shared":34}],8:[function(_dereq_,module,exports){ /* License Copyright (c) 2015 Irrelon Software Limited http://www.irrelon.com http://www.forerunnerdb.com Please visit the license page to see latest license information: http://www.forerunnerdb.com/licensing.html */ "use strict"; var Shared, Db, Metrics, Overload, _instances = []; Shared = _dereq_('./Shared'); Overload = _dereq_('./Overload'); /** * Creates a new ForerunnerDB instance. Core instances handle the lifecycle of * multiple database instances. * @constructor */ var Core = function (val) { this.init.apply(this, arguments); }; Core.prototype.init = function (name) { this._db = {}; this._debug = {}; this._name = name || 'ForerunnerDB'; _instances.push(this); }; /** * Returns the number of instantiated ForerunnerDB objects. * @returns {Number} The number of instantiated instances. */ Core.prototype.instantiatedCount = function () { return _instances.length; }; /** * Get all instances as an array or a single ForerunnerDB instance * by it's array index. * @param {Number=} index Optional index of instance to get. * @returns {Array|Object} Array of instances or a single instance. */ Core.prototype.instances = function (index) { if (index !== undefined) { return _instances[index]; } return _instances; }; /** * Get all instances as an array of instance names or a single ForerunnerDB * instance by it's name. * @param {String=} name Optional name of instance to get. * @returns {Array|Object} Array of instance names or a single instance. */ Core.prototype.namedInstances = function (name) { var i, instArr; if (name !== undefined) { for (i = 0; i < _instances.length; i++) { if (_instances[i].name === name) { return _instances[i]; } } return undefined; } instArr = []; for (i = 0; i < _instances.length; i++) { instArr.push(_instances[i].name); } return instArr; }; Core.prototype.moduleLoaded = new Overload({ /** * Checks if a module has been loaded into the database. * @func moduleLoaded * @memberof Core * @param {String} moduleName The name of the module to check for. * @returns {Boolean} True if the module is loaded, false if not. */ 'string': function (moduleName) { if (moduleName !== undefined) { moduleName = moduleName.replace(/ /g, ''); var modules = moduleName.split(','), index; for (index = 0; index < modules.length; index++) { if (!Shared.modules[modules[index]]) { return false; } } return true; } return false; }, /** * Checks if a module is loaded and if so calls the passed * callback method. * @func moduleLoaded * @memberof Core * @param {String} moduleName The name of the module to check for. * @param {Function} callback The callback method to call if module is loaded. */ 'string, function': function (moduleName, callback) { if (moduleName !== undefined) { moduleName = moduleName.replace(/ /g, ''); var modules = moduleName.split(','), index; for (index = 0; index < modules.length; index++) { if (!Shared.modules[modules[index]]) { return false; } } if (callback) { callback(); } } }, /** * Checks if an array of named modules are loaded and if so * calls the passed callback method. * @func moduleLoaded * @memberof Core * @param {Array} moduleName The array of module names to check for. * @param {Function} callback The callback method to call if modules are loaded. */ 'array, function': function (moduleNameArr, callback) { var moduleName, i; for (i = 0; i < moduleNameArr.length; i++) { moduleName = moduleNameArr[i]; if (moduleName !== undefined) { moduleName = moduleName.replace(/ /g, ''); var modules = moduleName.split(','), index; for (index = 0; index < modules.length; index++) { if (!Shared.modules[modules[index]]) { return false; } } } } if (callback) { callback(); } }, /** * Checks if a module is loaded and if so calls the passed * success method, otherwise calls the failure method. * @func moduleLoaded * @memberof Core * @param {String} moduleName The name of the module to check for. * @param {Function} success The callback method to call if module is loaded. * @param {Function} failure The callback method to call if module not loaded. */ 'string, function, function': function (moduleName, success, failure) { if (moduleName !== undefined) { moduleName = moduleName.replace(/ /g, ''); var modules = moduleName.split(','), index; for (index = 0; index < modules.length; index++) { if (!Shared.modules[modules[index]]) { failure(); return false; } } success(); } } }); /** * Checks version against the string passed and if it matches (or partially matches) * then the callback is called. * @param {String} val The version to check against. * @param {Function} callback The callback to call if match is true. * @returns {Boolean} */ Core.prototype.version = function (val, callback) { if (val !== undefined) { if (Shared.version.indexOf(val) === 0) { if (callback) { callback(); } return true; } return false; } return Shared.version; }; // Expose moduleLoaded() method to non-instantiated object ForerunnerDB Core.moduleLoaded = Core.prototype.moduleLoaded; // Expose version() method to non-instantiated object ForerunnerDB Core.version = Core.prototype.version; // Expose instances() method to non-instantiated object ForerunnerDB Core.instances = Core.prototype.instances; // Expose instantiatedCount() method to non-instantiated object ForerunnerDB Core.instantiatedCount = Core.prototype.instantiatedCount; // Provide public access to the Shared object Core.shared = Shared; Core.prototype.shared = Shared; Shared.addModule('Core', Core); Shared.mixin(Core.prototype, 'Mixin.Common'); Shared.mixin(Core.prototype, 'Mixin.Constants'); Db = _dereq_('./Db.js'); Metrics = _dereq_('./Metrics.js'); /** * Gets / sets the name of the instance. This is primarily used for * name-spacing persistent storage. * @param {String=} val The name of the instance to set. * @returns {*} */ Shared.synthesize(Core.prototype, 'name'); /** * Gets / sets mongodb emulation mode. * @param {Boolean=} val True to enable, false to disable. * @returns {*} */ Shared.synthesize(Core.prototype, 'mongoEmulation'); // Set a flag to determine environment Core.prototype._isServer = false; /** * Checks if the database is running on a client (browser) or * a server (node.js). * @returns {Boolean} Returns true if running on a browser. */ Core.prototype.isClient = function () { return !this._isServer; }; /** * Checks if the database is running on a client (browser) or * a server (node.js). * @returns {Boolean} Returns true if running on a server. */ Core.prototype.isServer = function () { return this._isServer; }; /** * Added to provide an error message for users who have not seen * the new instantiation breaking change warning and try to get * a collection directly from the core instance. */ Core.prototype.collection = function () { throw("ForerunnerDB's instantiation has changed since version 1.3.36 to support multiple database instances. Please see the readme.md file for the minor change you have to make to get your project back up and running, or see the issue related to this change at https://github.com/Irrelon/ForerunnerDB/issues/44"); }; module.exports = Core; },{"./Db.js":9,"./Metrics.js":15,"./Overload":27,"./Shared":34}],9:[function(_dereq_,module,exports){ "use strict"; var Shared, Core, Collection, Metrics, Checksum, Overload; Shared = _dereq_('./Shared'); Overload = _dereq_('./Overload'); /** * Creates a new ForerunnerDB database instance. * @constructor */ var Db = function (name, core) { this.init.apply(this, arguments); }; Db.prototype.init = function (name, core) { this.core(core); this._primaryKey = '_id'; this._name = name; this._collection = {}; this._debug = {}; }; Shared.addModule('Db', Db); Db.prototype.moduleLoaded = new Overload({ /** * Checks if a module has been loaded into the database. * @func moduleLoaded * @memberof Db * @param {String} moduleName The name of the module to check for. * @returns {Boolean} True if the module is loaded, false if not. */ 'string': function (moduleName) { if (moduleName !== undefined) { moduleName = moduleName.replace(/ /g, ''); var modules = moduleName.split(','), index; for (index = 0; index < modules.length; index++) { if (!Shared.modules[modules[index]]) { return false; } } return true; } return false; }, /** * Checks if a module is loaded and if so calls the passed * callback method. * @func moduleLoaded * @memberof Db * @param {String} moduleName The name of the module to check for. * @param {Function} callback The callback method to call if module is loaded. */ 'string, function': function (moduleName, callback) { if (moduleName !== undefined) { moduleName = moduleName.replace(/ /g, ''); var modules = moduleName.split(','), index; for (index = 0; index < modules.length; index++) { if (!Shared.modules[modules[index]]) { return false; } } if (callback) { callback(); } } }, /** * Checks if a module is loaded and if so calls the passed * success method, otherwise calls the failure method. * @func moduleLoaded * @memberof Db * @param {String} moduleName The name of the module to check for. * @param {Function} success The callback method to call if module is loaded. * @param {Function} failure The callback method to call if module not loaded. */ 'string, function, function': function (moduleName, success, failure) { if (moduleName !== undefined) { moduleName = moduleName.replace(/ /g, ''); var modules = moduleName.split(','), index; for (index = 0; index < modules.length; index++) { if (!Shared.modules[modules[index]]) { failure(); return false; } } success(); } } }); /** * Checks version against the string passed and if it matches (or partially matches) * then the callback is called. * @param {String} val The version to check against. * @param {Function} callback The callback to call if match is true. * @returns {Boolean} */ Db.prototype.version = function (val, callback) { if (val !== undefined) { if (Shared.version.indexOf(val) === 0) { if (callback) { callback(); } return true; } return false; } return Shared.version; }; // Expose moduleLoaded method to non-instantiated object ForerunnerDB Db.moduleLoaded = Db.prototype.moduleLoaded; // Expose version method to non-instantiated object ForerunnerDB Db.version = Db.prototype.version; // Provide public access to the Shared object Db.shared = Shared; Db.prototype.shared = Shared; Shared.addModule('Db', Db); Shared.mixin(Db.prototype, 'Mixin.Common'); Shared.mixin(Db.prototype, 'Mixin.ChainReactor'); Shared.mixin(Db.prototype, 'Mixin.Constants'); Shared.mixin(Db.prototype, 'Mixin.Tags'); Core = Shared.modules.Core; Collection = _dereq_('./Collection.js'); Metrics = _dereq_('./Metrics.js'); Checksum = _dereq_('./Checksum.js'); Db.prototype._isServer = false; /** * Gets / sets the core object this database belongs to. */ Shared.synthesize(Db.prototype, 'core'); /** * Gets / sets the default primary key for new collections. * @param {String=} val The name of the primary key to set. * @returns {*} */ Shared.synthesize(Db.prototype, 'primaryKey'); /** * Gets / sets the current state. * @param {String=} val The name of the state to set. * @returns {*} */ Shared.synthesize(Db.prototype, 'state'); /** * Gets / sets the name of the database. * @param {String=} val The name of the database to set. * @returns {*} */ Shared.synthesize(Db.prototype, 'name'); /** * Gets / sets mongodb emulation mode. * @param {Boolean=} val True to enable, false to disable. * @returns {*} */ Shared.synthesize(Db.prototype, 'mongoEmulation'); /** * Returns true if ForerunnerDB is running on a client browser. * @returns {boolean} */ Db.prototype.isClient = function () { return !this._isServer; }; /** * Returns true if ForerunnerDB is running on a server. * @returns {boolean} */ Db.prototype.isServer = function () { return this._isServer; }; /** * Returns a checksum of a string. * @param {String} string The string to checksum. * @return {String} The checksum generated. */ Db.prototype.Checksum = Checksum; /** * Checks if the database is running on a client (browser) or * a server (node.js). * @returns {Boolean} Returns true if running on a browser. */ Db.prototype.isClient = function () { return !this._isServer; }; /** * Checks if the database is running on a client (browser) or * a server (node.js). * @returns {Boolean} Returns true if running on a server. */ Db.prototype.isServer = function () { return this._isServer; }; /** * Converts a normal javascript array of objects into a DB collection. * @param {Array} arr An array of objects. * @returns {Collection} A new collection instance with the data set to the * array passed. */ Db.prototype.arrayToCollection = function (arr) { return new Collection().setData(arr); }; /** * Registers an event listener against an event name. * @param {String} event The name of the event to listen for. * @param {Function} listener The listener method to call when * the event is fired. * @returns {*} */ Db.prototype.on = function(event, listener) { this._listeners = this._listeners || {}; this._listeners[event] = this._listeners[event] || []; this._listeners[event].push(listener); return this; }; /** * De-registers an event listener from an event name. * @param {String} event The name of the event to stop listening for. * @param {Function} listener The listener method passed to on() when * registering the event listener. * @returns {*} */ Db.prototype.off = function(event, listener) { if (event in this._listeners) { var arr = this._listeners[event], index = arr.indexOf(listener); if (index > -1) { arr.splice(index, 1); } } return this; }; /** * Emits an event by name with the given data. * @param {String} event The name of the event to emit. * @param {*=} data The data to emit with the event. * @returns {*} */ Db.prototype.emit = function(event, data) { this._listeners = this._listeners || {}; if (event in this._listeners) { var arr = this._listeners[event], arrCount = arr.length, arrIndex; for (arrIndex = 0; arrIndex < arrCount; arrIndex++) { arr[arrIndex].apply(this, Array.prototype.slice.call(arguments, 1)); } } return this; }; Db.prototype.peek = function (search) { var i, coll, arr = [], typeOfSearch = typeof search; // Loop collections for (i in this._collection) { if (this._collection.hasOwnProperty(i)) { coll = this._collection[i]; if (typeOfSearch === 'string') { arr = arr.concat(coll.peek(search)); } else { arr = arr.concat(coll.find(search)); } } } return arr; }; /** * Find all documents across all collections in the database that match the passed * string or search object. * @param search String or search object. * @returns {Array} */ Db.prototype.peek = function (search) { var i, coll, arr = [], typeOfSearch = typeof search; // Loop collections for (i in this._collection) { if (this._collection.hasOwnProperty(i)) { coll = this._collection[i]; if (typeOfSearch === 'string') { arr = arr.concat(coll.peek(search)); } else { arr = arr.concat(coll.find(search)); } } } return arr; }; /** * Find all documents across all collections in the database that match the passed * string or search object and return them in an object where each key is the name * of the collection that the document was matched in. * @param search String or search object. * @returns {object} */ Db.prototype.peekCat = function (search) { var i, coll, cat = {}, arr, typeOfSearch = typeof search; // Loop collections for (i in this._collection) { if (this._collection.hasOwnProperty(i)) { coll = this._collection[i]; if (typeOfSearch === 'string') { arr = coll.peek(search); if (arr && arr.length) { cat[coll.name()] = arr; } } else { arr = coll.find(search); if (arr && arr.length) { cat[coll.name()] = arr; } } } } return cat; }; Db.prototype.drop = new Overload({ /** * Drops the database. * @func drop * @memberof Db */ '': function () { if (!this.isDropped()) { var arr = this.collections(), arrCount = arr.length, arrIndex; this._state = 'dropped'; for (arrIndex = 0; arrIndex < arrCount; arrIndex++) { this.collection(arr[arrIndex].name).drop(); delete this._collection[arr[arrIndex].name]; } this.emit('drop', this); delete this._listeners; delete this._core._db[this._name]; } return true; }, /** * Drops the database with optional callback method. * @func drop * @memberof Db * @param {Function} callback Optional callback method. */ 'function': function (callback) { if (!this.isDropped()) { var arr = this.collections(), arrCount = arr.length, arrIndex, finishCount = 0, afterDrop = function () { finishCount++; if (finishCount === arrCount) { if (callback) { callback(); } } }; this._state = 'dropped'; for (arrIndex = 0; arrIndex < arrCount; arrIndex++) { this.collection(arr[arrIndex].name).drop(afterDrop); delete this._collection[arr[arrIndex].name]; } this.emit('drop', this); delete this._listeners; delete this._core._db[this._name]; } return true; }, /** * Drops the database with optional persistent storage drop. Persistent * storage is dropped by default if no preference is provided. * @func drop * @memberof Db * @param {Boolean} removePersist Drop persistent storage for this database. */ 'boolean': function (removePersist) { if (!this.isDropped()) { var arr = this.collections(), arrCount = arr.length, arrIndex; this._state = 'dropped'; for (arrIndex = 0; arrIndex < arrCount; arrIndex++) { this.collection(arr[arrIndex].name).drop(removePersist); delete this._collection[arr[arrIndex].name]; } this.emit('drop', this); delete this._listeners; delete this._core._db[this._name]; } return true; }, /** * Drops the database and optionally controls dropping persistent storage * and callback method. * @func drop * @memberof Db * @param {Boolean} removePersist Drop persistent storage for this database. * @param {Function} callback Optional callback method. */ 'boolean, function': function (removePersist, callback) { if (!this.isDropped()) { var arr = this.collections(), arrCount = arr.length, arrIndex, finishCount = 0, afterDrop = function () { finishCount++; if (finishCount === arrCount) { if (callback) { callback(); } } }; this._state = 'dropped'; for (arrIndex = 0; arrIndex < arrCount; arrIndex++) { this.collection(arr[arrIndex].name).drop(removePersist, afterDrop); delete this._collection[arr[arrIndex].name]; } this.emit('drop', this); delete this._listeners; delete this._core._db[this._name]; } return true; } }); /** * Gets a database instance by name. * @memberof Core * @param {String=} name Optional name of the database. If none is provided * a random name is assigned. * @returns {Db} */ Core.prototype.db = function (name) { // Handle being passed an instance if (name instanceof Db) { return name; } if (!name) { name = this.objectId(); } this._db[name] = this._db[name] || new Db(name, this); this._db[name].mongoEmulation(this.mongoEmulation()); return this._db[name]; }; /** * Returns an array of databases that ForerunnerDB currently has. * @memberof Core * @param {String|RegExp=} search The optional search string or regular expression to use * to match collection names against. * @returns {Array} An array of objects containing details of each database * that ForerunnerDB is currently managing and it's child entities. */ Core.prototype.databases = function (search) { var arr = [], tmpObj, addDb, i; if (search) { if (!(search instanceof RegExp)) { // Turn the search into a regular expression search = new RegExp(search); } } for (i in this._db) { if (this._db.hasOwnProperty(i)) { addDb = true; if (search) { if (!search.exec(i)) { addDb = false; } } if (addDb) { tmpObj = { name: i, children: [] }; if (this.shared.moduleExists('Collection')) { tmpObj.children.push({ module: 'collection', moduleName: 'Collections', count: this._db[i].collections().length }); } if (this.shared.moduleExists('CollectionGroup')) { tmpObj.children.push({ module: 'collectionGroup', moduleName: 'Collection Groups', count: this._db[i].collectionGroups().length }); } if (this.shared.moduleExists('Document')) { tmpObj.children.push({ module: 'document', moduleName: 'Documents', count: this._db[i].documents().length }); } if (this.shared.moduleExists('Grid')) { tmpObj.children.push({ module: 'grid', moduleName: 'Grids', count: this._db[i].grids().length }); } if (this.shared.moduleExists('Overview')) { tmpObj.children.push({ module: 'overview', moduleName: 'Overviews', count: this._db[i].overviews().length }); } if (this.shared.moduleExists('View')) { tmpObj.children.push({ module: 'view', moduleName: 'Views', count: this._db[i].views().length }); } arr.push(tmpObj); } } } arr.sort(function (a, b) { return a.name.localeCompare(b.name); }); return arr; }; Shared.finishModule('Db'); module.exports = Db; },{"./Checksum.js":4,"./Collection.js":5,"./Metrics.js":15,"./Overload":27,"./Shared":34}],10:[function(_dereq_,module,exports){ // geohash.js // Geohash library for Javascript // (c) 2008 David Troy // Distributed under the MIT License // Original at: https://github.com/davetroy/geohash-js // Modified by Irrelon Software Limited (http://www.irrelon.com) // to clean up and modularise the code using Node.js-style exports // and add a few helper methods. // @by Rob Evans - [email protected] "use strict"; /* Define some shared constants that will be used by all instances of the module. */ var bits, base32, neighbors, borders, PI180 = Math.PI / 180, PI180R = 180 / Math.PI, earthRadius = 6371; // mean radius of the earth bits = [16, 8, 4, 2, 1]; base32 = "0123456789bcdefghjkmnpqrstuvwxyz"; neighbors = { right: {even: "bc01fg45238967deuvhjyznpkmstqrwx"}, left: {even: "238967debc01fg45kmstqrwxuvhjyznp"}, top: {even: "p0r21436x8zb9dcf5h7kjnmqesgutwvy"}, bottom: {even: "14365h7k9dcfesgujnmqp0r2twvyx8zb"} }; borders = { right: {even: "bcfguvyz"}, left: {even: "0145hjnp"}, top: {even: "prxz"}, bottom: {even: "028b"} }; neighbors.bottom.odd = neighbors.left.even; neighbors.top.odd = neighbors.right.even; neighbors.left.odd = neighbors.bottom.even; neighbors.right.odd = neighbors.top.even; borders.bottom.odd = borders.left.even; borders.top.odd = borders.right.even; borders.left.odd = borders.bottom.even; borders.right.odd = borders.top.even; var GeoHash = function () {}; /** * Converts degrees to radians. * @param {Number} degrees * @return {Number} radians */ GeoHash.prototype.radians = function radians (degrees) { return degrees * PI180; }; /** * Converts radians to degrees. * @param {Number} radians * @return {Number} degrees */ GeoHash.prototype.degrees = function (radians) { return radians * PI180R; }; GeoHash.prototype.refineInterval = function (interval, cd, mask) { if (cd & mask) { //jshint ignore: line interval[0] = (interval[0] + interval[1]) / 2; } else { interval[1] = (interval[0] + interval[1]) / 2; } }; /** * Calculates all surrounding neighbours of a hash and returns them. * @param {String} centerHash The hash at the center of the grid. * @param options * @returns {*} */ GeoHash.prototype.calculateNeighbours = function (centerHash, options) { var response; if (!options || options.type === 'object') { response = { center: centerHash, left: this.calculateAdjacent(centerHash, 'left'), right: this.calculateAdjacent(centerHash, 'right'), top: this.calculateAdjacent(centerHash, 'top'), bottom: this.calculateAdjacent(centerHash, 'bottom') }; response.topLeft = this.calculateAdjacent(response.left, 'top'); response.topRight = this.calculateAdjacent(response.right, 'top'); response.bottomLeft = this.calculateAdjacent(response.left, 'bottom'); response.bottomRight = this.calculateAdjacent(response.right, 'bottom'); } else { response = []; response[4] = centerHash; response[3] = this.calculateAdjacent(centerHash, 'left'); response[5] = this.calculateAdjacent(centerHash, 'right'); response[1] = this.calculateAdjacent(centerHash, 'top'); response[7] = this.calculateAdjacent(centerHash, 'bottom'); response[0] = this.calculateAdjacent(response[3], 'top'); response[2] = this.calculateAdjacent(response[5], 'top'); response[6] = this.calculateAdjacent(response[3], 'bottom'); response[8] = this.calculateAdjacent(response[5], 'bottom'); } return response; }; /** * Calculates a new lat/lng by travelling from the center point in the * bearing specified for the distance specified. * @param {Array} centerPoint An array with latitude at index 0 and * longitude at index 1. * @param {Number} distanceKm The distance to travel in kilometers. * @param {Number} bearing The bearing to travel in degrees (zero is * north). * @returns {{lat: Number, lng: Number}} */ GeoHash.prototype.calculateLatLngByDistanceBearing = function (centerPoint, distanceKm, bearing) { var curLon = centerPoint[1], curLat = centerPoint[0], destLat = Math.asin(Math.sin(this.radians(curLat)) * Math.cos(distanceKm / earthRadius) + Math.cos(this.radians(curLat)) * Math.sin(distanceKm / earthRadius) * Math.cos(this.radians(bearing))), tmpLon = this.radians(curLon) + Math.atan2(Math.sin(this.radians(bearing)) * Math.sin(distanceKm / earthRadius) * Math.cos(this.radians(curLat)), Math.cos(distanceKm / earthRadius) - Math.sin(this.radians(curLat)) * Math.sin(destLat)), destLon = (tmpLon + 3 * Math.PI) % (2 * Math.PI) - Math.PI; // normalise to -180..+180º return { lat: this.degrees(destLat), lng: this.degrees(destLon) }; }; /** * Calculates the extents of a bounding box around the center point which * encompasses the radius in kilometers passed. * @param {Array} centerPoint An array with latitude at index 0 and * longitude at index 1. * @param radiusKm Radius in kilometers. * @returns {{lat: Array, lng: Array}} */ GeoHash.prototype.calculateExtentByRadius = function (centerPoint, radiusKm) { var maxWest, maxEast, maxNorth, maxSouth, lat = [], lng = []; maxNorth = this.calculateLatLngByDistanceBearing(centerPoint, radiusKm, 0); maxEast = this.calculateLatLngByDistanceBearing(centerPoint, radiusKm, 90); maxSouth = this.calculateLatLngByDistanceBearing(centerPoint, radiusKm, 180); maxWest = this.calculateLatLngByDistanceBearing(centerPoint, radiusKm, 270); lat[0] = maxNorth.lat; lat[1] = maxSouth.lat; lng[0] = maxWest.lng; lng[1] = maxEast.lng; return { lat: lat, lng: lng }; }; /** * Calculates all the geohashes that make up the bounding box that surrounds * the circle created from the center point and radius passed. * @param {Array} centerPoint An array with latitude at index 0 and * longitude at index 1. * @param {Number} radiusKm The radius in kilometers to encompass. * @param {Number} precision The number of characters to limit the returned * geohash strings to. * @returns {Array} The array of geohashes that encompass the bounding box. */ GeoHash.prototype.calculateHashArrayByRadius = function (centerPoint, radiusKm, precision) { var extent = this.calculateExtentByRadius(centerPoint, radiusKm), northWest = [extent.lat[0], extent.lng[0]], northEast = [extent.lat[0], extent.lng[1]], southWest = [extent.lat[1], extent.lng[0]], northWestHash = this.encode(northWest[0], northWest[1], precision), northEastHash = this.encode(northEast[0], northEast[1], precision), southWestHash = this.encode(southWest[0], southWest[1], precision), hash, widthCount = 0, heightCount = 0, widthIndex, heightIndex, hashArray = []; hash = northWestHash; hashArray.push(hash); // Walk from north west to north east until we find the north east geohash while (hash !== northEastHash) { hash = this.calculateAdjacent(hash, 'right'); widthCount++; hashArray.push(hash); } hash = northWestHash; // Walk from north west to south west until we find the south west geohash while (hash !== southWestHash) { hash = this.calculateAdjacent(hash, 'bottom'); heightCount++; } // We now know the width and height in hash boxes of the area, fill in the // rest of the hashes into the hashArray array for (widthIndex = 0; widthIndex <= widthCount; widthIndex++) { hash = hashArray[widthIndex]; for (heightIndex = 0; heightIndex < heightCount; heightIndex++) { hash = this.calculateAdjacent(hash, 'bottom'); hashArray.push(hash); } } return hashArray; }; /** * Calculates an adjacent hash to the hash passed, in the direction * specified. * @param {String} srcHash The hash to calculate adjacent to. * @param {String} dir Either "top", "left", "bottom" or "right". * @returns {String} The resulting geohash. */ GeoHash.prototype.calculateAdjacent = function (srcHash, dir) { srcHash = srcHash.toLowerCase(); var lastChr = srcHash.charAt(srcHash.length - 1), type = (srcHash.length % 2) ? 'odd' : 'even', base = srcHash.substring(0, srcHash.length - 1); if (borders[dir][type].indexOf(lastChr) !== -1) { base = this.calculateAdjacent(base, dir); } return base + base32[neighbors[dir][type].indexOf(lastChr)]; }; /** * Decodes a string geohash back to a longitude/latitude array. * The array contains three latitudes and three longitudes. The * first of each is the lower extent of the geohash bounding box, * the second is the upper extent and the third is the center * of the geohash bounding box. * @param {String} geohash The hash to decode. * @returns {Object} */ GeoHash.prototype.decode = function (geohash) { var isEven = 1, lat = [], lon = [], i, c, cd, j, mask, latErr, lonErr; lat[0] = -90.0; lat[1] = 90.0; lon[0] = -180.0; lon[1] = 180.0; latErr = 90.0; lonErr = 180.0; for (i = 0; i < geohash.length; i++) { c = geohash[i]; cd = base32.indexOf(c); for (j = 0; j < 5; j++) { mask = bits[j]; if (isEven) { lonErr /= 2; this.refineInterval(lon, cd, mask); } else { latErr /= 2; this.refineInterval(lat, cd, mask); } isEven = !isEven; } } lat[2] = (lat[0] + lat[1]) / 2; lon[2] = (lon[0] + lon[1]) / 2; return { lat: lat, lng: lon }; }; /** * Encodes a longitude/latitude to geohash string. * @param latitude * @param longitude * @param {Number=} precision Length of the geohash string. Defaults to 12. * @returns {String} */ GeoHash.prototype.encode = function (latitude, longitude, precision) { var isEven = 1, mid, lat = [], lon = [], bit = 0, ch = 0, geoHash = ""; if (!precision) { precision = 12; } lat[0] = -90.0; lat[1] = 90.0; lon[0] = -180.0; lon[1] = 180.0; while (geoHash.length < precision) { if (isEven) { mid = (lon[0] + lon[1]) / 2; if (longitude > mid) { ch |= bits[bit]; //jshint ignore: line lon[0] = mid; } else { lon[1] = mid; } } else { mid = (lat[0] + lat[1]) / 2; if (latitude > mid) { ch |= bits[bit]; //jshint ignore: line lat[0] = mid; } else { lat[1] = mid; } } isEven = !isEven; if (bit < 4) { bit++; } else { geoHash += base32[ch]; bit = 0; ch = 0; } } return geoHash; }; if (typeof module !== 'undefined') { module.exports = GeoHash; } },{}],11:[function(_dereq_,module,exports){ "use strict"; /* name(string) id(string) rebuild(null) state ?? needed? match(query, options) lookup(query, options) insert(doc) remove(doc) primaryKey(string) collection(collection) */ var Shared = _dereq_('./Shared'), Path = _dereq_('./Path'), BinaryTree = _dereq_('./BinaryTree'), GeoHash = _dereq_('./GeoHash'), sharedPathSolver = new Path(), sharedGeoHashSolver = new GeoHash(), // GeoHash Distances in Kilometers geoHashDistance = [ 5000, 1250, 156, 39.1, 4.89, 1.22, 0.153, 0.0382, 0.00477, 0.00119, 0.000149, 0.0000372 ]; /** * The index class used to instantiate 2d indexes that the database can * use to handle high-performance geospatial queries. * @constructor */ var Index2d = function () { this.init.apply(this, arguments); }; /** * Create the index. * @param {Object} keys The object with the keys that the user wishes the index * to operate on. * @param {Object} options Can be undefined, if passed is an object with arbitrary * options keys and values. * @param {Collection} collection The collection the index should be created for. */ Index2d.prototype.init = function (keys, options, collection) { this._btree = new BinaryTree(); this._btree.index(keys); this._size = 0; this._id = this._itemKeyHash(keys, keys); this._debug = options && options.debug ? options.debug : false; this.unique(options && options.unique ? options.unique : false); if (keys !== undefined) { this.keys(keys); } if (collection !== undefined) { this.collection(collection); this._btree.primaryKey(collection.primaryKey()); } this.name(options && options.name ? options.name : this._id); this._btree.debug(this._debug); }; Shared.addModule('Index2d', Index2d); Shared.mixin(Index2d.prototype, 'Mixin.Common'); Shared.mixin(Index2d.prototype, 'Mixin.ChainReactor'); Shared.mixin(Index2d.prototype, 'Mixin.Sorting'); Index2d.prototype.id = function () { return this._id; }; Index2d.prototype.state = function () { return this._state; }; Index2d.prototype.size = function () { return this._size; }; Shared.synthesize(Index2d.prototype, 'data'); Shared.synthesize(Index2d.prototype, 'name'); Shared.synthesize(Index2d.prototype, 'collection'); Shared.synthesize(Index2d.prototype, 'type'); Shared.synthesize(Index2d.prototype, 'unique'); Index2d.prototype.keys = function (val) { if (val !== undefined) { this._keys = val; // Count the keys this._keyCount = sharedPathSolver.parse(this._keys).length; return this; } return this._keys; }; Index2d.prototype.rebuild = function () { // Do we have a collection? if (this._collection) { // Get sorted data var collection = this._collection.subset({}, { $decouple: false, $orderBy: this._keys }), collectionData = collection.find(), dataIndex, dataCount = collectionData.length; // Clear the index data for the index this._btree.clear(); this._size = 0; if (this._unique) { this._uniqueLookup = {}; } // Loop the collection data for (dataIndex = 0; dataIndex < dataCount; dataIndex++) { this.insert(collectionData[dataIndex]); } } this._state = { name: this._name, keys: this._keys, indexSize: this._size, built: new Date(), updated: new Date(), ok: true }; }; Index2d.prototype.insert = function (dataItem, options) { var uniqueFlag = this._unique, uniqueHash; dataItem = this.decouple(dataItem); if (uniqueFlag) { uniqueHash = this._itemHash(dataItem, this._keys); this._uniqueLookup[uniqueHash] = dataItem; } // Convert 2d indexed values to geohashes var keys = this._btree.keys(), pathVal, geoHash, lng, lat, i; for (i = 0; i < keys.length; i++) { pathVal = sharedPathSolver.get(dataItem, keys[i].path); if (pathVal instanceof Array) { lng = pathVal[0]; lat = pathVal[1]; geoHash = sharedGeoHashSolver.encode(lng, lat); sharedPathSolver.set(dataItem, keys[i].path, geoHash); } } if (this._btree.insert(dataItem)) { this._size++; return true; } return false; }; Index2d.prototype.remove = function (dataItem, options) { var uniqueFlag = this._unique, uniqueHash; if (uniqueFlag) { uniqueHash = this._itemHash(dataItem, this._keys); delete this._uniqueLookup[uniqueHash]; } if (this._btree.remove(dataItem)) { this._size--; return true; } return false; }; Index2d.prototype.violation = function (dataItem) { // Generate item hash var uniqueHash = this._itemHash(dataItem, this._keys); // Check if the item breaks the unique constraint return Boolean(this._uniqueLookup[uniqueHash]); }; Index2d.prototype.hashViolation = function (uniqueHash) { // Check if the item breaks the unique constraint return Boolean(this._uniqueLookup[uniqueHash]); }; /** * Looks up records that match the passed query and options. * @param query The query to execute. * @param options A query options object. * @param {Operation=} op Optional operation instance that allows * us to provide operation diagnostics and analytics back to the * main calling instance as the process is running. * @returns {*} */ Index2d.prototype.lookup = function (query, options, op) { // Loop the indexed keys and determine if the query has any operators // that we want to handle differently from a standard lookup var keys = this._btree.keys(), pathStr, pathVal, results, i; for (i = 0; i < keys.length; i++) { pathStr = keys[i].path; pathVal = sharedPathSolver.get(query, pathStr); if (typeof pathVal === 'object') { if (pathVal.$near) { results = []; // Do a near point lookup results = results.concat(this.near(pathStr, pathVal.$near, options, op)); } if (pathVal.$geoWithin) { results = []; // Do a geoWithin shape lookup results = results.concat(this.geoWithin(pathStr, pathVal.$geoWithin, options, op)); } return results; } } return this._btree.lookup(query, options); }; Index2d.prototype.near = function (pathStr, query, options, op) { var self = this, neighbours, visitedCount, visitedNodes, visitedData, search, results, finalResults = [], precision, maxDistanceKm, distance, distCache, latLng, pk = this._collection.primaryKey(), i; // Calculate the required precision to encapsulate the distance // TODO: Instead of opting for the "one size larger" than the distance boxes, // TODO: we should calculate closest divisible box size as a multiple and then // TODO: scan neighbours until we have covered the area otherwise we risk // TODO: opening the results up to vastly more information as the box size // TODO: increases dramatically between the geohash precisions if (query.$distanceUnits === 'km') { maxDistanceKm = query.$maxDistance; for (i = 0; i < geoHashDistance.length; i++) { if (maxDistanceKm > geoHashDistance[i]) { precision = i + 1; break; } } } else if (query.$distanceUnits === 'miles') { maxDistanceKm = query.$maxDistance * 1.60934; for (i = 0; i < geoHashDistance.length; i++) { if (maxDistanceKm > geoHashDistance[i]) { precision = i + 1; break; } } } if (precision === 0) { precision = 1; } // Calculate 9 box geohashes if (op) { op.time('index2d.calculateHashArea'); } neighbours = sharedGeoHashSolver.calculateHashArrayByRadius(query.$point, maxDistanceKm, precision); if (op) { op.time('index2d.calculateHashArea'); } if (op) { op.data('index2d.near.precision', precision); op.data('index2d.near.hashArea', neighbours); op.data('index2d.near.maxDistanceKm', maxDistanceKm); op.data('index2d.near.centerPointCoords', [query.$point[0], query.$point[1]]); } // Lookup all matching co-ordinates from the btree results = []; visitedCount = 0; visitedData = {}; visitedNodes = []; if (op) { op.time('index2d.near.getDocsInsideHashArea'); } for (i = 0; i < neighbours.length; i++) { search = this._btree.startsWith(pathStr, neighbours[i]); visitedData[neighbours[i]] = search; visitedCount += search._visitedCount; visitedNodes = visitedNodes.concat(search._visitedNodes); results = results.concat(search); } if (op) { op.time('index2d.near.getDocsInsideHashArea'); op.data('index2d.near.startsWith', visitedData); op.data('index2d.near.visitedTreeNodes', visitedNodes); } // Work with original data if (op) { op.time('index2d.near.lookupDocsById'); } results = this._collection._primaryIndex.lookup(results); if (op) { op.time('index2d.near.lookupDocsById'); } if (query.$distanceField) { // Decouple the results before we modify them results = this.decouple(results); } if (results.length) { distance = {}; if (op) { op.time('index2d.near.calculateDistanceFromCenter'); } // Loop the results and calculate distance for (i = 0; i < results.length; i++) { latLng = sharedPathSolver.get(results[i], pathStr); distCache = distance[results[i][pk]] = this.distanceBetweenPoints(query.$point[0], query.$point[1], latLng[0], latLng[1]); if (distCache <= maxDistanceKm) { if (query.$distanceField) { // Options specify a field to add the distance data to // so add it now sharedPathSolver.set(results[i], query.$distanceField, query.$distanceUnits === 'km' ? distCache : Math.round(distCache * 0.621371)); } if (query.$geoHashField) { // Options specify a field to add the distance data to // so add it now sharedPathSolver.set(results[i], query.$geoHashField, sharedGeoHashSolver.encode(latLng[0], latLng[1], precision)); } // Add item as it is inside radius distance finalResults.push(results[i]); } } if (op) { op.time('index2d.near.calculateDistanceFromCenter'); } // Sort by distance from center if (op) { op.time('index2d.near.sortResultsByDistance'); } finalResults.sort(function (a, b) { return self.sortAsc(distance[a[pk]], distance[b[pk]]); }); if (op) { op.time('index2d.near.sortResultsByDistance'); } } // Return data return finalResults; }; Index2d.prototype.geoWithin = function (pathStr, query, options) { console.log('geoWithin() is currently a prototype method with no actual implementation... it just returns a blank array.'); return []; }; Index2d.prototype.distanceBetweenPoints = function (lat1, lng1, lat2, lng2) { var R = 6371; // kilometres var lat1Rad = this.toRadians(lat1); var lat2Rad = this.toRadians(lat2); var lat2MinusLat1Rad = this.toRadians(lat2-lat1); var lng2MinusLng1Rad = this.toRadians(lng2-lng1); var a = Math.sin(lat2MinusLat1Rad/2) * Math.sin(lat2MinusLat1Rad/2) + Math.cos(lat1Rad) * Math.cos(lat2Rad) * Math.sin(lng2MinusLng1Rad/2) * Math.sin(lng2MinusLng1Rad/2); var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a)); return R * c; }; Index2d.prototype.toRadians = function (degrees) { return degrees * 0.01747722222222; }; Index2d.prototype.match = function (query, options) { // TODO: work out how to represent that this is a better match if the query has $near than // TODO: a basic btree index which will not be able to resolve a $near operator return this._btree.match(query, options); }; Index2d.prototype._itemHash = function (item, keys) { var path = new Path(), pathData, hash = '', k; pathData = path.parse(keys); for (k = 0; k < pathData.length; k++) { if (hash) { hash += '_'; } hash += path.value(item, pathData[k].path).join(':'); } return hash; }; Index2d.prototype._itemKeyHash = function (item, keys) { var path = new Path(), pathData, hash = '', k; pathData = path.parse(keys); for (k = 0; k < pathData.length; k++) { if (hash) { hash += '_'; } hash += path.keyValue(item, pathData[k].path); } return hash; }; Index2d.prototype._itemHashArr = function (item, keys) { var path = new Path(), pathData, //hash = '', hashArr = [], valArr, i, k, j; pathData = path.parse(keys); for (k = 0; k < pathData.length; k++) { valArr = path.value(item, pathData[k].path); for (i = 0; i < valArr.length; i++) { if (k === 0) { // Setup the initial hash array hashArr.push(valArr[i]); } else { // Loop the hash array and concat the value to it for (j = 0; j < hashArr.length; j++) { hashArr[j] = hashArr[j] + '_' + valArr[i]; } } } } return hashArr; }; // Register this index on the shared object Shared.index['2d'] = Index2d; Shared.finishModule('Index2d'); module.exports = Index2d; },{"./BinaryTree":3,"./GeoHash":10,"./Path":28,"./Shared":34}],12:[function(_dereq_,module,exports){ "use strict"; /* name(string) id(string) rebuild(null) state ?? needed? match(query, options) lookup(query, options) insert(doc) remove(doc) primaryKey(string) collection(collection) */ var Shared = _dereq_('./Shared'), Path = _dereq_('./Path'), BinaryTree = _dereq_('./BinaryTree'); /** * The index class used to instantiate btree indexes that the database can * use to speed up queries on collections and views. * @constructor */ var IndexBinaryTree = function () { this.init.apply(this, arguments); }; IndexBinaryTree.prototype.init = function (keys, options, collection) { this._btree = new BinaryTree(); this._btree.index(keys); this._size = 0; this._id = this._itemKeyHash(keys, keys); this._debug = options && options.debug ? options.debug : false; this.unique(options && options.unique ? options.unique : false); if (keys !== undefined) { this.keys(keys); } if (collection !== undefined) { this.collection(collection); this._btree.primaryKey(collection.primaryKey()); } this.name(options && options.name ? options.name : this._id); this._btree.debug(this._debug); }; Shared.addModule('IndexBinaryTree', IndexBinaryTree); Shared.mixin(IndexBinaryTree.prototype, 'Mixin.ChainReactor'); Shared.mixin(IndexBinaryTree.prototype, 'Mixin.Sorting'); IndexBinaryTree.prototype.id = function () { return this._id; }; IndexBinaryTree.prototype.state = function () { return this._state; }; IndexBinaryTree.prototype.size = function () { return this._size; }; Shared.synthesize(IndexBinaryTree.prototype, 'data'); Shared.synthesize(IndexBinaryTree.prototype, 'name'); Shared.synthesize(IndexBinaryTree.prototype, 'collection'); Shared.synthesize(IndexBinaryTree.prototype, 'type'); Shared.synthesize(IndexBinaryTree.prototype, 'unique'); IndexBinaryTree.prototype.keys = function (val) { if (val !== undefined) { this._keys = val; // Count the keys this._keyCount = (new Path()).parse(this._keys).length; return this; } return this._keys; }; IndexBinaryTree.prototype.rebuild = function () { // Do we have a collection? if (this._collection) { // Get sorted data var collection = this._collection.subset({}, { $decouple: false, $orderBy: this._keys }), collectionData = collection.find(), dataIndex, dataCount = collectionData.length; // Clear the index data for the index this._btree.clear(); this._size = 0; if (this._unique) { this._uniqueLookup = {}; } // Loop the collection data for (dataIndex = 0; dataIndex < dataCount; dataIndex++) { this.insert(collectionData[dataIndex]); } } this._state = { name: this._name, keys: this._keys, indexSize: this._size, built: new Date(), updated: new Date(), ok: true }; }; IndexBinaryTree.prototype.insert = function (dataItem, options) { var uniqueFlag = this._unique, uniqueHash; if (uniqueFlag) { uniqueHash = this._itemHash(dataItem, this._keys); this._uniqueLookup[uniqueHash] = dataItem; } if (this._btree.insert(dataItem)) { this._size++; return true; } return false; }; IndexBinaryTree.prototype.remove = function (dataItem, options) { var uniqueFlag = this._unique, uniqueHash; if (uniqueFlag) { uniqueHash = this._itemHash(dataItem, this._keys); delete this._uniqueLookup[uniqueHash]; } if (this._btree.remove(dataItem)) { this._size--; return true; } return false; }; IndexBinaryTree.prototype.violation = function (dataItem) { // Generate item hash var uniqueHash = this._itemHash(dataItem, this._keys); // Check if the item breaks the unique constraint return Boolean(this._uniqueLookup[uniqueHash]); }; IndexBinaryTree.prototype.hashViolation = function (uniqueHash) { // Check if the item breaks the unique constraint return Boolean(this._uniqueLookup[uniqueHash]); }; IndexBinaryTree.prototype.lookup = function (query, options, op) { return this._btree.lookup(query, options, op); }; IndexBinaryTree.prototype.match = function (query, options) { return this._btree.match(query, options); }; IndexBinaryTree.prototype._itemHash = function (item, keys) { var path = new Path(), pathData, hash = '', k; pathData = path.parse(keys); for (k = 0; k < pathData.length; k++) { if (hash) { hash += '_'; } hash += path.value(item, pathData[k].path).join(':'); } return hash; }; IndexBinaryTree.prototype._itemKeyHash = function (item, keys) { var path = new Path(), pathData, hash = '', k; pathData = path.parse(keys); for (k = 0; k < pathData.length; k++) { if (hash) { hash += '_'; } hash += path.keyValue(item, pathData[k].path); } return hash; }; IndexBinaryTree.prototype._itemHashArr = function (item, keys) { var path = new Path(), pathData, //hash = '', hashArr = [], valArr, i, k, j; pathData = path.parse(keys); for (k = 0; k < pathData.length; k++) { valArr = path.value(item, pathData[k].path); for (i = 0; i < valArr.length; i++) { if (k === 0) { // Setup the initial hash array hashArr.push(valArr[i]); } else { // Loop the hash array and concat the value to it for (j = 0; j < hashArr.length; j++) { hashArr[j] = hashArr[j] + '_' + valArr[i]; } } } } return hashArr; }; // Register this index on the shared object Shared.index.btree = IndexBinaryTree; Shared.finishModule('IndexBinaryTree'); module.exports = IndexBinaryTree; },{"./BinaryTree":3,"./Path":28,"./Shared":34}],13:[function(_dereq_,module,exports){ "use strict"; var Shared = _dereq_('./Shared'), Path = _dereq_('./Path'); /** * The index class used to instantiate hash map indexes that the database can * use to speed up queries on collections and views. * @constructor */ var IndexHashMap = function () { this.init.apply(this, arguments); }; IndexHashMap.prototype.init = function (keys, options, collection) { this._crossRef = {}; this._size = 0; this._id = this._itemKeyHash(keys, keys); this.data({}); this.unique(options && options.unique ? options.unique : false); if (keys !== undefined) { this.keys(keys); } if (collection !== undefined) { this.collection(collection); } this.name(options && options.name ? options.name : this._id); }; Shared.addModule('IndexHashMap', IndexHashMap); Shared.mixin(IndexHashMap.prototype, 'Mixin.ChainReactor'); IndexHashMap.prototype.id = function () { return this._id; }; IndexHashMap.prototype.state = function () { return this._state; }; IndexHashMap.prototype.size = function () { return this._size; }; Shared.synthesize(IndexHashMap.prototype, 'data'); Shared.synthesize(IndexHashMap.prototype, 'name'); Shared.synthesize(IndexHashMap.prototype, 'collection'); Shared.synthesize(IndexHashMap.prototype, 'type'); Shared.synthesize(IndexHashMap.prototype, 'unique'); IndexHashMap.prototype.keys = function (val) { if (val !== undefined) { this._keys = val; // Count the keys this._keyCount = (new Path()).parse(this._keys).length; return this; } return this._keys; }; IndexHashMap.prototype.rebuild = function () { // Do we have a collection? if (this._collection) { // Get sorted data var collection = this._collection.subset({}, { $decouple: false, $orderBy: this._keys }), collectionData = collection.find(), dataIndex, dataCount = collectionData.length; // Clear the index data for the index this._data = {}; this._size = 0; if (this._unique) { this._uniqueLookup = {}; } // Loop the collection data for (dataIndex = 0; dataIndex < dataCount; dataIndex++) { this.insert(collectionData[dataIndex]); } } this._state = { name: this._name, keys: this._keys, indexSize: this._size, built: new Date(), updated: new Date(), ok: true }; }; IndexHashMap.prototype.insert = function (dataItem, options) { var uniqueFlag = this._unique, uniqueHash, itemHashArr, hashIndex; if (uniqueFlag) { uniqueHash = this._itemHash(dataItem, this._keys); this._uniqueLookup[uniqueHash] = dataItem; } // Generate item hash itemHashArr = this._itemHashArr(dataItem, this._keys); // Get the path search results and store them for (hashIndex = 0; hashIndex < itemHashArr.length; hashIndex++) { this.pushToPathValue(itemHashArr[hashIndex], dataItem); } }; IndexHashMap.prototype.update = function (dataItem, options) { // TODO: Write updates to work // 1: Get uniqueHash for the dataItem primary key value (may need to generate a store for this) // 2: Remove the uniqueHash as it currently stands // 3: Generate a new uniqueHash for dataItem // 4: Insert the new uniqueHash }; IndexHashMap.prototype.remove = function (dataItem, options) { var uniqueFlag = this._unique, uniqueHash, itemHashArr, hashIndex; if (uniqueFlag) { uniqueHash = this._itemHash(dataItem, this._keys); delete this._uniqueLookup[uniqueHash]; } // Generate item hash itemHashArr = this._itemHashArr(dataItem, this._keys); // Get the path search results and store them for (hashIndex = 0; hashIndex < itemHashArr.length; hashIndex++) { this.pullFromPathValue(itemHashArr[hashIndex], dataItem); } }; IndexHashMap.prototype.violation = function (dataItem) { // Generate item hash var uniqueHash = this._itemHash(dataItem, this._keys); // Check if the item breaks the unique constraint return Boolean(this._uniqueLookup[uniqueHash]); }; IndexHashMap.prototype.hashViolation = function (uniqueHash) { // Check if the item breaks the unique constraint return Boolean(this._uniqueLookup[uniqueHash]); }; IndexHashMap.prototype.pushToPathValue = function (hash, obj) { var pathValArr = this._data[hash] = this._data[hash] || []; // Make sure we have not already indexed this object at this path/value if (pathValArr.indexOf(obj) === -1) { // Index the object pathValArr.push(obj); // Record the reference to this object in our index size this._size++; // Cross-reference this association for later lookup this.pushToCrossRef(obj, pathValArr); } }; IndexHashMap.prototype.pullFromPathValue = function (hash, obj) { var pathValArr = this._data[hash], indexOfObject; // Make sure we have already indexed this object at this path/value indexOfObject = pathValArr.indexOf(obj); if (indexOfObject > -1) { // Un-index the object pathValArr.splice(indexOfObject, 1); // Record the reference to this object in our index size this._size--; // Remove object cross-reference this.pullFromCrossRef(obj, pathValArr); } // Check if we should remove the path value array if (!pathValArr.length) { // Remove the array delete this._data[hash]; } }; IndexHashMap.prototype.pull = function (obj) { // Get all places the object has been used and remove them var id = obj[this._collection.primaryKey()], crossRefArr = this._crossRef[id], arrIndex, arrCount = crossRefArr.length, arrItem; for (arrIndex = 0; arrIndex < arrCount; arrIndex++) { arrItem = crossRefArr[arrIndex]; // Remove item from this index lookup array this._pullFromArray(arrItem, obj); } // Record the reference to this object in our index size this._size--; // Now remove the cross-reference entry for this object delete this._crossRef[id]; }; IndexHashMap.prototype._pullFromArray = function (arr, obj) { var arrCount = arr.length; while (arrCount--) { if (arr[arrCount] === obj) { arr.splice(arrCount, 1); } } }; IndexHashMap.prototype.pushToCrossRef = function (obj, pathValArr) { var id = obj[this._collection.primaryKey()], crObj; this._crossRef[id] = this._crossRef[id] || []; // Check if the cross-reference to the pathVal array already exists crObj = this._crossRef[id]; if (crObj.indexOf(pathValArr) === -1) { // Add the cross-reference crObj.push(pathValArr); } }; IndexHashMap.prototype.pullFromCrossRef = function (obj, pathValArr) { var id = obj[this._collection.primaryKey()]; delete this._crossRef[id]; }; IndexHashMap.prototype.lookup = function (query) { return this._data[this._itemHash(query, this._keys)] || []; }; IndexHashMap.prototype.match = function (query, options) { // Check if the passed query has data in the keys our index // operates on and if so, is the query sort matching our order var pathSolver = new Path(); var indexKeyArr = pathSolver.parseArr(this._keys), queryArr = pathSolver.parseArr(query), matchedKeys = [], matchedKeyCount = 0, i; // Loop the query array and check the order of keys against the // index key array to see if this index can be used for (i = 0; i < indexKeyArr.length; i++) { if (queryArr[i] === indexKeyArr[i]) { matchedKeyCount++; matchedKeys.push(queryArr[i]); } else { // Query match failed - this is a hash map index so partial key match won't work return { matchedKeys: [], totalKeyCount: queryArr.length, score: 0 }; } } return { matchedKeys: matchedKeys, totalKeyCount: queryArr.length, score: matchedKeyCount }; //return pathSolver.countObjectPaths(this._keys, query); }; IndexHashMap.prototype._itemHash = function (item, keys) { var path = new Path(), pathData, hash = '', k; pathData = path.parse(keys); for (k = 0; k < pathData.length; k++) { if (hash) { hash += '_'; } hash += path.value(item, pathData[k].path).join(':'); } return hash; }; IndexHashMap.prototype._itemKeyHash = function (item, keys) { var path = new Path(), pathData, hash = '', k; pathData = path.parse(keys); for (k = 0; k < pathData.length; k++) { if (hash) { hash += '_'; } hash += path.keyValue(item, pathData[k].path); } return hash; }; IndexHashMap.prototype._itemHashArr = function (item, keys) { var path = new Path(), pathData, //hash = '', hashArr = [], valArr, i, k, j; pathData = path.parse(keys); for (k = 0; k < pathData.length; k++) { valArr = path.value(item, pathData[k].path); for (i = 0; i < valArr.length; i++) { if (k === 0) { // Setup the initial hash array hashArr.push(valArr[i]); } else { // Loop the hash array and concat the value to it for (j = 0; j < hashArr.length; j++) { hashArr[j] = hashArr[j] + '_' + valArr[i]; } } } } return hashArr; }; // Register this index on the shared object Shared.index.hashed = IndexHashMap; Shared.finishModule('IndexHashMap'); module.exports = IndexHashMap; },{"./Path":28,"./Shared":34}],14:[function(_dereq_,module,exports){ "use strict"; var Shared = _dereq_('./Shared'); /** * The key value store class used when storing basic in-memory KV data, * and can be queried for quick retrieval. Mostly used for collection * primary key indexes and lookups. * @param {String=} name Optional KV store name. * @constructor */ var KeyValueStore = function (name) { this.init.apply(this, arguments); }; KeyValueStore.prototype.init = function (name) { this._name = name; this._data = {}; this._primaryKey = '_id'; }; Shared.addModule('KeyValueStore', KeyValueStore); Shared.mixin(KeyValueStore.prototype, 'Mixin.ChainReactor'); /** * Get / set the name of the key/value store. * @param {String} val The name to set. * @returns {*} */ Shared.synthesize(KeyValueStore.prototype, 'name'); /** * Get / set the primary key. * @param {String} key The key to set. * @returns {*} */ KeyValueStore.prototype.primaryKey = function (key) { if (key !== undefined) { this._primaryKey = key; return this; } return this._primaryKey; }; /** * Removes all data from the store. * @returns {*} */ KeyValueStore.prototype.truncate = function () { this._data = {}; return this; }; /** * Sets data against a key in the store. * @param {String} key The key to set data for. * @param {*} value The value to assign to the key. * @returns {*} */ KeyValueStore.prototype.set = function (key, value) { this._data[key] = value ? value : true; return this; }; /** * Gets data stored for the passed key. * @param {String} key The key to get data for. * @returns {*} */ KeyValueStore.prototype.get = function (key) { return this._data[key]; }; /** * Get / set the primary key. * @param {*} val A lookup query. * @returns {*} */ KeyValueStore.prototype.lookup = function (val) { var pk = this._primaryKey, valType = typeof val, arrIndex, arrCount, lookupItem, result = []; // Check for early exit conditions if (valType === 'string' || valType === 'number') { lookupItem = this.get(val); if (lookupItem !== undefined) { return [lookupItem]; } else { return []; } } else if (valType === 'object') { if (val instanceof Array) { // An array of primary keys, find all matches arrCount = val.length; result = []; for (arrIndex = 0; arrIndex < arrCount; arrIndex++) { lookupItem = this.lookup(val[arrIndex]); if (lookupItem) { if (lookupItem instanceof Array) { result = result.concat(lookupItem); } else { result.push(lookupItem); } } } return result; } else if (val[pk] !== undefined && val[pk] !== null) { return this.lookup(val[pk]); } } // COMMENTED AS CODE WILL NEVER BE REACHED // Complex lookup /*lookupData = this._lookupKeys(val); keys = lookupData.keys; negate = lookupData.negate; if (!negate) { // Loop keys and return values for (arrIndex = 0; arrIndex < keys.length; arrIndex++) { result.push(this.get(keys[arrIndex])); } } else { // Loop data and return non-matching keys for (arrIndex in this._data) { if (this._data.hasOwnProperty(arrIndex)) { if (keys.indexOf(arrIndex) === -1) { result.push(this.get(arrIndex)); } } } } return result;*/ }; // COMMENTED AS WE ARE NOT CURRENTLY PASSING COMPLEX QUERIES TO KEYVALUESTORE INDEXES /*KeyValueStore.prototype._lookupKeys = function (val) { var pk = this._primaryKey, valType = typeof val, arrIndex, arrCount, lookupItem, bool, result; if (valType === 'string' || valType === 'number') { return { keys: [val], negate: false }; } else if (valType === 'object') { if (val instanceof RegExp) { // Create new data result = []; for (arrIndex in this._data) { if (this._data.hasOwnProperty(arrIndex)) { if (val.test(arrIndex)) { result.push(arrIndex); } } } return { keys: result, negate: false }; } else if (val instanceof Array) { // An array of primary keys, find all matches arrCount = val.length; result = []; for (arrIndex = 0; arrIndex < arrCount; arrIndex++) { result = result.concat(this._lookupKeys(val[arrIndex]).keys); } return { keys: result, negate: false }; } else if (val.$in && (val.$in instanceof Array)) { return { keys: this._lookupKeys(val.$in).keys, negate: false }; } else if (val.$nin && (val.$nin instanceof Array)) { return { keys: this._lookupKeys(val.$nin).keys, negate: true }; } else if (val.$ne) { return { keys: this._lookupKeys(val.$ne, true).keys, negate: true }; } else if (val.$or && (val.$or instanceof Array)) { // Create new data result = []; for (arrIndex = 0; arrIndex < val.$or.length; arrIndex++) { result = result.concat(this._lookupKeys(val.$or[arrIndex]).keys); } return { keys: result, negate: false }; } else if (val[pk]) { return this._lookupKeys(val[pk]); } } };*/ /** * Removes data for the given key from the store. * @param {String} key The key to un-set. * @returns {*} */ KeyValueStore.prototype.unSet = function (key) { delete this._data[key]; return this; }; /** * Sets data for the give key in the store only where the given key * does not already have a value in the store. * @param {String} key The key to set data for. * @param {*} value The value to assign to the key. * @returns {Boolean} True if data was set or false if data already * exists for the key. */ KeyValueStore.prototype.uniqueSet = function (key, value) { if (this._data[key] === undefined) { this._data[key] = value; return true; } return false; }; Shared.finishModule('KeyValueStore'); module.exports = KeyValueStore; },{"./Shared":34}],15:[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":26,"./Shared":34}],16:[function(_dereq_,module,exports){ "use strict"; var CRUD = { preSetData: function () { }, postSetData: function () { } }; module.exports = CRUD; },{}],17:[function(_dereq_,module,exports){ "use strict"; /** * The chain reactor mixin, provides methods to the target object that allow chain * reaction events to propagate to the target and be handled, processed and passed * on down the chain. * @mixin */ var ChainReactor = { /** * Creates a chain link between the current reactor node and the passed * reactor node. Chain packets that are send by this reactor node will * then be propagated to the passed node for subsequent packets. * @param {*} obj The chain reactor node to link to. */ chain: function (obj) { if (this.debug && this.debug()) { if (obj._reactorIn && obj._reactorOut) { console.log(obj._reactorIn.logIdentifier() + ' Adding target "' + obj._reactorOut.instanceIdentifier() + '" to the chain reactor target list'); } else { console.log(this.logIdentifier() + ' Adding target "' + obj.instanceIdentifier() + '" to the chain reactor target list'); } } this._chain = this._chain || []; var index = this._chain.indexOf(obj); if (index === -1) { this._chain.push(obj); } }, /** * Removes a chain link between the current reactor node and the passed * reactor node. Chain packets sent from this reactor node will no longer * be received by the passed node. * @param {*} obj The chain reactor node to unlink from. */ unChain: function (obj) { if (this.debug && this.debug()) { if (obj._reactorIn && obj._reactorOut) { console.log(obj._reactorIn.logIdentifier() + ' Removing target "' + obj._reactorOut.instanceIdentifier() + '" from the chain reactor target list'); } else { console.log(this.logIdentifier() + ' Removing target "' + obj.instanceIdentifier() + '" from the chain reactor target list'); } } if (this._chain) { var index = this._chain.indexOf(obj); if (index > -1) { this._chain.splice(index, 1); } } }, /** * Gets / sets the flag that will enable / disable chain reactor sending * from this instance. Chain reactor sending is enabled by default on all * instances. * @param {Boolean} val True or false to enable or disable chain sending. * @returns {*} */ chainEnabled: function (val) { if (val !== undefined) { this._chainDisabled = !val; return this; } return !this._chainDisabled; }, /** * Determines if this chain reactor node has any listeners downstream. * @returns {Boolean} True if there are nodes downstream of this node. */ chainWillSend: function () { return Boolean(this._chain && !this._chainDisabled); }, /** * Sends a chain reactor packet downstream from this node to any of its * chained targets that were linked to this node via a call to chain(). * @param {String} type The type of chain reactor packet to send. This * can be any string but the receiving reactor nodes will not react to * it unless they recognise the string. Built-in strings include: "insert", * "update", "remove", "setData" and "debug". * @param {Object} data A data object that usually contains a key called * "dataSet" which is an array of items to work on, and can contain other * custom keys that help describe the operation. * @param {Object=} options An options object. Can also contain custom * key/value pairs that your custom chain reactor code can operate on. */ chainSend: function (type, data, options) { if (this._chain && !this._chainDisabled) { var arr = this._chain, arrItem, count = arr.length, index, dataCopy = this.decouple(data, count); for (index = 0; index < count; index++) { arrItem = arr[index]; if (!arrItem._state || (arrItem._state && !arrItem.isDropped())) { if (this.debug && this.debug()) { if (arrItem._reactorIn && arrItem._reactorOut) { console.log(arrItem._reactorIn.logIdentifier() + ' Sending data down the chain reactor pipe to "' + arrItem._reactorOut.instanceIdentifier() + '"'); } else { console.log(this.logIdentifier() + ' Sending data down the chain reactor pipe to "' + arrItem.instanceIdentifier() + '"'); } } if (arrItem.chainReceive) { arrItem.chainReceive(this, type, dataCopy[index], options); } } else { console.log('Reactor Data:', type, data, options); console.log('Reactor Node:', arrItem); throw('Chain reactor attempting to send data to target reactor node that is in a dropped state!'); } } } }, /** * Handles receiving a chain reactor message that was sent via the chainSend() * method. Creates the chain packet object and then allows it to be processed. * @param {Object} sender The node that is sending the packet. * @param {String} type The type of packet. * @param {Object} data The data related to the packet. * @param {Object=} options An options object. */ chainReceive: function (sender, type, data, options) { var chainPacket = { sender: sender, type: type, data: data, options: options }, cancelPropagate = false; if (this.debug && this.debug()) { console.log(this.logIdentifier() + ' Received data from parent reactor node'); } // Check if we have a chain handler method if (this._chainHandler) { // Fire our internal handler cancelPropagate = this._chainHandler(chainPacket); } // Check if we were told to cancel further propagation if (!cancelPropagate) { // Propagate the message down the chain this.chainSend(chainPacket.type, chainPacket.data, chainPacket.options); } } }; module.exports = ChainReactor; },{}],18:[function(_dereq_,module,exports){ "use strict"; var idCounter = 0, Overload = _dereq_('./Overload'), Serialiser = _dereq_('./Serialiser'), Common, serialiser = new Serialiser(); /** * Provides commonly used methods to most classes in ForerunnerDB. * @mixin */ Common = { // Expose the serialiser object so it can be extended with new data handlers. serialiser: serialiser, /** * Generates a JSON serialisation-compatible object instance. After the * instance has been passed through this method, it will be able to survive * a JSON.stringify() and JSON.parse() cycle and still end up as an * instance at the end. Further information about this process can be found * in the ForerunnerDB wiki at: https://github.com/Irrelon/ForerunnerDB/wiki/Serialiser-&-Performance-Benchmarks * @param {*} val The object instance such as "new Date()" or "new RegExp()". */ make: function (val) { // This is a conversion request, hand over to serialiser return serialiser.convert(val); }, /** * Gets / sets data in the item store. The store can be used to set and * retrieve data against a key. Useful for adding arbitrary key/value data * to a collection / view etc and retrieving it later. * @param {String|*} key The key under which to store the passed value or * retrieve the existing stored value. * @param {*=} val Optional value. If passed will overwrite the existing value * stored against the specified key if one currently exists. * @returns {*} */ store: function (key, val) { if (key !== undefined) { if (val !== undefined) { // Store the data this._store = this._store || {}; this._store[key] = val; return this; } if (this._store) { return this._store[key]; } } return undefined; }, /** * Removes a previously stored key/value pair from the item store, set previously * by using the store() method. * @param {String|*} key The key of the key/value pair to remove; * @returns {Common} Returns this for chaining. */ unStore: function (key) { if (key !== undefined) { delete this._store[key]; } return this; }, /** * Returns a non-referenced version of the passed object / array. * @param {Object} data The object or array to return as a non-referenced version. * @param {Number=} copies Optional number of copies to produce. If specified, the return * value will be an array of decoupled objects, each distinct from the other. * @returns {*} */ decouple: function (data, copies) { if (data !== undefined && data !== "") { if (!copies) { return this.jParse(this.jStringify(data)); } else { var i, json = this.jStringify(data), copyArr = []; for (i = 0; i < copies; i++) { copyArr.push(this.jParse(json)); } return copyArr; } } return undefined; }, /** * Parses and returns data from stringified version. * @param {String} data The stringified version of data to parse. * @returns {Object} The parsed JSON object from the data. */ jParse: function (data) { return JSON.parse(data, serialiser.reviver()); }, /** * Converts a JSON object into a stringified version. * @param {Object} data The data to stringify. * @returns {String} The stringified data. */ jStringify: function (data) { //return serialiser.stringify(data); return JSON.stringify(data); }, /** * Generates a new 16-character hexadecimal unique ID or * generates a new 16-character hexadecimal ID based on * the passed string. Will always generate the same ID * for the same string. * @param {String=} str A string to generate the ID from. * @return {String} */ objectId: function (str) { var id, pow = Math.pow(10, 17); if (!str) { idCounter++; id = (idCounter + ( Math.random() * pow + Math.random() * pow + Math.random() * pow + Math.random() * pow )).toString(16); } else { var val = 0, count = str.length, i; for (i = 0; i < count; i++) { val += str.charCodeAt(i) * pow; } id = val.toString(16); } return id; }, /** * Generates a unique hash for the passed object. * @param {Object} obj The object to generate a hash for. * @returns {String} */ hash: function (obj) { return JSON.stringify(obj); }, /** * Gets / sets debug flag that can enable debug message output to the * console if required. * @param {Boolean} val The value to set debug flag to. * @return {Boolean} True if enabled, false otherwise. */ /** * Sets debug flag for a particular type that can enable debug message * output to the console if required. * @param {String} type The name of the debug type to set flag for. * @param {Boolean} val The value to set debug flag to. * @return {Boolean} True if enabled, false otherwise. */ debug: new Overload([ function () { return this._debug && this._debug.all; }, function (val) { if (val !== undefined) { if (typeof val === 'boolean') { this._debug = this._debug || {}; this._debug.all = val; this.chainSend('debug', this._debug); return this; } else { return (this._debug && this._debug[val]) || (this._db && this._db._debug && this._db._debug[val]) || (this._debug && this._debug.all); } } return this._debug && this._debug.all; }, function (type, val) { if (type !== undefined) { if (val !== undefined) { this._debug = this._debug || {}; this._debug[type] = val; this.chainSend('debug', this._debug); return this; } return (this._debug && this._debug[val]) || (this._db && this._db._debug && this._db._debug[type]); } return this._debug && this._debug.all; } ]), /** * Returns a string describing the class this instance is derived from. * @returns {string} */ classIdentifier: function () { return 'ForerunnerDB.' + this.className; }, /** * Returns a string describing the instance by it's class name and instance * object name. * @returns {String} The instance identifier. */ instanceIdentifier: function () { return '[' + this.className + ']' + this.name(); }, /** * Returns a string used to denote a console log against this instance, * consisting of the class identifier and instance identifier. * @returns {string} The log identifier. */ logIdentifier: function () { return 'ForerunnerDB ' + this.instanceIdentifier(); }, /** * Converts a query object with MongoDB dot notation syntax * to Forerunner's object notation syntax. * @param {Object} obj The object to convert. */ convertToFdb: function (obj) { var varName, splitArr, objCopy, i; for (i in obj) { if (obj.hasOwnProperty(i)) { objCopy = obj; if (i.indexOf('.') > -1) { // Replace .$ with a placeholder before splitting by . char i = i.replace('.$', '[|$|]'); splitArr = i.split('.'); while ((varName = splitArr.shift())) { // Replace placeholder back to original .$ varName = varName.replace('[|$|]', '.$'); if (splitArr.length) { objCopy[varName] = {}; } else { objCopy[varName] = obj[i]; } objCopy = objCopy[varName]; } delete obj[i]; } } } }, /** * Checks if the state is dropped. * @returns {boolean} True when dropped, false otherwise. */ isDropped: function () { return this._state === 'dropped'; }, /** * Registers a timed callback that will overwrite itself if * the same id is used within the timeout period. Useful * for de-bouncing fast-calls. * @param {String} id An ID for the call (use the same one * to debounce the same calls). * @param {Function} callback The callback method to call on * timeout. * @param {Number} timeout The timeout in milliseconds before * the callback is called. */ debounce: function (id, callback, timeout) { var self = this, newData; self._debounce = self._debounce || {}; if (self._debounce[id]) { // Clear timeout for this item clearTimeout(self._debounce[id].timeout); } newData = { callback: callback, timeout: setTimeout(function () { // Delete existing reference delete self._debounce[id]; // Call the callback callback(); }, timeout) }; // Save current data self._debounce[id] = newData; } }; module.exports = Common; },{"./Overload":27,"./Serialiser":33}],19:[function(_dereq_,module,exports){ "use strict"; /** * Provides some database constants. * @mixin */ var Constants = { TYPE_INSERT: 0, TYPE_UPDATE: 1, TYPE_REMOVE: 2, PHASE_BEFORE: 0, PHASE_AFTER: 1 }; module.exports = Constants; },{}],20:[function(_dereq_,module,exports){ "use strict"; var Overload = _dereq_('./Overload'); /** * Provides event emitter functionality including the methods: on, off, once, emit, deferEmit. * @mixin */ var Events = { on: new Overload({ /** * Attach an event listener to the passed event. * @param {String} event The name of the event to listen for. * @param {Function} listener The method to call when the event is fired. */ 'string, function': function (event, listener) { this._listeners = this._listeners || {}; this._listeners[event] = this._listeners[event] || {}; this._listeners[event]['*'] = this._listeners[event]['*'] || []; this._listeners[event]['*'].push(listener); return this; }, /** * Attach an event listener to the passed event only if the passed * id matches the document id for the event being fired. * @param {String} event The name of the event to listen for. * @param {*} id The document id to match against. * @param {Function} listener The method to call when the event is fired. */ 'string, *, function': function (event, id, listener) { this._listeners = this._listeners || {}; this._listeners[event] = this._listeners[event] || {}; this._listeners[event][id] = this._listeners[event][id] || []; this._listeners[event][id].push(listener); return this; } }), once: new Overload({ 'string, function': function (eventName, callback) { var self = this, fired = false, internalCallback = function () { if (!fired) { self.off(eventName, internalCallback); callback.apply(self, arguments); fired = true; } }; return this.on(eventName, internalCallback); }, 'string, *, function': function (eventName, id, callback) { var self = this, fired = false, internalCallback = function () { if (!fired) { self.off(eventName, id, internalCallback); callback.apply(self, arguments); fired = true; } }; return this.on(eventName, id, internalCallback); } }), off: new Overload({ 'string': function (event) { var self = this; if (this._emitting) { this._eventRemovalQueue = this._eventRemovalQueue || []; this._eventRemovalQueue.push(function () { self.off(event); }); } else { if (this._listeners && this._listeners[event] && event in this._listeners) { delete this._listeners[event]; } } return this; }, 'string, function': function (event, listener) { var self = this, arr, index; if (this._emitting) { this._eventRemovalQueue = this._eventRemovalQueue || []; this._eventRemovalQueue.push(function () { self.off(event, listener); }); } else { if (typeof(listener) === 'string') { if (this._listeners && this._listeners[event] && this._listeners[event][listener]) { delete this._listeners[event][listener]; } } else { if (this._listeners && event in this._listeners) { arr = this._listeners[event]['*']; index = arr.indexOf(listener); if (index > -1) { arr.splice(index, 1); } } } } return this; }, 'string, *, function': function (event, id, listener) { var self = this; if (this._emitting) { this._eventRemovalQueue = this._eventRemovalQueue || []; this._eventRemovalQueue.push(function () { self.off(event, id, listener); }); } else { 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) { var self = this; if (this._emitting) { this._eventRemovalQueue = this._eventRemovalQueue || []; this._eventRemovalQueue.push(function () { self.off(event, id); }); } else { 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 || {}; this._emitting = true; if (event in this._listeners) { var arrIndex, arrCount, tmpFunc, arr, listenerIdArr, listenerIdCount, listenerIdIndex; // Handle global emit if (this._listeners[event]['*']) { arr = this._listeners[event]['*']; arrCount = arr.length; for (arrIndex = 0; arrIndex < arrCount; arrIndex++) { // Check we have a function to execute tmpFunc = arr[arrIndex]; if (typeof tmpFunc === 'function') { tmpFunc.apply(this, Array.prototype.slice.call(arguments, 1)); } } } // Handle individual emit if (data instanceof Array) { // Check if the array is an array of objects in the collection if (data[0] && data[0][this._primaryKey]) { // Loop the array and check for listeners against the primary key listenerIdArr = this._listeners[event]; arrCount = data.length; for (arrIndex = 0; arrIndex < arrCount; arrIndex++) { if (listenerIdArr[data[arrIndex][this._primaryKey]]) { // Emit for this id listenerIdCount = listenerIdArr[data[arrIndex][this._primaryKey]].length; for (listenerIdIndex = 0; listenerIdIndex < listenerIdCount; listenerIdIndex++) { tmpFunc = listenerIdArr[data[arrIndex][this._primaryKey]][listenerIdIndex]; if (typeof tmpFunc === 'function') { listenerIdArr[data[arrIndex][this._primaryKey]][listenerIdIndex].apply(this, Array.prototype.slice.call(arguments, 1)); } } } } } } } this._emitting = false; this._processRemovalQueue(); return this; }, /** * If events are cleared with the off() method while the event emitter is * actively processing any events then the off() calls get added to a * queue to be executed after the event emitter is finished. This stops * errors that might occur by potentially modifying the event queue while * the emitter is running through them. This method is called after the * event emitter is finished processing. * @private */ _processRemovalQueue: function () { var i; if (this._eventRemovalQueue && this._eventRemovalQueue.length) { // Execute each removal call for (i = 0; i < this._eventRemovalQueue.length; i++) { this._eventRemovalQueue[i](); } // Clear the removal queue this._eventRemovalQueue = []; } }, /** * Queues an event to be fired. This has automatic de-bouncing so that any * events of the same type that occur within 100 milliseconds of a previous * one will all be wrapped into a single emit rather than emitting tons of * events for lots of chained inserts etc. Only the data from the last * de-bounced event will be emitted. * @param {String} eventName The name of the event to emit. * @param {*=} data Optional data to emit with the event. */ deferEmit: function (eventName, data) { var self = this, args; if (!this._noEmitDefer && (!this._db || (this._db && !this._db._noEmitDefer))) { args = arguments; // Check for an existing timeout this._deferTimeout = this._deferTimeout || {}; if (this._deferTimeout[eventName]) { clearTimeout(this._deferTimeout[eventName]); } // Set a timeout this._deferTimeout[eventName] = setTimeout(function () { if (self.debug()) { console.log(self.logIdentifier() + ' Emitting ' + args[0]); } self.emit.apply(self, args); }, 1); } else { this.emit.apply(this, arguments); } return this; } }; module.exports = Events; },{"./Overload":27}],21:[function(_dereq_,module,exports){ "use strict"; /** * Provides object matching algorithm methods. * @mixin */ var Matching = { /** * Internal method that checks a document against a test object. * @param {*} source The source object or value to test against. * @param {*} test The test object or value to test with. * @param {Object} queryOptions The options the query was passed with. * @param {String=} opToApply The special operation to apply to the test such * as 'and' or an 'or' operator. * @param {Object=} options An object containing options to apply to the * operation such as limiting the fields returned etc. * @returns {Boolean} True if the test was positive, false on negative. * @private */ _match: function (source, test, queryOptions, opToApply, options) { // TODO: This method is quite long, break into smaller pieces var operation, applyOp = opToApply, recurseVal, tmpIndex, sourceType = typeof source, testType = typeof test, matchedAll = true, opResult, substringCache, i; if (sourceType === 'object' && source === null) { sourceType = 'null'; } if (testType === 'object' && test === null) { testType = 'null'; } options = options || {}; queryOptions = queryOptions || {}; // Check if options currently holds a root query object if (!options.$rootQuery) { // Root query not assigned, hold the root query options.$rootQuery = test; } // Check if options currently holds a root source object if (!options.$rootSource) { // Root query not assigned, hold the root query options.$rootSource = source; } // Assign current query data options.$currentQuery = test; options.$rootData = options.$rootData || {}; // Check if the comparison data are both strings or numbers if ((sourceType === 'string' || sourceType === 'number' || sourceType === 'null') && (testType === 'string' || testType === 'number' || testType === 'null')) { // 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' || sourceType === 'null' || testType === 'null') { // Number or null comparison if (source !== test) { matchedAll = false; } } else { // String comparison // TODO: We can probably use a queryOptions.$locale as a second parameter here // TODO: to satisfy https://github.com/Irrelon/ForerunnerDB/issues/35 if (source.localeCompare(test)) { matchedAll = false; } } } else if ((sourceType === 'string' || sourceType === 'number') && (testType === 'object' && test instanceof RegExp)) { if (!test.test(source)) { matchedAll = false; } } else { for (i in test) { if (test.hasOwnProperty(i)) { // Assign previous query data options.$previousQuery = options.$parent; // Assign parent query data options.$parent = { query: test[i], key: i, parent: options.$previousQuery }; // Reset operation flag operation = false; // Grab first two chars of the key name to check for $ substringCache = i.substr(0, 2); // Check if the property is a comment (ignorable) if (substringCache === '//') { // Skip this property continue; } // Check if the property starts with a dollar (function) if (substringCache.indexOf('$') === 0) { // Ask the _matchOp method to handle the operation opResult = this._matchOp(i, source, test[i], queryOptions, options); // Check the result of the matchOp operation // If the result is -1 then no operation took place, otherwise the result // will be a boolean denoting a match (true) or no match (false) if (opResult > -1) { if (opResult) { if (opToApply === 'or') { return true; } } else { // Set the matchedAll flag to the result of the operation // because the operation did not return true matchedAll = opResult; } // Record that an operation was handled operation = true; } } // Check for regex if (!operation && test[i] instanceof RegExp) { operation = true; if (sourceType === 'object' && source[i] !== undefined && test[i].test(source[i])) { if (opToApply === 'or') { return true; } } else { matchedAll = false; } } if (!operation) { // Check if our query is an object if (typeof(test[i]) === 'object') { // Because test[i] is an object, source must also be an object // Check if our source data we are checking the test query against // is an object or an array if (source[i] !== undefined) { if (source[i] instanceof Array && !(test[i] instanceof Array)) { // The source data is an array, so check each item until a // match is found recurseVal = false; for (tmpIndex = 0; tmpIndex < source[i].length; tmpIndex++) { recurseVal = this._match(source[i][tmpIndex], test[i], queryOptions, applyOp, options); if (recurseVal) { // One of the array items matched the query so we can // include this item in the results, so break now break; } } if (recurseVal) { if (opToApply === 'or') { return true; } } else { matchedAll = false; } } else if (!(source[i] instanceof Array) && test[i] instanceof Array) { // The test key data is an array and the source key data is not so check // each item in the test key data to see if the source item matches one // of them. This is effectively an $in search. recurseVal = false; for (tmpIndex = 0; tmpIndex < test[i].length; tmpIndex++) { recurseVal = this._match(source[i], test[i][tmpIndex], queryOptions, applyOp, options); if (recurseVal) { // One of the array items matched the query so we can // include this item in the results, so break now break; } } if (recurseVal) { if (opToApply === 'or') { return true; } } else { matchedAll = false; } } else if (typeof(source) === 'object') { // Recurse down the object tree recurseVal = this._match(source[i], test[i], queryOptions, applyOp, options); if (recurseVal) { if (opToApply === 'or') { return true; } } else { matchedAll = false; } } else { recurseVal = this._match(undefined, test[i], queryOptions, applyOp, options); if (recurseVal) { if (opToApply === 'or') { return true; } } else { matchedAll = false; } } } else { // First check if the test match is an $exists if (test[i] && test[i].$exists !== undefined) { // Push the item through another match recurse recurseVal = this._match(undefined, test[i], queryOptions, applyOp, options); if (recurseVal) { if (opToApply === 'or') { return true; } } else { matchedAll = false; } } else { matchedAll = false; } } } else { // Check if the prop matches our test value if (source && source[i] === test[i]) { if (opToApply === 'or') { return true; } } else if (source && source[i] && source[i] instanceof Array && test[i] && typeof(test[i]) !== "object") { // We are looking for a value inside an array // The source data is an array, so check each item until a // match is found recurseVal = false; for (tmpIndex = 0; tmpIndex < source[i].length; tmpIndex++) { recurseVal = this._match(source[i][tmpIndex], test[i], queryOptions, applyOp, options); if (recurseVal) { // One of the array items matched the query so we can // include this item in the results, so break now break; } } if (recurseVal) { if (opToApply === 'or') { return true; } } else { matchedAll = false; } } else { matchedAll = false; } } } if (opToApply === 'and' && !matchedAll) { return false; } } } } return matchedAll; }, /** * Internal method, performs a matching process against a query operator such as $gt or $nin. * @param {String} key The property name in the test that matches the operator to perform * matching against. * @param {*} source The source data to match the query against. * @param {*} test The query to match the source against. * @param {Object} queryOptions The options the query was passed with. * @param {Object=} options An options object. * @returns {*} * @private */ _matchOp: function (key, source, test, queryOptions, options) { // Check for commands switch (key) { case '$gt': // Greater than return source > test; case '$gte': // Greater than or equal return source >= test; case '$lt': // Less than return source < test; case '$lte': // Less than or equal return source <= test; case '$exists': // Property exists return (source === undefined) !== test; case '$eq': // Equals return source == test; // jshint ignore:line case '$eeq': // Equals equals return source === test; case '$ne': // Not equals return source != test; // jshint ignore:line case '$nee': // Not equals equals return source !== test; case '$or': // Match true on ANY check to pass for (var orIndex = 0; orIndex < test.length; orIndex++) { if (this._match(source, test[orIndex], queryOptions, 'and', options)) { return true; } } return false; case '$and': // Match true on ALL checks to pass for (var andIndex = 0; andIndex < test.length; andIndex++) { if (!this._match(source, test[andIndex], queryOptions, 'and', options)) { return false; } } return true; case '$in': // In // Check that the in test is an array if (test instanceof Array) { var inArr = test, inArrCount = inArr.length, inArrIndex; for (inArrIndex = 0; inArrIndex < inArrCount; inArrIndex++) { if (this._match(source, inArr[inArrIndex], queryOptions, 'and', options)) { return true; } } return false; } else if (typeof test === 'object') { return this._match(source, test, queryOptions, 'and', options); } else { console.log(this.logIdentifier() + ' Cannot use an $in operator on a non-array key: ' + key, options.$rootQuery); return false; } break; case '$nin': // Not in // Check that the not-in test is an array if (test instanceof Array) { var notInArr = test, notInArrCount = notInArr.length, notInArrIndex; for (notInArrIndex = 0; notInArrIndex < notInArrCount; notInArrIndex++) { if (this._match(source, notInArr[notInArrIndex], queryOptions, 'and', options)) { return false; } } return true; } else if (typeof test === 'object') { return this._match(source, test, queryOptions, 'and', options); } else { console.log(this.logIdentifier() + ' Cannot use a $nin operator on a non-array key: ' + key, options.$rootQuery); return false; } break; case '$fastIn': if (test instanceof Array) { // Source is a string or number, use indexOf to identify match in array return test.indexOf(source) !== -1; } else { console.log(this.logIdentifier() + ' Cannot use an $fastIn operator on a non-array key: ' + key, options.$rootQuery); return false; } break; case '$distinct': // Ensure options holds a distinct lookup options.$rootData['//distinctLookup'] = options.$rootData['//distinctLookup'] || {}; for (var distinctProp in test) { if (test.hasOwnProperty(distinctProp)) { options.$rootData['//distinctLookup'][distinctProp] = options.$rootData['//distinctLookup'][distinctProp] || {}; // Check if the options distinct lookup has this field's value if (options.$rootData['//distinctLookup'][distinctProp][source[distinctProp]]) { // Value is already in use return false; } else { // Set the value in the lookup options.$rootData['//distinctLookup'][distinctProp][source[distinctProp]] = true; // Allow the item in the results return true; } } } break; case '$count': var countKey, countArr, countVal; // Iterate the count object's keys for (countKey in test) { if (test.hasOwnProperty(countKey)) { // Check the property exists and is an array. If the property being counted is not // an array (or doesn't exist) then use a value of zero in any further count logic countArr = source[countKey]; if (typeof countArr === 'object' && countArr instanceof Array) { countVal = countArr.length; } else { countVal = 0; } // Now recurse down the query chain further to satisfy the query for this key (countKey) if (!this._match(countVal, test[countKey], queryOptions, 'and', options)) { return false; } } } // Allow the item in the results return true; case '$find': case '$findOne': case '$findSub': var fromType = 'collection', findQuery, findOptions, subQuery, subOptions, subPath, result, operation = {}; // Check all parts of the $find operation exist if (!test.$from) { throw(key + ' missing $from property!'); } if (test.$fromType) { fromType = test.$fromType; // Check the fromType exists as a method if (!this.db()[fromType] || typeof this.db()[fromType] !== 'function') { throw(key + ' cannot operate against $fromType "' + fromType + '" because the database does not recognise this type of object!'); } } // Perform the find operation findQuery = test.$query || {}; findOptions = test.$options || {}; if (key === '$findSub') { if (!test.$path) { throw(key + ' missing $path property!'); } subPath = test.$path; subQuery = test.$subQuery || {}; subOptions = test.$subOptions || {}; if (options.$parent && options.$parent.parent && options.$parent.parent.key) { result = this.db()[fromType](test.$from).findSub(findQuery, subPath, subQuery, subOptions); } else { // This is a root $find* query // Test the source against the main findQuery if (this._match(source, findQuery, {}, 'and', options)) { result = this._findSub([source], subPath, subQuery, subOptions); } return result && result.length > 0; } } else { result = this.db()[fromType](test.$from)[key.substr(1)](findQuery, findOptions); } operation[options.$parent.parent.key] = result; return this._match(source, operation, queryOptions, 'and', options); } return -1; }, /** * * @param {Array | Object} docArr An array of objects to run the join * operation against or a single object. * @param {Array} joinClause The join clause object array (the array in * the $join key of a normal join options object). * @param {Object} joinSource An object containing join source reference * data or a blank object if you are doing a bespoke join operation. * @param {Object} options An options object or blank object if no options. * @returns {Array} * @private */ applyJoin: function (docArr, joinClause, joinSource, options) { var self = this, joinSourceIndex, joinSourceKey, joinMatch, joinSourceType, joinSourceIdentifier, resultKeyName, joinSourceInstance, resultIndex, joinSearchQuery, joinMulti, joinRequire, joinPrefix, joinMatchIndex, joinMatchData, joinSearchOptions, joinFindResults, joinFindResult, joinItem, resultRemove = [], l; if (!(docArr instanceof Array)) { // Turn the document into an array docArr = [docArr]; } for (joinSourceIndex = 0; joinSourceIndex < joinClause.length; joinSourceIndex++) { for (joinSourceKey in joinClause[joinSourceIndex]) { if (joinClause[joinSourceIndex].hasOwnProperty(joinSourceKey)) { // Get the match data for the join joinMatch = joinClause[joinSourceIndex][joinSourceKey]; // Check if the join is to a collection (default) or a specified source type // e.g 'view' or 'collection' joinSourceType = joinMatch.$sourceType || 'collection'; joinSourceIdentifier = '$' + joinSourceType + '.' + joinSourceKey; // Set the key to store the join result in to the collection name by default // can be overridden by the '$as' clause in the join object resultKeyName = joinSourceKey; // Get the join collection instance from the DB if (joinSource[joinSourceIdentifier]) { // We have a joinSource for this identifier already (given to us by // an index when we analysed the query earlier on) and we can use // that source instead. joinSourceInstance = joinSource[joinSourceIdentifier]; } else { // We do not already have a joinSource so grab the instance from the db if (this._db[joinSourceType] && typeof this._db[joinSourceType] === 'function') { joinSourceInstance = this._db[joinSourceType](joinSourceKey); } } // Loop our result data array for (resultIndex = 0; resultIndex < docArr.length; resultIndex++) { // Loop the join conditions and build a search object from them joinSearchQuery = {}; joinMulti = false; joinRequire = false; joinPrefix = ''; for (joinMatchIndex in joinMatch) { if (joinMatch.hasOwnProperty(joinMatchIndex)) { joinMatchData = joinMatch[joinMatchIndex]; // Check the join condition name for a special command operator if (joinMatchIndex.substr(0, 1) === '$') { // Special command switch (joinMatchIndex) { case '$where': if (joinMatchData.$query || joinMatchData.$options) { if (joinMatchData.$query) { // Commented old code here, new one does dynamic reverse lookups //joinSearchQuery = joinMatchData.query; joinSearchQuery = self.resolveDynamicQuery(joinMatchData.$query, docArr[resultIndex]); } if (joinMatchData.$options) { joinSearchOptions = joinMatchData.$options; } } else { throw('$join $where clause requires "$query" and / or "$options" keys to work!'); } break; case '$as': // Rename the collection when stored in the result document resultKeyName = joinMatchData; break; case '$multi': // Return an array of documents instead of a single matching document joinMulti = joinMatchData; break; case '$require': // Remove the result item if no matching join data is found joinRequire = joinMatchData; break; case '$prefix': // Add a prefix to properties mixed in joinPrefix = joinMatchData; break; default: break; } } else { // Get the data to match against and store in the search object // Resolve complex referenced query joinSearchQuery[joinMatchIndex] = self.resolveDynamicQuery(joinMatchData, docArr[resultIndex]); } } } // Do a find on the target collection against the match data joinFindResults = joinSourceInstance.find(joinSearchQuery, joinSearchOptions); // Check if we require a joined row to allow the result item if (!joinRequire || (joinRequire && joinFindResults[0])) { // Join is not required or condition is met if (resultKeyName === '$root') { // The property name to store the join results in is $root // which means we need to mixin the results but this only // works if joinMulti is disabled if (joinMulti !== false) { // Throw an exception here as this join is not physically possible! throw(this.logIdentifier() + ' Cannot combine [$as: "$root"] with [$multi: true] in $join clause!'); } // Mixin the result joinFindResult = joinFindResults[0]; joinItem = docArr[resultIndex]; for (l in joinFindResult) { if (joinFindResult.hasOwnProperty(l) && joinItem[joinPrefix + l] === undefined) { // Properties are only mixed in if they do not already exist // in the target item (are undefined). Using a prefix denoted via // $prefix is a good way to prevent property name conflicts joinItem[joinPrefix + l] = joinFindResult[l]; } } } else { docArr[resultIndex][resultKeyName] = joinMulti === false ? joinFindResults[0] : joinFindResults; } } else { // Join required but condition not met, add item to removal queue resultRemove.push(resultIndex); } } } } } return resultRemove; }, /** * Takes a query object with dynamic references and converts the references * into actual values from the references source. * @param {Object} query The query object with dynamic references. * @param {Object} item The document to apply the references to. * @returns {*} * @private */ resolveDynamicQuery: function (query, item) { var self = this, newQuery, propType, propVal, pathResult, i; // Check for early exit conditions if (typeof query === 'string') { // Check if the property name starts with a back-reference if (query.substr(0, 3) === '$$.') { // Fill the query with a back-referenced value pathResult = this.sharedPathSolver.value(item, query.substr(3, query.length - 3)); } else { pathResult = this.sharedPathSolver.value(item, query); } if (pathResult.length > 1) { return {$in: pathResult}; } else { return pathResult[0]; } } newQuery = {}; for (i in query) { if (query.hasOwnProperty(i)) { propType = typeof query[i]; propVal = query[i]; switch (propType) { case 'string': // Check if the property name starts with a back-reference if (propVal.substr(0, 3) === '$$.') { // Fill the query with a back-referenced value newQuery[i] = this.sharedPathSolver.value(item, propVal.substr(3, propVal.length - 3))[0]; } else { newQuery[i] = propVal; } break; case 'object': newQuery[i] = self.resolveDynamicQuery(propVal, item); break; default: newQuery[i] = propVal; break; } } } return newQuery; }, spliceArrayByIndexList: function (arr, list) { var i; for (i = list.length - 1; i >= 0; i--) { arr.splice(list[i], 1); } } }; module.exports = Matching; },{}],22:[function(_dereq_,module,exports){ "use strict"; /** * Provides sorting methods. * @mixin */ var Sorting = { /** * Sorts the passed value a against the passed value b ascending. * @param {*} a The first value to compare. * @param {*} b The second value to compare. * @returns {*} 1 if a is sorted after b, -1 if a is sorted before b. */ sortAsc: function (a, b) { if (typeof(a) === 'string' && typeof(b) === 'string') { return a.localeCompare(b); } else { if (a > b) { return 1; } else if (a < b) { return -1; } } return 0; }, /** * Sorts the passed value a against the passed value b descending. * @param {*} a The first value to compare. * @param {*} b The second value to compare. * @returns {*} 1 if a is sorted after b, -1 if a is sorted before b. */ sortDesc: function (a, b) { if (typeof(a) === 'string' && typeof(b) === 'string') { return b.localeCompare(a); } else { if (a > b) { return -1; } else if (a < b) { return 1; } } return 0; } }; module.exports = Sorting; },{}],23:[function(_dereq_,module,exports){ "use strict"; var Tags, tagMap = {}; /** * Provides class instance tagging and tag operation methods. * @mixin */ Tags = { /** * Tags a class instance for later lookup. * @param {String} name The tag to add. * @returns {boolean} */ tagAdd: function (name) { var i, self = this, mapArr = tagMap[name] = tagMap[name] || []; for (i = 0; i < mapArr.length; i++) { if (mapArr[i] === self) { return true; } } mapArr.push(self); // Hook the drop event for this so we can react if (self.on) { self.on('drop', function () { // We've been dropped so remove ourselves from the tag map self.tagRemove(name); }); } return true; }, /** * Removes a tag from a class instance. * @param {String} name The tag to remove. * @returns {boolean} */ tagRemove: function (name) { var i, mapArr = tagMap[name]; if (mapArr) { for (i = 0; i < mapArr.length; i++) { if (mapArr[i] === this) { mapArr.splice(i, 1); return true; } } } return false; }, /** * Gets an array of all instances tagged with the passed tag name. * @param {String} name The tag to lookup. * @returns {Array} The array of instances that have the passed tag. */ tagLookup: function (name) { return tagMap[name] || []; }, /** * Drops all instances that are tagged with the passed tag name. * @param {String} name The tag to lookup. * @param {Function} callback Callback once dropping has completed * for all instances that match the passed tag name. * @returns {boolean} */ tagDrop: function (name, callback) { var arr = this.tagLookup(name), dropCb, dropCount, i; dropCb = function () { dropCount--; if (callback && dropCount === 0) { callback(false); } }; if (arr.length) { dropCount = arr.length; // Loop the array and drop all items for (i = arr.length - 1; i >= 0; i--) { arr[i].drop(dropCb); } } return true; } }; module.exports = Tags; },{}],24:[function(_dereq_,module,exports){ "use strict"; var Overload = _dereq_('./Overload'); /** * Provides trigger functionality methods. * @mixin */ var Triggers = { /** * When called in a before phase the newDoc object can be directly altered * to modify the data in it before the operation is carried out. * @callback addTriggerCallback * @param {Object} operation The details about the operation. * @param {Object} oldDoc The document before the operation. * @param {Object} newDoc The document after the operation. */ /** * Add a trigger by id. * @param {String} id The id of the trigger. This must be unique to the type and * phase of the trigger. Only one trigger may be added with this id per type and * phase. * @param {Constants} type The type of operation to apply the trigger to. See * Mixin.Constants for constants to use. * @param {Constants} phase The phase of an operation to fire the trigger on. See * Mixin.Constants for constants to use. * @param {addTriggerCallback} method The method to call when the trigger is fired. * @returns {boolean} True if the trigger was added successfully, false if not. */ addTrigger: function (id, type, phase, method) { var self = this, triggerIndex; // Check if the trigger already exists triggerIndex = self._triggerIndexOf(id, type, phase); if (triggerIndex === -1) { self.triggerStack = {}; // 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; }, /** * Tells the current instance to fire or ignore all triggers whether they * are enabled or not. * @param {Boolean} val Set to true to ignore triggers or false to not * ignore them. * @returns {*} */ ignoreTriggers: function (val) { if (val !== undefined) { this._ignoreTriggers = val; return this; } return this._ignoreTriggers; }, /** * Generates triggers that fire in the after phase for all CRUD ops * that automatically transform data back and forth and keep both * import and export collections in sync with each other. * @param {String} id The unique id for this link IO. * @param {Object} ioData The settings for the link IO. */ addLinkIO: function (id, ioData) { var self = this, matchAll, exportData, importData, exportTriggerMethod, importTriggerMethod, exportTo, importFrom, allTypes, i; // Store the linkIO self._linkIO = self._linkIO || {}; self._linkIO[id] = ioData; exportData = ioData['export']; importData = ioData['import']; if (exportData) { exportTo = self.db().collection(exportData.to); } if (importData) { importFrom = self.db().collection(importData.from); } allTypes = [ self.TYPE_INSERT, self.TYPE_UPDATE, self.TYPE_REMOVE ]; matchAll = function (data, callback) { // Match all callback(false, true); }; if (exportData) { // Check for export match method if (!exportData.match) { // No match method found, use the match all method exportData.match = matchAll; } // Check for export types if (!exportData.types) { exportData.types = allTypes; } exportTriggerMethod = function (operation, oldDoc, newDoc) { // Check if we should execute against this data exportData.match(newDoc, function (err, doExport) { if (!err && doExport) { // Get data to upsert (if any) exportData.data(newDoc, operation.type, function (err, data, callback) { if (!err && data) { // Disable all currently enabled triggers so that we // don't go into a trigger loop exportTo.ignoreTriggers(true); if (operation.type !== 'remove') { // Do upsert exportTo.upsert(data, callback); } else { // Do remove exportTo.remove(data, callback); } // Re-enable the previous triggers exportTo.ignoreTriggers(false); } }); } }); }; } if (importData) { // Check for import match method if (!importData.match) { // No match method found, use the match all method importData.match = matchAll; } // Check for import types if (!importData.types) { importData.types = allTypes; } importTriggerMethod = function (operation, oldDoc, newDoc) { // Check if we should execute against this data importData.match(newDoc, function (err, doExport) { if (!err && doExport) { // Get data to upsert (if any) importData.data(newDoc, operation.type, function (err, data, callback) { if (!err && data) { // Disable all currently enabled triggers so that we // don't go into a trigger loop exportTo.ignoreTriggers(true); if (operation.type !== 'remove') { // Do upsert self.upsert(data, callback); } else { // Do remove self.remove(data, callback); } // Re-enable the previous triggers exportTo.ignoreTriggers(false); } }); } }); }; } if (exportData) { for (i = 0; i < exportData.types.length; i++) { self.addTrigger(id + 'export' + exportData.types[i], exportData.types[i], self.PHASE_AFTER, exportTriggerMethod); } } if (importData) { for (i = 0; i < importData.types.length; i++) { importFrom.addTrigger(id + 'import' + importData.types[i], importData.types[i], self.PHASE_AFTER, importTriggerMethod); } } }, /** * Removes a previously added link IO via it's ID. * @param {String} id The id of the link IO to remove. * @returns {boolean} True if successful, false if the link IO * was not found. */ removeLinkIO: function (id) { var self = this, linkIO = self._linkIO[id], exportData, importData, importFrom, i; if (linkIO) { exportData = linkIO['export']; importData = linkIO['import']; if (exportData) { for (i = 0; i < exportData.types.length; i++) { self.removeTrigger(id + 'export' + exportData.types[i], exportData.types[i], self.db.PHASE_AFTER); } } if (importData) { importFrom = self.db().collection(importData.from); for (i = 0; i < importData.types.length; i++) { importFrom.removeTrigger(id + 'import' + importData.types[i], importData.types[i], self.db.PHASE_AFTER); } } delete self._linkIO[id]; return true; } 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._ignoreTriggers && 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, typeName, phaseName; if (!self._ignoreTriggers && 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 (self.debug()) { 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 "' + triggerItem.id + '" for ' + typeName + ' in phase "' + phaseName + '"'); } // Check if the trigger is already in the stack, if it is, // don't fire it again (this is so we avoid infinite loops // where a trigger triggers another trigger which calls this // one and so on) if (self.triggerStack && self.triggerStack[type] && self.triggerStack[type][phase] && self.triggerStack[type][phase][triggerItem.id]) { // The trigger is already in the stack, do not fire the trigger again if (self.debug()) { console.log('Triggers: Will not run trigger "' + triggerItem.id + '" for ' + typeName + ' in phase "' + phaseName + '" as it is already in the stack!'); } continue; } // Add the trigger to the stack so we don't go down an endless // trigger loop self.triggerStack = self.triggerStack || {}; self.triggerStack[type] = {}; self.triggerStack[type][phase] = {}; self.triggerStack[type][phase][triggerItem.id] = true; // Run the trigger's method and store the response response = triggerItem.method.call(self, operation, oldDoc, newDoc); // Remove the trigger from the stack self.triggerStack = self.triggerStack || {}; self.triggerStack[type] = {}; self.triggerStack[type][phase] = {}; self.triggerStack[type][phase][triggerItem.id] = false; // 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":27}],25:[function(_dereq_,module,exports){ "use strict"; /** * Provides methods to handle object update operations. * @mixin */ var Updating = { /** * Updates a property on an object. * @param {Object} doc The object whose property is to be updated. * @param {String} prop The property to update. * @param {*} val The new value of the property. * @private */ _updateProperty: function (doc, prop, val) { doc[prop] = val; if (this.debug()) { console.log(this.logIdentifier() + ' Setting non-data-bound document property "' + prop + '" to val "' + val + '"'); } }, /** * Increments a value for a property on a document by the passed number. * @param {Object} doc The document to modify. * @param {String} prop The property to modify. * @param {Number} val The amount to increment by. * @private */ _updateIncrement: function (doc, prop, val) { doc[prop] += val; }, /** * Changes the index of an item in the passed array. * @param {Array} arr The array to modify. * @param {Number} indexFrom The index to move the item from. * @param {Number} indexTo The index to move the item to. * @private */ _updateSpliceMove: function (arr, indexFrom, indexTo) { arr.splice(indexTo, 0, arr.splice(indexFrom, 1)[0]); if (this.debug()) { console.log(this.logIdentifier() + ' Moving non-data-bound document array index from "' + indexFrom + '" to "' + indexTo + '"'); } }, /** * Inserts an item into the passed array at the specified index. * @param {Array} arr The array to insert into. * @param {Number} index The index to insert at. * @param {Object} doc The document to insert. * @private */ _updateSplicePush: function (arr, index, doc) { if (arr.length > index) { arr.splice(index, 0, doc); } else { arr.push(doc); } }, /** * Removes an item from the passed array at the specified index. * @param {Array} arr The array to remove from. * @param {Number} index The index of the item to remove. * @param {Number} count The number of items to remove. * @private */ _updateSplicePull: function (arr, index, count) { if (!count) { count = 1; } arr.splice(index, count); }, /** * Inserts an item at the end of an array. * @param {Array} arr The array to insert the item into. * @param {Object} doc The document to insert. * @private */ _updatePush: function (arr, doc) { arr.push(doc); }, /** * Removes an item from the passed array. * @param {Array} arr The array to modify. * @param {Number} index The index of the item in the array to remove. * @private */ _updatePull: function (arr, index) { arr.splice(index, 1); }, /** * Multiplies a value for a property on a document by the passed number. * @param {Object} doc The document to modify. * @param {String} prop The property to modify. * @param {Number} val The amount to multiply by. * @private */ _updateMultiply: function (doc, prop, val) { doc[prop] *= val; }, /** * Renames a property on a document to the passed property. * @param {Object} doc The document to modify. * @param {String} prop The property to rename. * @param {Number} val The new property name. * @private */ _updateRename: function (doc, prop, val) { doc[val] = doc[prop]; delete doc[prop]; }, /** * Sets a property on a document to the passed value. * @param {Object} doc The document to modify. * @param {String} prop The property to set. * @param {*} val The new property value. * @private */ _updateOverwrite: function (doc, prop, val) { doc[prop] = val; }, /** * Deletes a property on a document. * @param {Object} doc The document to modify. * @param {String} prop The property to delete. * @private */ _updateUnset: function (doc, prop) { delete doc[prop]; }, /** * Removes all properties from an object without destroying * the object instance, thereby maintaining data-bound linking. * @param {Object} doc The parent object to modify. * @param {String} prop The name of the child object to clear. * @private */ _updateClear: function (doc, prop) { var obj = doc[prop], i; if (obj && typeof obj === 'object') { for (i in obj) { if (obj.hasOwnProperty(i)) { this._updateUnset(obj, i); } } } }, /** * Pops an item or items from the array stack. * @param {Object} doc The document to modify. * @param {Number} val If set to a positive integer, will pop the number specified * from the stack, if set to a negative integer will shift the number specified * from the stack. * @return {Boolean} * @private */ _updatePop: function (doc, val) { var updated = false, i; if (doc.length > 0) { if (val > 0) { for (i = 0; i < val; i++) { doc.pop(); } updated = true; } else if (val < 0) { for (i = 0; i > val; i--) { doc.shift(); } updated = true; } } return updated; } }; module.exports = Updating; },{}],26:[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":28,"./Shared":34}],27:[function(_dereq_,module,exports){ "use strict"; /** * Allows a method to accept overloaded calls with different parameters controlling * which passed overload function is called. * @param {String=} name A name to provide this overload to help identify * it if any errors occur during the resolving phase of the overload. This * is purely for debug purposes and serves no functional purpose. * @param {Object} def The overload definition. * @returns {Function} * @constructor */ var Overload = function (name, def) { if (!def) { def = name; name = undefined; } if (def) { var self = this, index, count, tmpDef, defNewKey, sigIndex, signatures; if (!(def instanceof Array)) { tmpDef = {}; // Def is an object, make sure all prop names are devoid of spaces for (index in def) { if (def.hasOwnProperty(index)) { defNewKey = index.replace(/ /g, ''); // Check if the definition array has a * string in it if (defNewKey.indexOf('*') === -1) { // No * found tmpDef[defNewKey] = def[index]; } else { // A * was found, generate the different signatures that this // definition could represent signatures = this.generateSignaturePermutations(defNewKey); for (sigIndex = 0; sigIndex < signatures.length; sigIndex++) { if (!tmpDef[signatures[sigIndex]]) { tmpDef[signatures[sigIndex]] = def[index]; } } } } } def = tmpDef; } return function () { var arr = [], lookup, type, overloadName; // Check if we are being passed a key/function object or an array of functions if (def instanceof Array) { // We were passed an array of functions count = def.length; for (index = 0; index < count; index++) { if (def[index].length === arguments.length) { return self.callExtend(this, '$main', def, def[index], arguments); } } } else { // Generate lookup key from arguments // Copy arguments to an array for (index = 0; index < arguments.length; index++) { type = typeof arguments[index]; // Handle detecting arrays if (type === 'object' && arguments[index] instanceof Array) { type = 'array'; } // Handle been presented with a single undefined argument if (arguments.length === 1 && type === 'undefined') { break; } // Add the type to the argument types array arr.push(type); } lookup = arr.join(','); // Check for an exact lookup match if (def[lookup]) { return self.callExtend(this, '$main', def, def[lookup], arguments); } else { for (index = arr.length; index >= 0; index--) { // Get the closest match lookup = arr.slice(0, index).join(','); if (def[lookup + ',...']) { // Matched against arguments + "any other" return self.callExtend(this, '$main', def, def[lookup + ',...'], arguments); } } } } overloadName = name !== undefined ? name : typeof this.name === 'function' ? this.name() : 'Unknown'; console.log('Overload Definition:', def); throw('ForerunnerDB.Overload "' + overloadName + '": Overloaded method does not have a matching signature "' + lookup + '" for the passed arguments: ' + this.jStringify(arr)); }; } return function () {}; }; /** * Generates an array of all the different definition signatures that can be * created from the passed string with a catch-all wildcard *. E.g. it will * convert the signature: string,*,string to all potentials: * string,string,string * string,number,string * string,object,string, * string,function,string, * string,undefined,string * * @param {String} str Signature string with a wildcard in it. * @returns {Array} An array of signature strings that are generated. */ Overload.prototype.generateSignaturePermutations = function (str) { var signatures = [], newSignature, types = ['array', 'string', 'object', 'number', 'function', 'undefined'], index; if (str.indexOf('*') > -1) { // There is at least one "any" type, break out into multiple keys // We could do this at query time with regular expressions but // would be significantly slower for (index = 0; index < types.length; index++) { newSignature = str.replace('*', types[index]); signatures = signatures.concat(this.generateSignaturePermutations(newSignature)); } } else { signatures.push(str); } return signatures; }; Overload.prototype.callExtend = function (context, prop, propContext, func, args) { var tmp, ret; if (context && propContext[prop]) { tmp = context[prop]; context[prop] = propContext[prop]; ret = func.apply(context, args); context[prop] = tmp; return ret; } else { return func.apply(context, args); } }; module.exports = Overload; },{}],28:[function(_dereq_,module,exports){ "use strict"; var Shared = _dereq_('./Shared'); /** * Path object used to resolve object paths and retrieve data from * objects by using paths. * @param {String=} path The path to assign. * @constructor */ var Path = function (path) { this.init.apply(this, arguments); }; Path.prototype.init = function (path) { if (path) { this.path(path); } }; Shared.addModule('Path', Path); Shared.mixin(Path.prototype, 'Mixin.Common'); Shared.mixin(Path.prototype, 'Mixin.ChainReactor'); /** * Gets / sets the given path for the Path instance. * @param {String=} path The path to assign. */ Path.prototype.path = function (path) { if (path !== undefined) { this._path = this.clean(path); this._pathParts = this._path.split('.'); return this; } return this._path; }; /** * Tests if the passed object has the paths that are specified and that * a value exists in those paths. * @param {Object} testKeys The object describing the paths to test for. * @param {Object} testObj The object to test paths against. * @returns {Boolean} True if the object paths exist. */ Path.prototype.hasObjectPaths = function (testKeys, testObj) { var result = true, i; for (i in testKeys) { if (testKeys.hasOwnProperty(i)) { if (testObj[i] === undefined) { return false; } if (typeof testKeys[i] === 'object') { // Recurse object result = this.hasObjectPaths(testKeys[i], testObj[i]); // Should we exit early? if (!result) { return false; } } } } return result; }; /** * Counts the total number of key endpoints in the passed object. * @param {Object} testObj The object to count key endpoints for. * @returns {Number} The number of endpoints. */ Path.prototype.countKeys = function (testObj) { var totalKeys = 0, i; for (i in testObj) { if (testObj.hasOwnProperty(i)) { if (testObj[i] !== undefined) { if (typeof testObj[i] !== 'object') { totalKeys++; } else { totalKeys += this.countKeys(testObj[i]); } } } } return totalKeys; }; /** * Tests if the passed object has the paths that are specified and that * a value exists in those paths and if so returns the number matched. * @param {Object} testKeys The object describing the paths to test for. * @param {Object} testObj The object to test paths against. * @returns {Object} Stats on the matched keys */ Path.prototype.countObjectPaths = function (testKeys, testObj) { var matchData, matchedKeys = {}, matchedKeyCount = 0, totalKeyCount = 0, i; for (i in testObj) { if (testObj.hasOwnProperty(i)) { if (typeof testObj[i] === 'object') { // The test / query object key is an object, recurse matchData = this.countObjectPaths(testKeys[i], testObj[i]); matchedKeys[i] = matchData.matchedKeys; totalKeyCount += matchData.totalKeyCount; matchedKeyCount += matchData.matchedKeyCount; } else { // The test / query object has a property that is not an object so add it as a key totalKeyCount++; // Check if the test keys also have this key and it is also not an object if (testKeys && testKeys[i] && typeof testKeys[i] !== 'object') { matchedKeys[i] = true; matchedKeyCount++; } else { matchedKeys[i] = false; } } } } return { matchedKeys: matchedKeys, matchedKeyCount: matchedKeyCount, totalKeyCount: totalKeyCount }; }; /** * Takes a non-recursive object and converts the object hierarchy into * a path string. * @param {Object} obj The object to parse. * @param {Boolean=} withValue If true will include a 'value' key in the returned * object that represents the value the object path points to. * @returns {Object} */ Path.prototype.parse = function (obj, withValue) { var paths = [], path = '', resultData, i, k; for (i in obj) { if (obj.hasOwnProperty(i)) { // Set the path to the key path = i; if (typeof(obj[i]) === 'object') { if (withValue) { resultData = this.parse(obj[i], withValue); for (k = 0; k < resultData.length; k++) { paths.push({ path: path + '.' + resultData[k].path, value: resultData[k].value }); } } else { resultData = this.parse(obj[i]); for (k = 0; k < resultData.length; k++) { paths.push({ path: path + '.' + resultData[k].path }); } } } else { if (withValue) { paths.push({ path: path, value: obj[i] }); } else { paths.push({ path: path }); } } } } return paths; }; /** * Takes a non-recursive object and converts the object hierarchy into * an array of path strings that allow you to target all possible paths * in an object. * * The options object accepts an "ignore" field with a regular expression * as the value. If any key matches the expression it is not included in * the results. * * The options object accepts a boolean "verbose" field. If set to true * the results will include all paths leading up to endpoints as well as * they endpoints themselves. * * @returns {Array} */ Path.prototype.parseArr = function (obj, options) { options = options || {}; return this._parseArr(obj, '', [], options); }; Path.prototype._parseArr = function (obj, path, paths, options) { var i, newPath = ''; path = path || ''; paths = paths || []; for (i in obj) { if (obj.hasOwnProperty(i)) { if (!options.ignore || (options.ignore && !options.ignore.test(i))) { if (path) { newPath = path + '.' + i; } else { newPath = i; } if (typeof(obj[i]) === 'object') { if (options.verbose) { paths.push(newPath); } this._parseArr(obj[i], newPath, paths, options); } else { paths.push(newPath); } } } } return paths; }; /** * Sets a value on an object for the specified path. * @param {Object} obj The object to update. * @param {String} path The path to update. * @param {*} val The value to set the object path to. * @returns {*} */ Path.prototype.set = function (obj, path, val) { if (obj !== undefined && path !== undefined) { var pathParts, part; path = this.clean(path); pathParts = path.split('.'); part = pathParts.shift(); if (pathParts.length) { // Generate the path part in the object if it does not already exist obj[part] = obj[part] || {}; // Recurse this.set(obj[part], pathParts.join('.'), val); } else { // Set the value obj[part] = val; } } return obj; }; /** * Gets a single value from the passed object and given path. * @param {Object} obj The object to inspect. * @param {String} path The path to retrieve data from. * @returns {*} */ Path.prototype.get = function (obj, path) { return this.value(obj, path)[0]; }; /** * Gets the value(s) that the object contains for the currently assigned path string. * @param {Object} obj The object to evaluate the path against. * @param {String=} path A path to use instead of the existing one passed in path(). * @param {Object=} options An optional options object. * @returns {Array} An array of values for the given path. */ Path.prototype.value = function (obj, path, options) { var pathParts, arr, arrCount, objPart, objPartParent, valuesArr, returnArr, i, k; // Detect early exit if (path && path.indexOf('.') === -1) { return [obj[path]]; } if (obj !== undefined && typeof obj === 'object') { if (!options || options && !options.skipArrCheck) { // Check if we were passed an array of objects and if so, // iterate over the array and return the value from each // array item if (obj instanceof Array) { returnArr = []; for (i = 0; i < obj.length; i++) { returnArr.push(this.get(obj[i], path)); } return returnArr; } } valuesArr = []; if (path !== undefined) { path = this.clean(path); pathParts = path.split('.'); } arr = pathParts || this._pathParts; arrCount = arr.length; objPart = obj; for (i = 0; i < arrCount; i++) { objPart = objPart[arr[i]]; if (objPartParent instanceof Array) { // Search inside the array for the next key for (k = 0; k < objPartParent.length; k++) { valuesArr = valuesArr.concat(this.value(objPartParent, k + '.' + arr[i], {skipArrCheck: true})); } return valuesArr; } else { if (!objPart || typeof(objPart) !== 'object') { break; } } objPartParent = objPart; } return [objPart]; } else { return []; } }; /** * Push a value to an array on an object for the specified path. * @param {Object} obj The object to update. * @param {String} path The path to the array to push to. * @param {*} val The value to push to the array at the object path. * @returns {*} */ Path.prototype.push = function (obj, path, val) { if (obj !== undefined && path !== undefined) { var pathParts, part; path = this.clean(path); pathParts = path.split('.'); part = pathParts.shift(); if (pathParts.length) { // Generate the path part in the object if it does not already exist obj[part] = obj[part] || {}; // Recurse this.set(obj[part], pathParts.join('.'), val); } else { // Set the value obj[part] = obj[part] || []; if (obj[part] instanceof Array) { obj[part].push(val); } else { throw('ForerunnerDB.Path: Cannot push to a path whose endpoint is not an array!'); } } } return obj; }; /** * Gets the value(s) that the object contains for the currently assigned path string * with their associated keys. * @param {Object} obj The object to evaluate the path against. * @param {String=} path A path to use instead of the existing one passed in path(). * @returns {Array} An array of values for the given path with the associated key. */ Path.prototype.keyValue = function (obj, path) { var pathParts, arr, arrCount, objPart, objPartParent, objPartHash, i; if (path !== undefined) { path = this.clean(path); pathParts = path.split('.'); } arr = pathParts || this._pathParts; arrCount = arr.length; objPart = obj; for (i = 0; i < arrCount; i++) { objPart = objPart[arr[i]]; if (!objPart || typeof(objPart) !== 'object') { objPartHash = arr[i] + ':' + objPart; break; } objPartParent = objPart; } return objPartHash; }; /** * Sets a value on an object for the specified path. * @param {Object} obj The object to update. * @param {String} path The path to update. * @param {*} val The value to set the object path to. * @returns {*} */ Path.prototype.set = function (obj, path, val) { if (obj !== undefined && path !== undefined) { var pathParts, part; path = this.clean(path); pathParts = path.split('.'); part = pathParts.shift(); if (pathParts.length) { // Generate the path part in the object if it does not already exist obj[part] = obj[part] || {}; // Recurse this.set(obj[part], pathParts.join('.'), val); } else { // Set the value obj[part] = val; } } return obj; }; /** * Removes leading period (.) from string and returns it. * @param {String} str The string to clean. * @returns {*} */ Path.prototype.clean = function (str) { if (str.substr(0, 1) === '.') { str = str.substr(1, str.length -1); } return str; }; Shared.finishModule('Path'); module.exports = Path; },{"./Shared":34}],29:[function(_dereq_,module,exports){ "use strict"; // Import external names locally var Shared = _dereq_('./Shared'), async = _dereq_('async'), localforage = _dereq_('localforage'), FdbCompress = _dereq_('./PersistCompress'),// jshint ignore:line FdbCrypto = _dereq_('./PersistCrypto'),// jshint ignore:line Db, Collection, CollectionDrop, CollectionGroup, CollectionInit, DbInit, DbDrop, Persist, Overload;//, //DataVersion = '2.0'; /** * The persistent storage class handles loading and saving data to browser * storage. * @constructor */ Persist = function () { this.init.apply(this, arguments); }; /** * The local forage library. */ Persist.prototype.localforage = localforage; /** * The init method that can be overridden or extended. * @param {Db} db The ForerunnerDB database instance. */ Persist.prototype.init = function (db) { var self = this; this._encodeSteps = [ function () { return self._encode.apply(self, arguments); } ]; this._decodeSteps = [ function () { return self._decode.apply(self, arguments); } ]; // Check environment if (db.isClient()) { if (window.Storage !== undefined) { this.mode('localforage'); localforage.config({ driver: [ localforage.INDEXEDDB, localforage.WEBSQL, localforage.LOCALSTORAGE ], name: String(db.core().name()), storeName: 'FDB' }); } } }; Shared.addModule('Persist', Persist); Shared.mixin(Persist.prototype, 'Mixin.ChainReactor'); Shared.mixin(Persist.prototype, 'Mixin.Common'); Db = Shared.modules.Db; Collection = _dereq_('./Collection'); CollectionDrop = Collection.prototype.drop; CollectionGroup = _dereq_('./CollectionGroup'); CollectionInit = Collection.prototype.init; DbInit = Db.prototype.init; DbDrop = Db.prototype.drop; Overload = Shared.overload; /** * Gets / sets the auto flag which determines if the persistence module * will automatically load data for collections the first time they are * accessed and save data whenever it changes. This is disabled by * default. * @param {Boolean} val Set to true to enable, false to disable * @returns {*} */ Shared.synthesize(Persist.prototype, 'auto', function (val) { var self = this; if (val !== undefined) { if (val) { // Hook db events this._db.on('create', function () { self._autoLoad.apply(self, arguments); }); this._db.on('change', function () { self._autoSave.apply(self, arguments); }); if (this._db.debug()) { console.log(this._db.logIdentifier() + ' Automatic load/save enabled'); } } else { // Un-hook db events this._db.off('create', this._autoLoad); this._db.off('change', this._autoSave); if (this._db.debug()) { console.log(this._db.logIdentifier() + ' Automatic load/save disbled'); } } } return this.$super.call(this, val); }); Persist.prototype._autoLoad = function (obj, objType, name) { var self = this; if (typeof obj.load === 'function') { if (self._db.debug()) { console.log(self._db.logIdentifier() + ' Auto-loading data for ' + objType + ':', name); } obj.load(function (err, data) { if (err && self._db.debug()) { console.log(self._db.logIdentifier() + ' Automatic load failed:', err); } self.emit('load', err, data); }); } else { if (self._db.debug()) { console.log(self._db.logIdentifier() + ' Auto-load for ' + objType + ':', name, 'no load method, skipping'); } } }; Persist.prototype._autoSave = function (obj, objType, name) { var self = this; if (typeof obj.save === 'function') { if (self._db.debug()) { console.log(self._db.logIdentifier() + ' Auto-saving data for ' + objType + ':', name); } obj.save(function (err, data) { if (err && self._db.debug()) { console.log(self._db.logIdentifier() + ' Automatic save failed:', err); } self.emit('save', err, data); }); } }; /** * Gets / sets the persistent storage mode (the library used * to persist data to the browser - defaults to localForage). * @param {String} type The library to use for storage. Defaults * to localForage. * @returns {*} */ Persist.prototype.mode = function (type) { if (type !== undefined) { this._mode = type; return this; } return this._mode; }; /** * Gets / sets the driver used when persisting data. * @param {String} val Specify the driver type (LOCALSTORAGE, * WEBSQL or INDEXEDDB) * @returns {*} */ Persist.prototype.driver = function (val) { if (val !== undefined) { switch (val.toUpperCase()) { case 'LOCALSTORAGE': localforage.setDriver(localforage.LOCALSTORAGE); break; case 'WEBSQL': localforage.setDriver(localforage.WEBSQL); break; case 'INDEXEDDB': localforage.setDriver(localforage.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 localforage.driver(); }; /** * Starts a decode waterfall process. * @param {*} val The data to be decoded. * @param {Function} finished The callback to pass final data to. */ Persist.prototype.decode = function (val, finished) { async.waterfall([function (callback) { if (callback) { callback(false, val, {}); } }].concat(this._decodeSteps), finished); }; /** * Starts an encode waterfall process. * @param {*} val The data to be encoded. * @param {Function} finished The callback to pass final data to. */ Persist.prototype.encode = function (val, finished) { async.waterfall([function (callback) { if (callback) { callback(false, val, {}); } }].concat(this._encodeSteps), finished); }; Shared.synthesize(Persist.prototype, 'encodeSteps'); Shared.synthesize(Persist.prototype, 'decodeSteps'); /** * Adds an encode/decode step to the persistent storage system so * that you can add custom functionality. * @param {Function} encode The encode method called with the data from the * previous encode step. When your method is complete it MUST call the * callback method. If you provide anything other than false to the err * parameter the encoder will fail and throw an error. * @param {Function} decode The decode method called with the data from the * previous decode step. When your method is complete it MUST call the * callback method. If you provide anything other than false to the err * parameter the decoder will fail and throw an error. * @param {Number=} index Optional index to add the encoder step to. This * allows you to place a step before or after other existing steps. If not * provided your step is placed last in the list of steps. For instance if * you are providing an encryption step it makes sense to place this last * since all previous steps will then have their data encrypted by your * final step. */ Persist.prototype.addStep = new Overload({ 'object': function (obj) { this.$main.call(this, function objEncode () { obj.encode.apply(obj, arguments); }, function objDecode () { obj.decode.apply(obj, arguments); }, 0); }, 'function, function': function (encode, decode) { this.$main.call(this, encode, decode, 0); }, 'function, function, number': function (encode, decode, index) { this.$main.call(this, encode, decode, index); }, $main: function (encode, decode, index) { if (index === 0 || index === undefined) { this._encodeSteps.push(encode); this._decodeSteps.unshift(decode); } else { // Place encoder step at index then work out correct // index to place decoder step this._encodeSteps.splice(index, 0, encode); this._decodeSteps.splice(this._decodeSteps.length - index, 0, decode); } } }); Persist.prototype.unwrap = function (dataStr) { var parts = dataStr.split('::fdb::'), data; switch (parts[0]) { case 'json': data = this.jParse(parts[1]); break; case 'raw': data = parts[1]; break; default: break; } }; /** * Takes encoded data and decodes it for use as JS native objects and arrays. * @param {String} val The currently encoded string data. * @param {Object} meta Meta data object that can be used to pass back useful * supplementary data. * @param {Function} finished The callback method to call when decoding is * completed. * @private */ Persist.prototype._decode = function (val, meta, finished) { var parts, data; if (val) { parts = val.split('::fdb::'); switch (parts[0]) { case 'json': data = this.jParse(parts[1]); break; case 'raw': data = parts[1]; break; default: break; } if (data) { meta.foundData = true; meta.rowCount = data.length || 0; } else { meta.foundData = false; meta.rowCount = 0; } if (finished) { finished(false, data, meta); } } else { meta.foundData = false; meta.rowCount = 0; if (finished) { finished(false, val, meta); } } }; /** * Takes native JS data and encodes it for for storage as a string. * @param {Object} val The current un-encoded data. * @param {Object} meta Meta data object that can be used to pass back useful * supplementary data. * @param {Function} finished The callback method to call when encoding is * completed. * @private */ Persist.prototype._encode = function (val, meta, finished) { var data = val; if (typeof val === 'object') { val = 'json::fdb::' + this.jStringify(val); } else { val = 'raw::fdb::' + val; } if (data) { meta.foundData = true; meta.rowCount = data.length || 0; } else { meta.foundData = false; meta.rowCount = 0; } if (finished) { finished(false, val, meta); } }; /** * Encodes passed data and then stores it in the browser's persistent * storage layer. * @param {String} key The key to store the data under in the persistent * storage. * @param {Object} data The data to store under the key. * @param {Function=} callback The method to call when the save process * has completed. */ Persist.prototype.save = function (key, data, callback) { switch (this.mode()) { case 'localforage': this.encode(data, function (err, data, tableStats) { if (!err) { localforage.setItem(key, data).then(function (data) { if (callback) { callback(false, data, tableStats); } }, function (err) { if (callback) { callback(err); } }); } else { callback(err); } }); break; default: if (callback) { callback('No data handler.'); } break; } }; /** * Loads and decodes data from the passed key. * @param {String} key The key to retrieve data from in the persistent * storage. * @param {Function=} callback The method to call when the load process * has completed. */ Persist.prototype.load = function (key, callback) { var self = this; switch (this.mode()) { case 'localforage': localforage.getItem(key).then(function (val) { self.decode(val, callback); }, function (err) { if (callback) { callback(err); } }); break; default: if (callback) { callback('No data handler or unrecognised data type.'); } break; } }; /** * Deletes data in persistent storage stored under the passed key. * @param {String} key The key to drop data for in the storage. * @param {Function=} callback The method to call when the data is dropped. */ Persist.prototype.drop = function (key, callback) { switch (this.mode()) { case 'localforage': localforage.removeItem(key).then(function () { if (callback) { callback(false); } }, function (err) { if (callback) { callback(err); } }); break; default: if (callback) { callback('No data handler or unrecognised data type.'); } break; } }; // Extend the Collection prototype with persist methods Collection.prototype.drop = new Overload({ /** * Drop collection and persistent storage. */ '': function () { if (!this.isDropped()) { this.drop(true); } }, /** * Drop collection and persistent storage with callback. * @param {Function} callback Callback method. */ 'function': function (callback) { if (!this.isDropped()) { this.drop(true, callback); } }, /** * Drop collection and optionally drop persistent storage. * @param {Boolean} removePersistent True to drop persistent storage, false to keep it. */ 'boolean': function (removePersistent) { if (!this.isDropped()) { // Remove persistent storage if (removePersistent) { if (this._name) { if (this._db) { // Drop the collection data from storage this._db.persist.drop(this._db._name + '-' + this._name); this._db.persist.drop(this._db._name + '-' + this._name + '-metaData'); } } else { throw('ForerunnerDB.Persist: Cannot drop a collection\'s persistent storage when no name assigned to collection!'); } } // Call the original method CollectionDrop.call(this); } }, /** * Drop collections and optionally drop persistent storage with callback. * @param {Boolean} removePersistent True to drop persistent storage, false to keep it. * @param {Function} callback Callback method. */ 'boolean, function': function (removePersistent, callback) { var self = this; if (!this.isDropped()) { // Remove persistent storage if (removePersistent) { if (this._name) { if (this._db) { // Drop the collection data from storage this._db.persist.drop(this._db._name + '-' + this._name, function () { self._db.persist.drop(self._db._name + '-' + self._name + '-metaData', callback); }); return CollectionDrop.call(this); } else { if (callback) { callback('Cannot drop a collection\'s persistent storage when the collection is not attached to a database!'); } } } else { if (callback) { callback('Cannot drop a collection\'s persistent storage when no name assigned to collection!'); } } } else { // Call the original method return CollectionDrop.call(this, callback); } } } }); /** * Saves an entire collection's data to persistent storage. * @param {Function=} callback The method to call when the save function * has completed. */ Collection.prototype.save = function (callback) { var self = this, processSave; if (self._name) { if (self._db) { processSave = function () { // Save the collection data self._db.persist.save(self._db._name + '-' + self._name, self._data, function (err, tableData, tableStats) { if (!err) { self._db.persist.save(self._db._name + '-' + self._name + '-metaData', self.metaData(), function (err, metaData, metaStats) { if (callback) { callback(err, tableStats, metaStats, { tableData: tableData, metaData: metaData, tableDataName: self._db._name + '-' + self._name, metaDataName: self._db._name + '-' + self._name + '-metaData' }); } }); } else { if (callback) { callback(err); } } }); }; // Check for processing queues if (self.isProcessingQueue()) { // Hook queue complete to process save self.on('queuesComplete', function () { processSave(); }); } else { // Process save immediately processSave(); } } else { if (callback) { callback('Cannot save a collection that is not attached to a database!'); } } } else { if (callback) { callback('Cannot save a collection with no assigned name!'); } } }; /** * Loads an entire collection's data from persistent storage. * @param {Function=} callback The method to call when the load function * has completed. */ Collection.prototype.load = function (callback) { var self = this; if (self._name) { if (self._db) { // Load the collection data self._db.persist.load(self._db._name + '-' + self._name, function (err, data, tableStats) { if (!err) { // Remove all previous data self.remove({}, function () { // Now insert the new data data = data || []; self.insert(data, function () { // Now load the collection's metadata self._db.persist.load(self._db._name + '-' + self._name + '-metaData', function (err, data, metaStats) { if (!err) { if (data) { self.metaData(data); } } if (callback) { callback(err, tableStats, metaStats); } }); }); //self.setData(data); }); } else { if (callback) { callback(err); } } }); } else { if (callback) { callback('Cannot load a collection that is not attached to a database!'); } } } else { if (callback) { callback('Cannot load a collection with no assigned name!'); } } }; /** * Gets the data that represents this collection for easy storage using * a third-party method / plugin instead of using the standard persistent * storage system. * @param {Function} callback The method to call with the data response. */ Collection.prototype.saveCustom = function (callback) { var self = this, myData = {}, processSave; if (self._name) { if (self._db) { processSave = function () { self.encode(self._data, function (err, data, tableStats) { if (!err) { myData.data = { name: self._db._name + '-' + self._name, store: data, tableStats: tableStats }; self.encode(self._data, function (err, data, tableStats) { if (!err) { myData.metaData = { name: self._db._name + '-' + self._name + '-metaData', store: data, tableStats: tableStats }; callback(false, myData); } else { callback(err); } }); } else { callback(err); } }); }; // Check for processing queues if (self.isProcessingQueue()) { // Hook queue complete to process save self.on('queuesComplete', function () { processSave(); }); } else { // Process save immediately processSave(); } } else { if (callback) { callback('Cannot save a collection that is not attached to a database!'); } } } else { if (callback) { callback('Cannot save a collection with no assigned name!'); } } }; /** * Loads custom data loaded by a third-party plugin into the collection. * @param {Object} myData Data object previously saved by using saveCustom() * @param {Function} callback A callback method to receive notification when * data has loaded. */ Collection.prototype.loadCustom = function (myData, callback) { var self = this; if (self._name) { if (self._db) { if (myData.data && myData.data.store) { if (myData.metaData && myData.metaData.store) { self.decode(myData.data.store, function (err, data, tableStats) { if (!err) { if (data) { // Remove all previous data self.remove({}); self.insert(data); self.decode(myData.metaData.store, function (err, data, metaStats) { if (!err) { if (data) { self.metaData(data); if (callback) { callback(err, tableStats, metaStats); } } } else { callback(err); } }); } } else { callback(err); } }); } else { callback('No "metaData" key found in passed object!'); } } else { callback('No "data" key found in passed object!'); } } else { if (callback) { callback('Cannot load a collection that is not attached to a database!'); } } } else { if (callback) { callback('Cannot load a collection with no assigned name!'); } } }; // Override the DB init to instantiate the plugin Db.prototype.init = function () { DbInit.apply(this, arguments); this.persist = new Persist(this); }; Db.prototype.load = new Overload({ /** * Loads an entire database's data from persistent storage. * @param {Function=} callback The method to call when the load function * has completed. */ 'function': function (callback) { this.$main.call(this, {}, callback); }, 'object, function': function (myData, callback) { this.$main.call(this, myData, callback); }, '$main': function (myData, callback) { // Loop the collections in the database var obj = this._collection, keys = obj.keys(), keyCount = keys.length, loadCallback, index; loadCallback = function (err) { if (!err) { keyCount--; if (keyCount === 0) { if (callback) { callback(false); } } } else { if (callback) { callback(err); } } }; for (index in obj) { if (obj.hasOwnProperty(index)) { // Call the collection load method if (!myData) { obj[index].load(loadCallback); } else { obj[index].loadCustom(myData, loadCallback); } } } } }); Db.prototype.save = new Overload({ /** * Saves an entire database's data to persistent storage. * @param {Function=} callback The method to call when the save function * has completed. */ 'function': function (callback) { this.$main.call(this, {}, callback); }, 'object, function': function (options, callback) { this.$main.call(this, options, callback); }, '$main': function (options, callback) { // Loop the collections in the database var obj = this._collection, keys = obj.keys(), keyCount = keys.length, saveCallback, index; saveCallback = function (err) { if (!err) { keyCount--; if (keyCount === 0) { if (callback) { callback(false); } } } else { if (callback) { callback(err); } } }; for (index in obj) { if (obj.hasOwnProperty(index)) { // Call the collection save method if (!options.custom) { obj[index].save(saveCallback); } else { obj[index].saveCustom(saveCallback); } } } } }); Shared.finishModule('Persist'); module.exports = Persist; },{"./Collection":5,"./CollectionGroup":6,"./PersistCompress":30,"./PersistCrypto":31,"./Shared":34,"async":37,"localforage":75}],30:[function(_dereq_,module,exports){ "use strict"; var Shared = _dereq_('./Shared'), pako = _dereq_('pako'); var Plugin = function () { this.init.apply(this, arguments); }; Plugin.prototype.init = function (options) { }; Shared.mixin(Plugin.prototype, 'Mixin.Common'); Plugin.prototype.encode = function (val, meta, finished) { var wrapper = { data: val, type: 'fdbCompress', enabled: false }, before, after, compressedVal; // Compress the data before = val.length; compressedVal = pako.deflate(val, {to: 'string'}); after = compressedVal.length; // If the compressed version is smaller than the original, use it! if (after < before) { wrapper.data = compressedVal; wrapper.enabled = true; } meta.compression = { enabled: wrapper.enabled, compressedBytes: after, uncompressedBytes: before, effect: Math.round((100 / before) * after) + '%' }; finished(false, this.jStringify(wrapper), meta); }; Plugin.prototype.decode = function (wrapper, meta, finished) { var compressionEnabled = false, data; if (wrapper) { wrapper = this.jParse(wrapper); // Check if we need to decompress the string if (wrapper.enabled) { data = pako.inflate(wrapper.data, {to: 'string'}); compressionEnabled = true; } else { data = wrapper.data; compressionEnabled = false; } meta.compression = { enabled: compressionEnabled }; if (finished) { finished(false, data, meta); } } else { if (finished) { finished(false, data, meta); } } }; // Register this plugin with ForerunnerDB Shared.plugins.FdbCompress = Plugin; module.exports = Plugin; },{"./Shared":34,"pako":77}],31:[function(_dereq_,module,exports){ "use strict"; var Shared = _dereq_('./Shared'), CryptoJS = _dereq_('crypto-js'); var Plugin = function () { this.init.apply(this, arguments); }; Plugin.prototype.init = function (options) { // Ensure at least a password is passed in options if (!options || !options.pass) { throw('Cannot initialise persistent storage encryption without a passphrase provided in the passed options object as the "pass" field.'); } this._algo = options.algo || 'AES'; this._pass = options.pass; }; Shared.mixin(Plugin.prototype, 'Mixin.Common'); /** * Gets / sets the current pass-phrase being used to encrypt / decrypt * data with the plugin. */ Shared.synthesize(Plugin.prototype, 'pass'); Plugin.prototype.stringify = function (cipherParams) { // create json object with ciphertext var jsonObj = { ct: cipherParams.ciphertext.toString(CryptoJS.enc.Base64) }; // optionally add iv and salt if (cipherParams.iv) { jsonObj.iv = cipherParams.iv.toString(); } if (cipherParams.salt) { jsonObj.s = cipherParams.salt.toString(); } // stringify json object return this.jStringify(jsonObj); }; Plugin.prototype.parse = function (jsonStr) { // parse json string var jsonObj = this.jParse(jsonStr); // extract ciphertext from json object, and create cipher params object var cipherParams = CryptoJS.lib.CipherParams.create({ ciphertext: CryptoJS.enc.Base64.parse(jsonObj.ct) }); // optionally extract iv and salt if (jsonObj.iv) { cipherParams.iv = CryptoJS.enc.Hex.parse(jsonObj.iv); } if (jsonObj.s) { cipherParams.salt = CryptoJS.enc.Hex.parse(jsonObj.s); } return cipherParams; }; Plugin.prototype.encode = function (val, meta, finished) { var self = this, wrapper = { type: 'fdbCrypto' }, encryptedVal; // Encrypt the data encryptedVal = CryptoJS[this._algo].encrypt(val, this._pass, { format: { stringify: function () { return self.stringify.apply(self, arguments); }, parse: function () { return self.parse.apply(self, arguments); } } }); wrapper.data = encryptedVal.toString(); wrapper.enabled = true; meta.encryption = { enabled: wrapper.enabled }; if (finished) { finished(false, this.jStringify(wrapper), meta); } }; Plugin.prototype.decode = function (wrapper, meta, finished) { var self = this, data; if (wrapper) { wrapper = this.jParse(wrapper); data = CryptoJS[this._algo].decrypt(wrapper.data, this._pass, { format: { stringify: function () { return self.stringify.apply(self, arguments); }, parse: function () { return self.parse.apply(self, arguments); } } }).toString(CryptoJS.enc.Utf8); if (finished) { finished(false, data, meta); } } else { if (finished) { finished(false, wrapper, meta); } } }; // Register this plugin with ForerunnerDB Shared.plugins.FdbCrypto = Plugin; module.exports = Plugin; },{"./Shared":34,"crypto-js":46}],32:[function(_dereq_,module,exports){ "use strict"; var Shared = _dereq_('./Shared'); /** * Provides chain reactor node linking so that a chain reaction can propagate * down a node tree. Effectively creates a chain link between the reactorIn and * reactorOut objects where a chain reaction from the reactorIn is passed through * the reactorProcess before being passed to the reactorOut object. Reactor * packets are only passed through to the reactorOut if the reactor IO method * chainSend is used. * @param {*} reactorIn An object that has the Mixin.ChainReactor methods mixed * in to it. Chain reactions that occur inside this object will be passed through * to the reactorOut object. * @param {*} reactorOut An object that has the Mixin.ChainReactor methods mixed * in to it. Chain reactions that occur in the reactorIn object will be passed * through to this object. * @param {Function} reactorProcess The processing method to use when chain * reactions occur. * @constructor */ var ReactorIO = function (reactorIn, reactorOut, reactorProcess) { if (reactorIn && reactorOut && reactorProcess) { this._reactorIn = reactorIn; this._reactorOut = reactorOut; this._chainHandler = reactorProcess; if (!reactorIn.chain) { throw('ForerunnerDB.ReactorIO: ReactorIO requires passed in and out objects to implement the ChainReactor mixin!'); } // Register the reactorIO with the input reactorIn.chain(this); // Register the output with the reactorIO this.chain(reactorOut); } else { throw('ForerunnerDB.ReactorIO: ReactorIO requires in, out and process arguments to instantiate!'); } }; Shared.addModule('ReactorIO', ReactorIO); /** * Drop a reactor IO object, breaking the reactor link between the in and out * reactor nodes. * @returns {boolean} */ ReactorIO.prototype.drop = function () { if (!this.isDropped()) { this._state = 'dropped'; // Remove links if (this._reactorIn) { this._reactorIn.unChain(this); } if (this._reactorOut) { this.unChain(this._reactorOut); } delete this._reactorIn; delete this._reactorOut; delete this._chainHandler; this.emit('drop', this); delete this._listeners; } return true; }; /** * Gets / sets the current state. * @param {String=} val The name of the state to set. * @returns {*} */ Shared.synthesize(ReactorIO.prototype, 'state'); Shared.mixin(ReactorIO.prototype, 'Mixin.Common'); Shared.mixin(ReactorIO.prototype, 'Mixin.ChainReactor'); Shared.mixin(ReactorIO.prototype, 'Mixin.Events'); Shared.finishModule('ReactorIO'); module.exports = ReactorIO; },{"./Shared":34}],33:[function(_dereq_,module,exports){ "use strict"; /** * Provides functionality to encode and decode JavaScript objects to strings * and back again. This differs from JSON.stringify and JSON.parse in that * special objects such as dates can be encoded to strings and back again * so that the reconstituted version of the string still contains a JavaScript * date object. * @constructor */ var Serialiser = function () { this.init.apply(this, arguments); }; Serialiser.prototype.init = function () { var self = this; this._encoder = []; this._decoder = []; // Handler for Date() objects this.registerHandler('$date', function (objInstance) { if (objInstance instanceof Date) { // Augment this date object with a new toJSON method objInstance.toJSON = function () { return "$date:" + this.toISOString(); }; // Tell the converter we have matched this object return true; } // Tell converter to keep looking, we didn't match this object return false; }, function (data) { if (typeof data === 'string' && data.indexOf('$date:') === 0) { return self.convert(new Date(data.substr(6))); } return undefined; }); // Handler for RegExp() objects this.registerHandler('$regexp', function (objInstance) { if (objInstance instanceof RegExp) { objInstance.toJSON = function () { return "$regexp:" + this.source.length + ":" + this.source + ":" + (this.global ? 'g' : '') + (this.ignoreCase ? 'i' : ''); /*return { source: this.source, params: '' + (this.global ? 'g' : '') + (this.ignoreCase ? 'i' : '') };*/ }; // Tell the converter we have matched this object return true; } // Tell converter to keep looking, we didn't match this object return false; }, function (data) { if (typeof data === 'string' && data.indexOf('$regexp:') === 0) { var dataStr = data.substr(8),//± lengthEnd = dataStr.indexOf(':'), sourceLength = Number(dataStr.substr(0, lengthEnd)), source = dataStr.substr(lengthEnd + 1, sourceLength), params = dataStr.substr(lengthEnd + sourceLength + 2); return self.convert(new RegExp(source, params)); } return undefined; }); }; Serialiser.prototype.registerHandler = function (handles, encoder, decoder) { if (handles !== undefined) { // Register encoder this._encoder.push(encoder); // Register decoder this._decoder.push(decoder); } }; Serialiser.prototype.convert = function (data) { // Run through converters and check for match var arr = this._encoder, i; for (i = 0; i < arr.length; i++) { if (arr[i](data)) { // The converter we called matched the object and converted it // so let's return it now. return data; } } // No converter matched the object, return the unaltered one return data; }; Serialiser.prototype.reviver = function () { var arr = this._decoder; return function (key, value) { // Check if we have a decoder method for this key var decodedData, i; for (i = 0; i < arr.length; i++) { decodedData = arr[i](value); if (decodedData !== undefined) { // The decoder we called matched the object and decoded it // so let's return it now. return decodedData; } } // No decoder, return basic value return value; }; }; module.exports = Serialiser; },{}],34:[function(_dereq_,module,exports){ "use strict"; var Overload = _dereq_('./Overload'); /** * A shared object that can be used to store arbitrary data between class * instances, and access helper methods. * @mixin */ var Shared = { version: '1.3.832', modules: {}, plugins: {}, index: {}, _synth: {}, /** * Adds a module to ForerunnerDB. * @memberof Shared * @param {String} name The name of the module. * @param {Function} module The module class. */ addModule: function (name, module) { // Store the module in the module registry this.modules[name] = module; // Tell the universe we are loading this module this.emit('moduleLoad', [name, module]); }, /** * Called by the module once all processing has been completed. Used to determine * if the module is ready for use by other modules. * @memberof Shared * @param {String} name The name of the module. */ finishModule: function (name) { if (this.modules[name]) { // Set the finished loading flag to true this.modules[name]._fdbFinished = true; // Assign the module name to itself so it knows what it // is called if (this.modules[name].prototype) { this.modules[name].prototype.className = name; } else { this.modules[name].className = name; } this.emit('moduleFinished', [name, this.modules[name]]); } else { throw('ForerunnerDB.Shared: finishModule called on a module that has not been registered with addModule(): ' + name); } }, /** * Will call your callback method when the specified module has loaded. If the module * is already loaded the callback is called immediately. * @memberof Shared * @param {String} name The name of the module. * @param {Function} callback The callback method to call when the module is loaded. */ moduleFinished: function (name, callback) { if (this.modules[name] && this.modules[name]._fdbFinished) { if (callback) { callback(name, this.modules[name]); } } else { this.on('moduleFinished', callback); } }, /** * Determines if a module has been added to ForerunnerDB or not. * @memberof Shared * @param {String} name The name of the module. * @returns {Boolean} True if the module exists or false if not. */ moduleExists: function (name) { return Boolean(this.modules[name]); }, mixin: new Overload({ /** * Adds the properties and methods defined in the mixin to the passed * object. * @memberof Shared * @name mixin * @param {Object} obj The target object to add mixin key/values to. * @param {String} mixinName The name of the mixin to add to the object. */ 'object, string': function (obj, mixinName) { var mixinObj; if (typeof mixinName === 'string') { mixinObj = this.mixins[mixinName]; if (!mixinObj) { throw('ForerunnerDB.Shared: Cannot find mixin named: ' + mixinName); } } return this.$main.call(this, obj, mixinObj); }, /** * Adds the properties and methods defined in the mixin to the passed * object. * @memberof Shared * @name mixin * @param {Object} obj The target object to add mixin key/values to. * @param {Object} mixinObj The object containing the keys to mix into * the target object. */ 'object, *': function (obj, mixinObj) { return this.$main.call(this, obj, mixinObj); }, '$main': function (obj, mixinObj) { if (mixinObj && typeof mixinObj === 'object') { for (var i in mixinObj) { if (mixinObj.hasOwnProperty(i)) { obj[i] = mixinObj[i]; } } } return obj; } }), /** * Generates a generic getter/setter method for the passed method name. * @memberof Shared * @param {Object} obj The object to add the getter/setter to. * @param {String} name The name of the getter/setter to generate. * @param {Function=} extend A method to call before executing the getter/setter. * The existing getter/setter can be accessed from the extend method via the * $super e.g. this.$super(); */ synthesize: function (obj, name, extend) { this._synth[name] = this._synth[name] || function (val) { if (val !== undefined) { this['_' + name] = val; return this; } return this['_' + name]; }; if (extend) { var self = this; obj[name] = function () { var tmp = this.$super, ret; this.$super = self._synth[name]; ret = extend.apply(this, arguments); this.$super = tmp; return ret; }; } else { obj[name] = this._synth[name]; } }, /** * Allows a method to be overloaded. * @memberof Shared * @param arr * @returns {Function} * @constructor */ overload: Overload, /** * Define the mixins that other modules can use as required. * @memberof Shared */ mixins: { 'Mixin.Common': _dereq_('./Mixin.Common'), 'Mixin.Events': _dereq_('./Mixin.Events'), 'Mixin.ChainReactor': _dereq_('./Mixin.ChainReactor'), 'Mixin.CRUD': _dereq_('./Mixin.CRUD'), 'Mixin.Constants': _dereq_('./Mixin.Constants'), 'Mixin.Triggers': _dereq_('./Mixin.Triggers'), 'Mixin.Sorting': _dereq_('./Mixin.Sorting'), 'Mixin.Matching': _dereq_('./Mixin.Matching'), 'Mixin.Updating': _dereq_('./Mixin.Updating'), 'Mixin.Tags': _dereq_('./Mixin.Tags') } }; // Add event handling to shared Shared.mixin(Shared, 'Mixin.Events'); module.exports = Shared; },{"./Mixin.CRUD":16,"./Mixin.ChainReactor":17,"./Mixin.Common":18,"./Mixin.Constants":19,"./Mixin.Events":20,"./Mixin.Matching":21,"./Mixin.Sorting":22,"./Mixin.Tags":23,"./Mixin.Triggers":24,"./Mixin.Updating":25,"./Overload":27}],35:[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 = {}; },{}],36:[function(_dereq_,module,exports){ (function (process){ // Use the fastest possible means to execute a task in a future turn // of the event loop. // linked list of tasks (single, with head node) var head = {task: void 0, next: null}; var tail = head; var flushing = false; var requestFlush = void 0; var isNodeJS = false; function flush() { /* jshint loopfunc: true */ while (head.next) { head = head.next; var task = head.task; head.task = void 0; var domain = head.domain; if (domain) { head.domain = void 0; domain.enter(); } try { task(); } catch (e) { if (isNodeJS) { // In node, uncaught exceptions are considered fatal errors. // Re-throw them synchronously to interrupt flushing! // Ensure continuation if the uncaught exception is suppressed // listening "uncaughtException" events (as domains does). // Continue in next event to avoid tick recursion. if (domain) { domain.exit(); } setTimeout(flush, 0); if (domain) { domain.enter(); } throw e; } else { // In browsers, uncaught exceptions are not fatal. // Re-throw them asynchronously to avoid slow-downs. setTimeout(function() { throw e; }, 0); } } if (domain) { domain.exit(); } } flushing = false; } if (typeof process !== "undefined" && process.nextTick) { // Node.js before 0.9. Note that some fake-Node environments, like the // Mocha test runner, introduce a `process` global without a `nextTick`. isNodeJS = true; requestFlush = function () { process.nextTick(flush); }; } else if (typeof setImmediate === "function") { // In IE10, Node.js 0.9+, or https://github.com/NobleJS/setImmediate if (typeof window !== "undefined") { requestFlush = setImmediate.bind(window, flush); } else { requestFlush = function () { setImmediate(flush); }; } } else if (typeof MessageChannel !== "undefined") { // modern browsers // http://www.nonblocking.io/2011/06/windownexttick.html var channel = new MessageChannel(); channel.port1.onmessage = flush; requestFlush = function () { channel.port2.postMessage(0); }; } else { // old browsers requestFlush = function () { setTimeout(flush, 0); }; } function asap(task) { tail = tail.next = { task: task, domain: isNodeJS && process.domain, next: null }; if (!flushing) { flushing = true; requestFlush(); } }; module.exports = asap; }).call(this,_dereq_('_process')) },{"_process":93}],37:[function(_dereq_,module,exports){ (function (process,global){ /*! * async * https://github.com/caolan/async * * Copyright 2010-2014 Caolan McMahon * Released under the MIT license */ (function () { var async = {}; function noop() {} function identity(v) { return v; } function toBool(v) { return !!v; } function notId(v) { return !v; } // global on the server, window in the browser var previous_async; // Establish the root object, `window` (`self`) in the browser, `global` // on the server, or `this` in some virtual machines. We use `self` // instead of `window` for `WebWorker` support. var root = typeof self === 'object' && self.self === self && self || typeof global === 'object' && global.global === global && global || this; if (root != null) { previous_async = root.async; } async.noConflict = function () { root.async = previous_async; return async; }; function only_once(fn) { return function() { if (fn === null) throw new Error("Callback was already called."); fn.apply(this, arguments); fn = null; }; } function _once(fn) { return function() { if (fn === null) return; fn.apply(this, arguments); fn = null; }; } //// cross-browser compatiblity functions //// var _toString = Object.prototype.toString; var _isArray = Array.isArray || function (obj) { return _toString.call(obj) === '[object Array]'; }; // Ported from underscore.js isObject var _isObject = function(obj) { var type = typeof obj; return type === 'function' || type === 'object' && !!obj; }; function _isArrayLike(arr) { return _isArray(arr) || ( // has a positive integer length property typeof arr.length === "number" && arr.length >= 0 && arr.length % 1 === 0 ); } function _arrayEach(arr, iterator) { var index = -1, length = arr.length; while (++index < length) { iterator(arr[index], index, arr); } } function _map(arr, iterator) { var index = -1, length = arr.length, result = Array(length); while (++index < length) { result[index] = iterator(arr[index], index, arr); } return result; } function _range(count) { return _map(Array(count), function (v, i) { return i; }); } function _reduce(arr, iterator, memo) { _arrayEach(arr, function (x, i, a) { memo = iterator(memo, x, i, a); }); return memo; } function _forEachOf(object, iterator) { _arrayEach(_keys(object), function (key) { iterator(object[key], key); }); } function _indexOf(arr, item) { for (var i = 0; i < arr.length; i++) { if (arr[i] === item) return i; } return -1; } var _keys = Object.keys || function (obj) { var keys = []; for (var k in obj) { if (obj.hasOwnProperty(k)) { keys.push(k); } } return keys; }; function _keyIterator(coll) { var i = -1; var len; var keys; if (_isArrayLike(coll)) { len = coll.length; return function next() { i++; return i < len ? i : null; }; } else { keys = _keys(coll); len = keys.length; return function next() { i++; return i < len ? keys[i] : null; }; } } // Similar to ES6's rest param (http://ariya.ofilabs.com/2013/03/es6-and-rest-parameter.html) // This accumulates the arguments passed into an array, after a given index. // From underscore.js (https://github.com/jashkenas/underscore/pull/2140). function _restParam(func, startIndex) { startIndex = startIndex == null ? func.length - 1 : +startIndex; return function() { var length = Math.max(arguments.length - startIndex, 0); var rest = Array(length); for (var index = 0; index < length; index++) { rest[index] = arguments[index + startIndex]; } switch (startIndex) { case 0: return func.call(this, rest); case 1: return func.call(this, arguments[0], rest); } // Currently unused but handle cases outside of the switch statement: // var args = Array(startIndex + 1); // for (index = 0; index < startIndex; index++) { // args[index] = arguments[index]; // } // args[startIndex] = rest; // return func.apply(this, args); }; } function _withoutIndex(iterator) { return function (value, index, callback) { return iterator(value, callback); }; } //// exported async module functions //// //// nextTick implementation with browser-compatible fallback //// // capture the global reference to guard against fakeTimer mocks var _setImmediate = typeof setImmediate === 'function' && setImmediate; var _delay = _setImmediate ? function(fn) { // not a direct alias for IE10 compatibility _setImmediate(fn); } : function(fn) { setTimeout(fn, 0); }; if (typeof process === 'object' && typeof process.nextTick === 'function') { async.nextTick = process.nextTick; } else { async.nextTick = _delay; } async.setImmediate = _setImmediate ? _delay : async.nextTick; async.forEach = async.each = function (arr, iterator, callback) { return async.eachOf(arr, _withoutIndex(iterator), callback); }; async.forEachSeries = async.eachSeries = function (arr, iterator, callback) { return async.eachOfSeries(arr, _withoutIndex(iterator), callback); }; async.forEachLimit = async.eachLimit = function (arr, limit, iterator, callback) { return _eachOfLimit(limit)(arr, _withoutIndex(iterator), callback); }; async.forEachOf = async.eachOf = function (object, iterator, callback) { callback = _once(callback || noop); object = object || []; var iter = _keyIterator(object); var key, completed = 0; while ((key = iter()) != null) { completed += 1; iterator(object[key], key, only_once(done)); } if (completed === 0) callback(null); function done(err) { completed--; if (err) { callback(err); } // Check key is null in case iterator isn't exhausted // and done resolved synchronously. else if (key === null && completed <= 0) { callback(null); } } }; async.forEachOfSeries = async.eachOfSeries = function (obj, iterator, callback) { callback = _once(callback || noop); obj = obj || []; var nextKey = _keyIterator(obj); var key = nextKey(); function iterate() { var sync = true; if (key === null) { return callback(null); } iterator(obj[key], key, only_once(function (err) { if (err) { callback(err); } else { key = nextKey(); if (key === null) { return callback(null); } else { if (sync) { async.setImmediate(iterate); } else { iterate(); } } } })); sync = false; } iterate(); }; async.forEachOfLimit = async.eachOfLimit = function (obj, limit, iterator, callback) { _eachOfLimit(limit)(obj, iterator, callback); }; function _eachOfLimit(limit) { return function (obj, iterator, callback) { callback = _once(callback || noop); obj = obj || []; var nextKey = _keyIterator(obj); if (limit <= 0) { return callback(null); } var done = false; var running = 0; var errored = false; (function replenish () { if (done && running <= 0) { return callback(null); } while (running < limit && !errored) { var key = nextKey(); if (key === null) { done = true; if (running <= 0) { callback(null); } return; } running += 1; iterator(obj[key], key, only_once(function (err) { running -= 1; if (err) { callback(err); errored = true; } else { replenish(); } })); } })(); }; } function doParallel(fn) { return function (obj, iterator, callback) { return fn(async.eachOf, obj, iterator, callback); }; } function doParallelLimit(fn) { return function (obj, limit, iterator, callback) { return fn(_eachOfLimit(limit), obj, iterator, callback); }; } function doSeries(fn) { return function (obj, iterator, callback) { return fn(async.eachOfSeries, obj, iterator, callback); }; } function _asyncMap(eachfn, arr, iterator, callback) { callback = _once(callback || noop); arr = arr || []; var results = _isArrayLike(arr) ? [] : {}; eachfn(arr, function (value, index, callback) { iterator(value, function (err, v) { results[index] = v; callback(err); }); }, function (err) { callback(err, results); }); } async.map = doParallel(_asyncMap); async.mapSeries = doSeries(_asyncMap); async.mapLimit = doParallelLimit(_asyncMap); // reduce only has a series version, as doing reduce in parallel won't // work in many situations. async.inject = async.foldl = async.reduce = function (arr, memo, iterator, callback) { async.eachOfSeries(arr, function (x, i, callback) { iterator(memo, x, function (err, v) { memo = v; callback(err); }); }, function (err) { callback(err, memo); }); }; async.foldr = async.reduceRight = function (arr, memo, iterator, callback) { var reversed = _map(arr, identity).reverse(); async.reduce(reversed, memo, iterator, callback); }; async.transform = function (arr, memo, iterator, callback) { if (arguments.length === 3) { callback = iterator; iterator = memo; memo = _isArray(arr) ? [] : {}; } async.eachOf(arr, function(v, k, cb) { iterator(memo, v, k, cb); }, function(err) { callback(err, memo); }); }; function _filter(eachfn, arr, iterator, callback) { var results = []; eachfn(arr, function (x, index, callback) { iterator(x, function (v) { if (v) { results.push({index: index, value: x}); } callback(); }); }, function () { callback(_map(results.sort(function (a, b) { return a.index - b.index; }), function (x) { return x.value; })); }); } async.select = async.filter = doParallel(_filter); async.selectLimit = async.filterLimit = doParallelLimit(_filter); async.selectSeries = async.filterSeries = doSeries(_filter); function _reject(eachfn, arr, iterator, callback) { _filter(eachfn, arr, function(value, cb) { iterator(value, function(v) { cb(!v); }); }, callback); } async.reject = doParallel(_reject); async.rejectLimit = doParallelLimit(_reject); async.rejectSeries = doSeries(_reject); function _createTester(eachfn, check, getResult) { return function(arr, limit, iterator, cb) { function done() { if (cb) cb(getResult(false, void 0)); } function iteratee(x, _, callback) { if (!cb) return callback(); iterator(x, function (v) { if (cb && check(v)) { cb(getResult(true, x)); cb = iterator = false; } callback(); }); } if (arguments.length > 3) { eachfn(arr, limit, iteratee, done); } else { cb = iterator; iterator = limit; eachfn(arr, iteratee, done); } }; } async.any = async.some = _createTester(async.eachOf, toBool, identity); async.someLimit = _createTester(async.eachOfLimit, toBool, identity); async.all = async.every = _createTester(async.eachOf, notId, notId); async.everyLimit = _createTester(async.eachOfLimit, notId, notId); function _findGetResult(v, x) { return x; } async.detect = _createTester(async.eachOf, identity, _findGetResult); async.detectSeries = _createTester(async.eachOfSeries, identity, _findGetResult); async.detectLimit = _createTester(async.eachOfLimit, identity, _findGetResult); async.sortBy = function (arr, iterator, callback) { async.map(arr, function (x, callback) { iterator(x, function (err, criteria) { if (err) { callback(err); } else { callback(null, {value: x, criteria: criteria}); } }); }, function (err, results) { if (err) { return callback(err); } else { callback(null, _map(results.sort(comparator), function (x) { return x.value; })); } }); function comparator(left, right) { var a = left.criteria, b = right.criteria; return a < b ? -1 : a > b ? 1 : 0; } }; async.auto = function (tasks, concurrency, callback) { if (typeof arguments[1] === 'function') { // concurrency is optional, shift the args. callback = concurrency; concurrency = null; } callback = _once(callback || noop); var keys = _keys(tasks); var remainingTasks = keys.length; if (!remainingTasks) { return callback(null); } if (!concurrency) { concurrency = remainingTasks; } var results = {}; var runningTasks = 0; var hasError = false; var listeners = []; function addListener(fn) { listeners.unshift(fn); } function removeListener(fn) { var idx = _indexOf(listeners, fn); if (idx >= 0) listeners.splice(idx, 1); } function taskComplete() { remainingTasks--; _arrayEach(listeners.slice(0), function (fn) { fn(); }); } addListener(function () { if (!remainingTasks) { callback(null, results); } }); _arrayEach(keys, function (k) { if (hasError) return; var task = _isArray(tasks[k]) ? tasks[k]: [tasks[k]]; var taskCallback = _restParam(function(err, args) { runningTasks--; if (args.length <= 1) { args = args[0]; } if (err) { var safeResults = {}; _forEachOf(results, function(val, rkey) { safeResults[rkey] = val; }); safeResults[k] = args; hasError = true; callback(err, safeResults); } else { results[k] = args; async.setImmediate(taskComplete); } }); var requires = task.slice(0, task.length - 1); // prevent dead-locks var len = requires.length; var dep; while (len--) { if (!(dep = tasks[requires[len]])) { throw new Error('Has nonexistent dependency in ' + requires.join(', ')); } if (_isArray(dep) && _indexOf(dep, k) >= 0) { throw new Error('Has cyclic dependencies'); } } function ready() { return runningTasks < concurrency && _reduce(requires, function (a, x) { return (a && results.hasOwnProperty(x)); }, true) && !results.hasOwnProperty(k); } if (ready()) { runningTasks++; task[task.length - 1](taskCallback, results); } else { addListener(listener); } function listener() { if (ready()) { runningTasks++; removeListener(listener); task[task.length - 1](taskCallback, results); } } }); }; async.retry = function(times, task, callback) { var DEFAULT_TIMES = 5; var DEFAULT_INTERVAL = 0; var attempts = []; var opts = { times: DEFAULT_TIMES, interval: DEFAULT_INTERVAL }; function parseTimes(acc, t){ if(typeof t === 'number'){ acc.times = parseInt(t, 10) || DEFAULT_TIMES; } else if(typeof t === 'object'){ acc.times = parseInt(t.times, 10) || DEFAULT_TIMES; acc.interval = parseInt(t.interval, 10) || DEFAULT_INTERVAL; } else { throw new Error('Unsupported argument type for \'times\': ' + typeof t); } } var length = arguments.length; if (length < 1 || length > 3) { throw new Error('Invalid arguments - must be either (task), (task, callback), (times, task) or (times, task, callback)'); } else if (length <= 2 && typeof times === 'function') { callback = task; task = times; } if (typeof times !== 'function') { parseTimes(opts, times); } opts.callback = callback; opts.task = task; function wrappedTask(wrappedCallback, wrappedResults) { function retryAttempt(task, finalAttempt) { return function(seriesCallback) { task(function(err, result){ seriesCallback(!err || finalAttempt, {err: err, result: result}); }, wrappedResults); }; } function retryInterval(interval){ return function(seriesCallback){ setTimeout(function(){ seriesCallback(null); }, interval); }; } while (opts.times) { var finalAttempt = !(opts.times-=1); attempts.push(retryAttempt(opts.task, finalAttempt)); if(!finalAttempt && opts.interval > 0){ attempts.push(retryInterval(opts.interval)); } } async.series(attempts, function(done, data){ data = data[data.length - 1]; (wrappedCallback || opts.callback)(data.err, data.result); }); } // If a callback is passed, run this as a controll flow return opts.callback ? wrappedTask() : wrappedTask; }; async.waterfall = function (tasks, callback) { callback = _once(callback || noop); if (!_isArray(tasks)) { var err = new Error('First argument to waterfall must be an array of functions'); return callback(err); } if (!tasks.length) { return callback(); } function wrapIterator(iterator) { return _restParam(function (err, args) { if (err) { callback.apply(null, [err].concat(args)); } else { var next = iterator.next(); if (next) { args.push(wrapIterator(next)); } else { args.push(callback); } ensureAsync(iterator).apply(null, args); } }); } wrapIterator(async.iterator(tasks))(); }; function _parallel(eachfn, tasks, callback) { callback = callback || noop; var results = _isArrayLike(tasks) ? [] : {}; eachfn(tasks, function (task, key, callback) { task(_restParam(function (err, args) { if (args.length <= 1) { args = args[0]; } results[key] = args; callback(err); })); }, function (err) { callback(err, results); }); } async.parallel = function (tasks, callback) { _parallel(async.eachOf, tasks, callback); }; async.parallelLimit = function(tasks, limit, callback) { _parallel(_eachOfLimit(limit), tasks, callback); }; async.series = function(tasks, callback) { _parallel(async.eachOfSeries, tasks, callback); }; async.iterator = function (tasks) { function makeCallback(index) { function fn() { if (tasks.length) { tasks[index].apply(null, arguments); } return fn.next(); } fn.next = function () { return (index < tasks.length - 1) ? makeCallback(index + 1): null; }; return fn; } return makeCallback(0); }; async.apply = _restParam(function (fn, args) { return _restParam(function (callArgs) { return fn.apply( null, args.concat(callArgs) ); }); }); function _concat(eachfn, arr, fn, callback) { var result = []; eachfn(arr, function (x, index, cb) { fn(x, function (err, y) { result = result.concat(y || []); cb(err); }); }, function (err) { callback(err, result); }); } async.concat = doParallel(_concat); async.concatSeries = doSeries(_concat); async.whilst = function (test, iterator, callback) { callback = callback || noop; if (test()) { var next = _restParam(function(err, args) { if (err) { callback(err); } else if (test.apply(this, args)) { iterator(next); } else { callback.apply(null, [null].concat(args)); } }); iterator(next); } else { callback(null); } }; async.doWhilst = function (iterator, test, callback) { var calls = 0; return async.whilst(function() { return ++calls <= 1 || test.apply(this, arguments); }, iterator, callback); }; async.until = function (test, iterator, callback) { return async.whilst(function() { return !test.apply(this, arguments); }, iterator, callback); }; async.doUntil = function (iterator, test, callback) { return async.doWhilst(iterator, function() { return !test.apply(this, arguments); }, callback); }; async.during = function (test, iterator, callback) { callback = callback || noop; var next = _restParam(function(err, args) { if (err) { callback(err); } else { args.push(check); test.apply(this, args); } }); var check = function(err, truth) { if (err) { callback(err); } else if (truth) { iterator(next); } else { callback(null); } }; test(check); }; async.doDuring = function (iterator, test, callback) { var calls = 0; async.during(function(next) { if (calls++ < 1) { next(null, true); } else { test.apply(this, arguments); } }, iterator, callback); }; function _queue(worker, concurrency, payload) { if (concurrency == null) { concurrency = 1; } else if(concurrency === 0) { throw new Error('Concurrency must not be zero'); } function _insert(q, data, pos, callback) { if (callback != null && typeof callback !== "function") { throw new Error("task callback must be a function"); } q.started = true; if (!_isArray(data)) { data = [data]; } if(data.length === 0 && q.idle()) { // call drain immediately if there are no tasks return async.setImmediate(function() { q.drain(); }); } _arrayEach(data, function(task) { var item = { data: task, callback: callback || noop }; if (pos) { q.tasks.unshift(item); } else { q.tasks.push(item); } if (q.tasks.length === q.concurrency) { q.saturated(); } }); async.setImmediate(q.process); } function _next(q, tasks) { return function(){ workers -= 1; var removed = false; var args = arguments; _arrayEach(tasks, function (task) { _arrayEach(workersList, function (worker, index) { if (worker === task && !removed) { workersList.splice(index, 1); removed = true; } }); task.callback.apply(task, args); }); if (q.tasks.length + workers === 0) { q.drain(); } q.process(); }; } var workers = 0; var workersList = []; var q = { tasks: [], concurrency: concurrency, payload: payload, saturated: noop, empty: noop, drain: noop, started: false, paused: false, push: function (data, callback) { _insert(q, data, false, callback); }, kill: function () { q.drain = noop; q.tasks = []; }, unshift: function (data, callback) { _insert(q, data, true, callback); }, process: function () { while(!q.paused && workers < q.concurrency && q.tasks.length){ var tasks = q.payload ? q.tasks.splice(0, q.payload) : q.tasks.splice(0, q.tasks.length); var data = _map(tasks, function (task) { return task.data; }); if (q.tasks.length === 0) { q.empty(); } workers += 1; workersList.push(tasks[0]); var cb = only_once(_next(q, tasks)); worker(data, cb); } }, length: function () { return q.tasks.length; }, running: function () { return workers; }, workersList: function () { return workersList; }, idle: function() { return q.tasks.length + workers === 0; }, pause: function () { q.paused = true; }, resume: function () { if (q.paused === false) { return; } q.paused = false; var resumeCount = Math.min(q.concurrency, q.tasks.length); // Need to call q.process once per concurrent // worker to preserve full concurrency after pause for (var w = 1; w <= resumeCount; w++) { async.setImmediate(q.process); } } }; return q; } async.queue = function (worker, concurrency) { var q = _queue(function (items, cb) { worker(items[0], cb); }, concurrency, 1); return q; }; async.priorityQueue = function (worker, concurrency) { function _compareTasks(a, b){ return a.priority - b.priority; } function _binarySearch(sequence, item, compare) { var beg = -1, end = sequence.length - 1; while (beg < end) { var mid = beg + ((end - beg + 1) >>> 1); if (compare(item, sequence[mid]) >= 0) { beg = mid; } else { end = mid - 1; } } return beg; } function _insert(q, data, priority, callback) { if (callback != null && typeof callback !== "function") { throw new Error("task callback must be a function"); } q.started = true; if (!_isArray(data)) { data = [data]; } if(data.length === 0) { // call drain immediately if there are no tasks return async.setImmediate(function() { q.drain(); }); } _arrayEach(data, function(task) { var item = { data: task, priority: priority, callback: typeof callback === 'function' ? callback : noop }; q.tasks.splice(_binarySearch(q.tasks, item, _compareTasks) + 1, 0, item); if (q.tasks.length === q.concurrency) { q.saturated(); } async.setImmediate(q.process); }); } // Start with a normal queue var q = async.queue(worker, concurrency); // Override push to accept second parameter representing priority q.push = function (data, priority, callback) { _insert(q, data, priority, callback); }; // Remove unshift function delete q.unshift; return q; }; async.cargo = function (worker, payload) { return _queue(worker, 1, payload); }; function _console_fn(name) { return _restParam(function (fn, args) { fn.apply(null, args.concat([_restParam(function (err, args) { if (typeof console === 'object') { if (err) { if (console.error) { console.error(err); } } else if (console[name]) { _arrayEach(args, function (x) { console[name](x); }); } } })])); }); } async.log = _console_fn('log'); async.dir = _console_fn('dir'); /*async.info = _console_fn('info'); async.warn = _console_fn('warn'); async.error = _console_fn('error');*/ async.memoize = function (fn, hasher) { var memo = {}; var queues = {}; var has = Object.prototype.hasOwnProperty; hasher = hasher || identity; var memoized = _restParam(function memoized(args) { var callback = args.pop(); var key = hasher.apply(null, args); if (has.call(memo, key)) { async.setImmediate(function () { callback.apply(null, memo[key]); }); } else if (has.call(queues, key)) { queues[key].push(callback); } else { queues[key] = [callback]; fn.apply(null, args.concat([_restParam(function (args) { memo[key] = args; var q = queues[key]; delete queues[key]; for (var i = 0, l = q.length; i < l; i++) { q[i].apply(null, args); } })])); } }); memoized.memo = memo; memoized.unmemoized = fn; return memoized; }; async.unmemoize = function (fn) { return function () { return (fn.unmemoized || fn).apply(null, arguments); }; }; function _times(mapper) { return function (count, iterator, callback) { mapper(_range(count), iterator, callback); }; } async.times = _times(async.map); async.timesSeries = _times(async.mapSeries); async.timesLimit = function (count, limit, iterator, callback) { return async.mapLimit(_range(count), limit, iterator, callback); }; async.seq = function (/* functions... */) { var fns = arguments; return _restParam(function (args) { var that = this; var callback = args[args.length - 1]; if (typeof callback == 'function') { args.pop(); } else { callback = noop; } async.reduce(fns, args, function (newargs, fn, cb) { fn.apply(that, newargs.concat([_restParam(function (err, nextargs) { cb(err, nextargs); })])); }, function (err, results) { callback.apply(that, [err].concat(results)); }); }); }; async.compose = function (/* functions... */) { return async.seq.apply(null, Array.prototype.reverse.call(arguments)); }; function _applyEach(eachfn) { return _restParam(function(fns, args) { var go = _restParam(function(args) { var that = this; var callback = args.pop(); return eachfn(fns, function (fn, _, cb) { fn.apply(that, args.concat([cb])); }, callback); }); if (args.length) { return go.apply(this, args); } else { return go; } }); } async.applyEach = _applyEach(async.eachOf); async.applyEachSeries = _applyEach(async.eachOfSeries); async.forever = function (fn, callback) { var done = only_once(callback || noop); var task = ensureAsync(fn); function next(err) { if (err) { return done(err); } task(next); } next(); }; function ensureAsync(fn) { return _restParam(function (args) { var callback = args.pop(); args.push(function () { var innerArgs = arguments; if (sync) { async.setImmediate(function () { callback.apply(null, innerArgs); }); } else { callback.apply(null, innerArgs); } }); var sync = true; fn.apply(this, args); sync = false; }); } async.ensureAsync = ensureAsync; async.constant = _restParam(function(values) { var args = [null].concat(values); return function (callback) { return callback.apply(this, args); }; }); async.wrapSync = async.asyncify = function asyncify(func) { return _restParam(function (args) { var callback = args.pop(); var result; try { result = func.apply(this, args); } catch (e) { return callback(e); } // if result is Promise object if (_isObject(result) && typeof result.then === "function") { result.then(function(value) { callback(null, value); })["catch"](function(err) { callback(err.message ? err : new Error(err)); }); } else { callback(null, result); } }); }; // Node.js if (typeof module === 'object' && module.exports) { module.exports = async; } // AMD / RequireJS else if (typeof define === 'function' && define.amd) { define([], function () { return async; }); } // included directly via <script> tag else { root.async = async; } }()); }).call(this,_dereq_('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) },{"_process":93}],38:[function(_dereq_,module,exports){ ;(function (root, factory, undef) { if (typeof exports === "object") { // CommonJS module.exports = exports = factory(_dereq_("./core"), _dereq_("./enc-base64"), _dereq_("./md5"), _dereq_("./evpkdf"), _dereq_("./cipher-core")); } else if (typeof define === "function" && define.amd) { // AMD define(["./core", "./enc-base64", "./md5", "./evpkdf", "./cipher-core"], factory); } else { // Global (browser) factory(root.CryptoJS); } }(this, function (CryptoJS) { (function () { // Shortcuts var C = CryptoJS; var C_lib = C.lib; var BlockCipher = C_lib.BlockCipher; var C_algo = C.algo; // Lookup tables var SBOX = []; var INV_SBOX = []; var SUB_MIX_0 = []; var SUB_MIX_1 = []; var SUB_MIX_2 = []; var SUB_MIX_3 = []; var INV_SUB_MIX_0 = []; var INV_SUB_MIX_1 = []; var INV_SUB_MIX_2 = []; var INV_SUB_MIX_3 = []; // Compute lookup tables (function () { // Compute double table var d = []; for (var i = 0; i < 256; i++) { if (i < 128) { d[i] = i << 1; } else { d[i] = (i << 1) ^ 0x11b; } } // Walk GF(2^8) var x = 0; var xi = 0; for (var i = 0; i < 256; i++) { // Compute sbox var sx = xi ^ (xi << 1) ^ (xi << 2) ^ (xi << 3) ^ (xi << 4); sx = (sx >>> 8) ^ (sx & 0xff) ^ 0x63; SBOX[x] = sx; INV_SBOX[sx] = x; // Compute multiplication var x2 = d[x]; var x4 = d[x2]; var x8 = d[x4]; // Compute sub bytes, mix columns tables var t = (d[sx] * 0x101) ^ (sx * 0x1010100); SUB_MIX_0[x] = (t << 24) | (t >>> 8); SUB_MIX_1[x] = (t << 16) | (t >>> 16); SUB_MIX_2[x] = (t << 8) | (t >>> 24); SUB_MIX_3[x] = t; // Compute inv sub bytes, inv mix columns tables var t = (x8 * 0x1010101) ^ (x4 * 0x10001) ^ (x2 * 0x101) ^ (x * 0x1010100); INV_SUB_MIX_0[sx] = (t << 24) | (t >>> 8); INV_SUB_MIX_1[sx] = (t << 16) | (t >>> 16); INV_SUB_MIX_2[sx] = (t << 8) | (t >>> 24); INV_SUB_MIX_3[sx] = t; // Compute next counter if (!x) { x = xi = 1; } else { x = x2 ^ d[d[d[x8 ^ x2]]]; xi ^= d[d[xi]]; } } }()); // Precomputed Rcon lookup var RCON = [0x00, 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, 0x1b, 0x36]; /** * AES block cipher algorithm. */ var AES = C_algo.AES = BlockCipher.extend({ _doReset: function () { // Shortcuts var key = this._key; var keyWords = key.words; var keySize = key.sigBytes / 4; // Compute number of rounds var nRounds = this._nRounds = keySize + 6 // Compute number of key schedule rows var ksRows = (nRounds + 1) * 4; // Compute key schedule var keySchedule = this._keySchedule = []; for (var ksRow = 0; ksRow < ksRows; ksRow++) { if (ksRow < keySize) { keySchedule[ksRow] = keyWords[ksRow]; } else { var t = keySchedule[ksRow - 1]; if (!(ksRow % keySize)) { // Rot word t = (t << 8) | (t >>> 24); // Sub word t = (SBOX[t >>> 24] << 24) | (SBOX[(t >>> 16) & 0xff] << 16) | (SBOX[(t >>> 8) & 0xff] << 8) | SBOX[t & 0xff]; // Mix Rcon t ^= RCON[(ksRow / keySize) | 0] << 24; } else if (keySize > 6 && ksRow % keySize == 4) { // Sub word t = (SBOX[t >>> 24] << 24) | (SBOX[(t >>> 16) & 0xff] << 16) | (SBOX[(t >>> 8) & 0xff] << 8) | SBOX[t & 0xff]; } keySchedule[ksRow] = keySchedule[ksRow - keySize] ^ t; } } // Compute inv key schedule var invKeySchedule = this._invKeySchedule = []; for (var invKsRow = 0; invKsRow < ksRows; invKsRow++) { var ksRow = ksRows - invKsRow; if (invKsRow % 4) { var t = keySchedule[ksRow]; } else { var t = keySchedule[ksRow - 4]; } if (invKsRow < 4 || ksRow <= 4) { invKeySchedule[invKsRow] = t; } else { invKeySchedule[invKsRow] = INV_SUB_MIX_0[SBOX[t >>> 24]] ^ INV_SUB_MIX_1[SBOX[(t >>> 16) & 0xff]] ^ INV_SUB_MIX_2[SBOX[(t >>> 8) & 0xff]] ^ INV_SUB_MIX_3[SBOX[t & 0xff]]; } } }, encryptBlock: function (M, offset) { this._doCryptBlock(M, offset, this._keySchedule, SUB_MIX_0, SUB_MIX_1, SUB_MIX_2, SUB_MIX_3, SBOX); }, decryptBlock: function (M, offset) { // Swap 2nd and 4th rows var t = M[offset + 1]; M[offset + 1] = M[offset + 3]; M[offset + 3] = t; this._doCryptBlock(M, offset, this._invKeySchedule, INV_SUB_MIX_0, INV_SUB_MIX_1, INV_SUB_MIX_2, INV_SUB_MIX_3, INV_SBOX); // Inv swap 2nd and 4th rows var t = M[offset + 1]; M[offset + 1] = M[offset + 3]; M[offset + 3] = t; }, _doCryptBlock: function (M, offset, keySchedule, SUB_MIX_0, SUB_MIX_1, SUB_MIX_2, SUB_MIX_3, SBOX) { // Shortcut var nRounds = this._nRounds; // Get input, add round key var s0 = M[offset] ^ keySchedule[0]; var s1 = M[offset + 1] ^ keySchedule[1]; var s2 = M[offset + 2] ^ keySchedule[2]; var s3 = M[offset + 3] ^ keySchedule[3]; // Key schedule row counter var ksRow = 4; // Rounds for (var round = 1; round < nRounds; round++) { // Shift rows, sub bytes, mix columns, add round key var t0 = SUB_MIX_0[s0 >>> 24] ^ SUB_MIX_1[(s1 >>> 16) & 0xff] ^ SUB_MIX_2[(s2 >>> 8) & 0xff] ^ SUB_MIX_3[s3 & 0xff] ^ keySchedule[ksRow++]; var t1 = SUB_MIX_0[s1 >>> 24] ^ SUB_MIX_1[(s2 >>> 16) & 0xff] ^ SUB_MIX_2[(s3 >>> 8) & 0xff] ^ SUB_MIX_3[s0 & 0xff] ^ keySchedule[ksRow++]; var t2 = SUB_MIX_0[s2 >>> 24] ^ SUB_MIX_1[(s3 >>> 16) & 0xff] ^ SUB_MIX_2[(s0 >>> 8) & 0xff] ^ SUB_MIX_3[s1 & 0xff] ^ keySchedule[ksRow++]; var t3 = SUB_MIX_0[s3 >>> 24] ^ SUB_MIX_1[(s0 >>> 16) & 0xff] ^ SUB_MIX_2[(s1 >>> 8) & 0xff] ^ SUB_MIX_3[s2 & 0xff] ^ keySchedule[ksRow++]; // Update state s0 = t0; s1 = t1; s2 = t2; s3 = t3; } // Shift rows, sub bytes, add round key var t0 = ((SBOX[s0 >>> 24] << 24) | (SBOX[(s1 >>> 16) & 0xff] << 16) | (SBOX[(s2 >>> 8) & 0xff] << 8) | SBOX[s3 & 0xff]) ^ keySchedule[ksRow++]; var t1 = ((SBOX[s1 >>> 24] << 24) | (SBOX[(s2 >>> 16) & 0xff] << 16) | (SBOX[(s3 >>> 8) & 0xff] << 8) | SBOX[s0 & 0xff]) ^ keySchedule[ksRow++]; var t2 = ((SBOX[s2 >>> 24] << 24) | (SBOX[(s3 >>> 16) & 0xff] << 16) | (SBOX[(s0 >>> 8) & 0xff] << 8) | SBOX[s1 & 0xff]) ^ keySchedule[ksRow++]; var t3 = ((SBOX[s3 >>> 24] << 24) | (SBOX[(s0 >>> 16) & 0xff] << 16) | (SBOX[(s1 >>> 8) & 0xff] << 8) | SBOX[s2 & 0xff]) ^ keySchedule[ksRow++]; // Set output M[offset] = t0; M[offset + 1] = t1; M[offset + 2] = t2; M[offset + 3] = t3; }, keySize: 256/32 }); /** * Shortcut functions to the cipher's object interface. * * @example * * var ciphertext = CryptoJS.AES.encrypt(message, key, cfg); * var plaintext = CryptoJS.AES.decrypt(ciphertext, key, cfg); */ C.AES = BlockCipher._createHelper(AES); }()); return CryptoJS.AES; })); },{"./cipher-core":39,"./core":40,"./enc-base64":41,"./evpkdf":43,"./md5":48}],39:[function(_dereq_,module,exports){ ;(function (root, factory) { if (typeof exports === "object") { // CommonJS module.exports = exports = factory(_dereq_("./core")); } else if (typeof define === "function" && define.amd) { // AMD define(["./core"], factory); } else { // Global (browser) factory(root.CryptoJS); } }(this, function (CryptoJS) { /** * Cipher core components. */ CryptoJS.lib.Cipher || (function (undefined) { // Shortcuts var C = CryptoJS; var C_lib = C.lib; var Base = C_lib.Base; var WordArray = C_lib.WordArray; var BufferedBlockAlgorithm = C_lib.BufferedBlockAlgorithm; var C_enc = C.enc; var Utf8 = C_enc.Utf8; var Base64 = C_enc.Base64; var C_algo = C.algo; var EvpKDF = C_algo.EvpKDF; /** * Abstract base cipher template. * * @property {number} keySize This cipher's key size. Default: 4 (128 bits) * @property {number} ivSize This cipher's IV size. Default: 4 (128 bits) * @property {number} _ENC_XFORM_MODE A constant representing encryption mode. * @property {number} _DEC_XFORM_MODE A constant representing decryption mode. */ var Cipher = C_lib.Cipher = BufferedBlockAlgorithm.extend({ /** * Configuration options. * * @property {WordArray} iv The IV to use for this operation. */ cfg: Base.extend(), /** * Creates this cipher in encryption mode. * * @param {WordArray} key The key. * @param {Object} cfg (Optional) The configuration options to use for this operation. * * @return {Cipher} A cipher instance. * * @static * * @example * * var cipher = CryptoJS.algo.AES.createEncryptor(keyWordArray, { iv: ivWordArray }); */ createEncryptor: function (key, cfg) { return this.create(this._ENC_XFORM_MODE, key, cfg); }, /** * Creates this cipher in decryption mode. * * @param {WordArray} key The key. * @param {Object} cfg (Optional) The configuration options to use for this operation. * * @return {Cipher} A cipher instance. * * @static * * @example * * var cipher = CryptoJS.algo.AES.createDecryptor(keyWordArray, { iv: ivWordArray }); */ createDecryptor: function (key, cfg) { return this.create(this._DEC_XFORM_MODE, key, cfg); }, /** * Initializes a newly created cipher. * * @param {number} xformMode Either the encryption or decryption transormation mode constant. * @param {WordArray} key The key. * @param {Object} cfg (Optional) The configuration options to use for this operation. * * @example * * var cipher = CryptoJS.algo.AES.create(CryptoJS.algo.AES._ENC_XFORM_MODE, keyWordArray, { iv: ivWordArray }); */ init: function (xformMode, key, cfg) { // Apply config defaults this.cfg = this.cfg.extend(cfg); // Store transform mode and key this._xformMode = xformMode; this._key = key; // Set initial values this.reset(); }, /** * Resets this cipher to its initial state. * * @example * * cipher.reset(); */ reset: function () { // Reset data buffer BufferedBlockAlgorithm.reset.call(this); // Perform concrete-cipher logic this._doReset(); }, /** * Adds data to be encrypted or decrypted. * * @param {WordArray|string} dataUpdate The data to encrypt or decrypt. * * @return {WordArray} The data after processing. * * @example * * var encrypted = cipher.process('data'); * var encrypted = cipher.process(wordArray); */ process: function (dataUpdate) { // Append this._append(dataUpdate); // Process available blocks return this._process(); }, /** * Finalizes the encryption or decryption process. * Note that the finalize operation is effectively a destructive, read-once operation. * * @param {WordArray|string} dataUpdate The final data to encrypt or decrypt. * * @return {WordArray} The data after final processing. * * @example * * var encrypted = cipher.finalize(); * var encrypted = cipher.finalize('data'); * var encrypted = cipher.finalize(wordArray); */ finalize: function (dataUpdate) { // Final data update if (dataUpdate) { this._append(dataUpdate); } // Perform concrete-cipher logic var finalProcessedData = this._doFinalize(); return finalProcessedData; }, keySize: 128/32, ivSize: 128/32, _ENC_XFORM_MODE: 1, _DEC_XFORM_MODE: 2, /** * Creates shortcut functions to a cipher's object interface. * * @param {Cipher} cipher The cipher to create a helper for. * * @return {Object} An object with encrypt and decrypt shortcut functions. * * @static * * @example * * var AES = CryptoJS.lib.Cipher._createHelper(CryptoJS.algo.AES); */ _createHelper: (function () { function selectCipherStrategy(key) { if (typeof key == 'string') { return PasswordBasedCipher; } else { return SerializableCipher; } } return function (cipher) { return { encrypt: function (message, key, cfg) { return selectCipherStrategy(key).encrypt(cipher, message, key, cfg); }, decrypt: function (ciphertext, key, cfg) { return selectCipherStrategy(key).decrypt(cipher, ciphertext, key, cfg); } }; }; }()) }); /** * Abstract base stream cipher template. * * @property {number} blockSize The number of 32-bit words this cipher operates on. Default: 1 (32 bits) */ var StreamCipher = C_lib.StreamCipher = Cipher.extend({ _doFinalize: function () { // Process partial blocks var finalProcessedBlocks = this._process(!!'flush'); return finalProcessedBlocks; }, blockSize: 1 }); /** * Mode namespace. */ var C_mode = C.mode = {}; /** * Abstract base block cipher mode template. */ var BlockCipherMode = C_lib.BlockCipherMode = Base.extend({ /** * Creates this mode for encryption. * * @param {Cipher} cipher A block cipher instance. * @param {Array} iv The IV words. * * @static * * @example * * var mode = CryptoJS.mode.CBC.createEncryptor(cipher, iv.words); */ createEncryptor: function (cipher, iv) { return this.Encryptor.create(cipher, iv); }, /** * Creates this mode for decryption. * * @param {Cipher} cipher A block cipher instance. * @param {Array} iv The IV words. * * @static * * @example * * var mode = CryptoJS.mode.CBC.createDecryptor(cipher, iv.words); */ createDecryptor: function (cipher, iv) { return this.Decryptor.create(cipher, iv); }, /** * Initializes a newly created mode. * * @param {Cipher} cipher A block cipher instance. * @param {Array} iv The IV words. * * @example * * var mode = CryptoJS.mode.CBC.Encryptor.create(cipher, iv.words); */ init: function (cipher, iv) { this._cipher = cipher; this._iv = iv; } }); /** * Cipher Block Chaining mode. */ var CBC = C_mode.CBC = (function () { /** * Abstract base CBC mode. */ var CBC = BlockCipherMode.extend(); /** * CBC encryptor. */ CBC.Encryptor = CBC.extend({ /** * Processes the data block at offset. * * @param {Array} words The data words to operate on. * @param {number} offset The offset where the block starts. * * @example * * mode.processBlock(data.words, offset); */ processBlock: function (words, offset) { // Shortcuts var cipher = this._cipher; var blockSize = cipher.blockSize; // XOR and encrypt xorBlock.call(this, words, offset, blockSize); cipher.encryptBlock(words, offset); // Remember this block to use with next block this._prevBlock = words.slice(offset, offset + blockSize); } }); /** * CBC decryptor. */ CBC.Decryptor = CBC.extend({ /** * Processes the data block at offset. * * @param {Array} words The data words to operate on. * @param {number} offset The offset where the block starts. * * @example * * mode.processBlock(data.words, offset); */ processBlock: function (words, offset) { // Shortcuts var cipher = this._cipher; var blockSize = cipher.blockSize; // Remember this block to use with next block var thisBlock = words.slice(offset, offset + blockSize); // Decrypt and XOR cipher.decryptBlock(words, offset); xorBlock.call(this, words, offset, blockSize); // This block becomes the previous block this._prevBlock = thisBlock; } }); function xorBlock(words, offset, blockSize) { // Shortcut var iv = this._iv; // Choose mixing block if (iv) { var block = iv; // Remove IV for subsequent blocks this._iv = undefined; } else { var block = this._prevBlock; } // XOR blocks for (var i = 0; i < blockSize; i++) { words[offset + i] ^= block[i]; } } return CBC; }()); /** * Padding namespace. */ var C_pad = C.pad = {}; /** * PKCS #5/7 padding strategy. */ var Pkcs7 = C_pad.Pkcs7 = { /** * Pads data using the algorithm defined in PKCS #5/7. * * @param {WordArray} data The data to pad. * @param {number} blockSize The multiple that the data should be padded to. * * @static * * @example * * CryptoJS.pad.Pkcs7.pad(wordArray, 4); */ pad: function (data, blockSize) { // Shortcut var blockSizeBytes = blockSize * 4; // Count padding bytes var nPaddingBytes = blockSizeBytes - data.sigBytes % blockSizeBytes; // Create padding word var paddingWord = (nPaddingBytes << 24) | (nPaddingBytes << 16) | (nPaddingBytes << 8) | nPaddingBytes; // Create padding var paddingWords = []; for (var i = 0; i < nPaddingBytes; i += 4) { paddingWords.push(paddingWord); } var padding = WordArray.create(paddingWords, nPaddingBytes); // Add padding data.concat(padding); }, /** * Unpads data that had been padded using the algorithm defined in PKCS #5/7. * * @param {WordArray} data The data to unpad. * * @static * * @example * * CryptoJS.pad.Pkcs7.unpad(wordArray); */ unpad: function (data) { // Get number of padding bytes from last byte var nPaddingBytes = data.words[(data.sigBytes - 1) >>> 2] & 0xff; // Remove padding data.sigBytes -= nPaddingBytes; } }; /** * Abstract base block cipher template. * * @property {number} blockSize The number of 32-bit words this cipher operates on. Default: 4 (128 bits) */ var BlockCipher = C_lib.BlockCipher = Cipher.extend({ /** * Configuration options. * * @property {Mode} mode The block mode to use. Default: CBC * @property {Padding} padding The padding strategy to use. Default: Pkcs7 */ cfg: Cipher.cfg.extend({ mode: CBC, padding: Pkcs7 }), reset: function () { // Reset cipher Cipher.reset.call(this); // Shortcuts var cfg = this.cfg; var iv = cfg.iv; var mode = cfg.mode; // Reset block mode if (this._xformMode == this._ENC_XFORM_MODE) { var modeCreator = mode.createEncryptor; } else /* if (this._xformMode == this._DEC_XFORM_MODE) */ { var modeCreator = mode.createDecryptor; // Keep at least one block in the buffer for unpadding this._minBufferSize = 1; } this._mode = modeCreator.call(mode, this, iv && iv.words); }, _doProcessBlock: function (words, offset) { this._mode.processBlock(words, offset); }, _doFinalize: function () { // Shortcut var padding = this.cfg.padding; // Finalize if (this._xformMode == this._ENC_XFORM_MODE) { // Pad data padding.pad(this._data, this.blockSize); // Process final blocks var finalProcessedBlocks = this._process(!!'flush'); } else /* if (this._xformMode == this._DEC_XFORM_MODE) */ { // Process final blocks var finalProcessedBlocks = this._process(!!'flush'); // Unpad data padding.unpad(finalProcessedBlocks); } return finalProcessedBlocks; }, blockSize: 128/32 }); /** * A collection of cipher parameters. * * @property {WordArray} ciphertext The raw ciphertext. * @property {WordArray} key The key to this ciphertext. * @property {WordArray} iv The IV used in the ciphering operation. * @property {WordArray} salt The salt used with a key derivation function. * @property {Cipher} algorithm The cipher algorithm. * @property {Mode} mode The block mode used in the ciphering operation. * @property {Padding} padding The padding scheme used in the ciphering operation. * @property {number} blockSize The block size of the cipher. * @property {Format} formatter The default formatting strategy to convert this cipher params object to a string. */ var CipherParams = C_lib.CipherParams = Base.extend({ /** * Initializes a newly created cipher params object. * * @param {Object} cipherParams An object with any of the possible cipher parameters. * * @example * * var cipherParams = CryptoJS.lib.CipherParams.create({ * ciphertext: ciphertextWordArray, * key: keyWordArray, * iv: ivWordArray, * salt: saltWordArray, * algorithm: CryptoJS.algo.AES, * mode: CryptoJS.mode.CBC, * padding: CryptoJS.pad.PKCS7, * blockSize: 4, * formatter: CryptoJS.format.OpenSSL * }); */ init: function (cipherParams) { this.mixIn(cipherParams); }, /** * Converts this cipher params object to a string. * * @param {Format} formatter (Optional) The formatting strategy to use. * * @return {string} The stringified cipher params. * * @throws Error If neither the formatter nor the default formatter is set. * * @example * * var string = cipherParams + ''; * var string = cipherParams.toString(); * var string = cipherParams.toString(CryptoJS.format.OpenSSL); */ toString: function (formatter) { return (formatter || this.formatter).stringify(this); } }); /** * Format namespace. */ var C_format = C.format = {}; /** * OpenSSL formatting strategy. */ var OpenSSLFormatter = C_format.OpenSSL = { /** * Converts a cipher params object to an OpenSSL-compatible string. * * @param {CipherParams} cipherParams The cipher params object. * * @return {string} The OpenSSL-compatible string. * * @static * * @example * * var openSSLString = CryptoJS.format.OpenSSL.stringify(cipherParams); */ stringify: function (cipherParams) { // Shortcuts var ciphertext = cipherParams.ciphertext; var salt = cipherParams.salt; // Format if (salt) { var wordArray = WordArray.create([0x53616c74, 0x65645f5f]).concat(salt).concat(ciphertext); } else { var wordArray = ciphertext; } return wordArray.toString(Base64); }, /** * Converts an OpenSSL-compatible string to a cipher params object. * * @param {string} openSSLStr The OpenSSL-compatible string. * * @return {CipherParams} The cipher params object. * * @static * * @example * * var cipherParams = CryptoJS.format.OpenSSL.parse(openSSLString); */ parse: function (openSSLStr) { // Parse base64 var ciphertext = Base64.parse(openSSLStr); // Shortcut var ciphertextWords = ciphertext.words; // Test for salt if (ciphertextWords[0] == 0x53616c74 && ciphertextWords[1] == 0x65645f5f) { // Extract salt var salt = WordArray.create(ciphertextWords.slice(2, 4)); // Remove salt from ciphertext ciphertextWords.splice(0, 4); ciphertext.sigBytes -= 16; } return CipherParams.create({ ciphertext: ciphertext, salt: salt }); } }; /** * A cipher wrapper that returns ciphertext as a serializable cipher params object. */ var SerializableCipher = C_lib.SerializableCipher = Base.extend({ /** * Configuration options. * * @property {Formatter} format The formatting strategy to convert cipher param objects to and from a string. Default: OpenSSL */ cfg: Base.extend({ format: OpenSSLFormatter }), /** * Encrypts a message. * * @param {Cipher} cipher The cipher algorithm to use. * @param {WordArray|string} message The message to encrypt. * @param {WordArray} key The key. * @param {Object} cfg (Optional) The configuration options to use for this operation. * * @return {CipherParams} A cipher params object. * * @static * * @example * * var ciphertextParams = CryptoJS.lib.SerializableCipher.encrypt(CryptoJS.algo.AES, message, key); * var ciphertextParams = CryptoJS.lib.SerializableCipher.encrypt(CryptoJS.algo.AES, message, key, { iv: iv }); * var ciphertextParams = CryptoJS.lib.SerializableCipher.encrypt(CryptoJS.algo.AES, message, key, { iv: iv, format: CryptoJS.format.OpenSSL }); */ encrypt: function (cipher, message, key, cfg) { // Apply config defaults cfg = this.cfg.extend(cfg); // Encrypt var encryptor = cipher.createEncryptor(key, cfg); var ciphertext = encryptor.finalize(message); // Shortcut var cipherCfg = encryptor.cfg; // Create and return serializable cipher params return CipherParams.create({ ciphertext: ciphertext, key: key, iv: cipherCfg.iv, algorithm: cipher, mode: cipherCfg.mode, padding: cipherCfg.padding, blockSize: cipher.blockSize, formatter: cfg.format }); }, /** * Decrypts serialized ciphertext. * * @param {Cipher} cipher The cipher algorithm to use. * @param {CipherParams|string} ciphertext The ciphertext to decrypt. * @param {WordArray} key The key. * @param {Object} cfg (Optional) The configuration options to use for this operation. * * @return {WordArray} The plaintext. * * @static * * @example * * var plaintext = CryptoJS.lib.SerializableCipher.decrypt(CryptoJS.algo.AES, formattedCiphertext, key, { iv: iv, format: CryptoJS.format.OpenSSL }); * var plaintext = CryptoJS.lib.SerializableCipher.decrypt(CryptoJS.algo.AES, ciphertextParams, key, { iv: iv, format: CryptoJS.format.OpenSSL }); */ decrypt: function (cipher, ciphertext, key, cfg) { // Apply config defaults cfg = this.cfg.extend(cfg); // Convert string to CipherParams ciphertext = this._parse(ciphertext, cfg.format); // Decrypt var plaintext = cipher.createDecryptor(key, cfg).finalize(ciphertext.ciphertext); return plaintext; }, /** * Converts serialized ciphertext to CipherParams, * else assumed CipherParams already and returns ciphertext unchanged. * * @param {CipherParams|string} ciphertext The ciphertext. * @param {Formatter} format The formatting strategy to use to parse serialized ciphertext. * * @return {CipherParams} The unserialized ciphertext. * * @static * * @example * * var ciphertextParams = CryptoJS.lib.SerializableCipher._parse(ciphertextStringOrParams, format); */ _parse: function (ciphertext, format) { if (typeof ciphertext == 'string') { return format.parse(ciphertext, this); } else { return ciphertext; } } }); /** * Key derivation function namespace. */ var C_kdf = C.kdf = {}; /** * OpenSSL key derivation function. */ var OpenSSLKdf = C_kdf.OpenSSL = { /** * Derives a key and IV from a password. * * @param {string} password The password to derive from. * @param {number} keySize The size in words of the key to generate. * @param {number} ivSize The size in words of the IV to generate. * @param {WordArray|string} salt (Optional) A 64-bit salt to use. If omitted, a salt will be generated randomly. * * @return {CipherParams} A cipher params object with the key, IV, and salt. * * @static * * @example * * var derivedParams = CryptoJS.kdf.OpenSSL.execute('Password', 256/32, 128/32); * var derivedParams = CryptoJS.kdf.OpenSSL.execute('Password', 256/32, 128/32, 'saltsalt'); */ execute: function (password, keySize, ivSize, salt) { // Generate random salt if (!salt) { salt = WordArray.random(64/8); } // Derive key and IV var key = EvpKDF.create({ keySize: keySize + ivSize }).compute(password, salt); // Separate key and IV var iv = WordArray.create(key.words.slice(keySize), ivSize * 4); key.sigBytes = keySize * 4; // Return params return CipherParams.create({ key: key, iv: iv, salt: salt }); } }; /** * A serializable cipher wrapper that derives the key from a password, * and returns ciphertext as a serializable cipher params object. */ var PasswordBasedCipher = C_lib.PasswordBasedCipher = SerializableCipher.extend({ /** * Configuration options. * * @property {KDF} kdf The key derivation function to use to generate a key and IV from a password. Default: OpenSSL */ cfg: SerializableCipher.cfg.extend({ kdf: OpenSSLKdf }), /** * Encrypts a message using a password. * * @param {Cipher} cipher The cipher algorithm to use. * @param {WordArray|string} message The message to encrypt. * @param {string} password The password. * @param {Object} cfg (Optional) The configuration options to use for this operation. * * @return {CipherParams} A cipher params object. * * @static * * @example * * var ciphertextParams = CryptoJS.lib.PasswordBasedCipher.encrypt(CryptoJS.algo.AES, message, 'password'); * var ciphertextParams = CryptoJS.lib.PasswordBasedCipher.encrypt(CryptoJS.algo.AES, message, 'password', { format: CryptoJS.format.OpenSSL }); */ encrypt: function (cipher, message, password, cfg) { // Apply config defaults cfg = this.cfg.extend(cfg); // Derive key and other params var derivedParams = cfg.kdf.execute(password, cipher.keySize, cipher.ivSize); // Add IV to config cfg.iv = derivedParams.iv; // Encrypt var ciphertext = SerializableCipher.encrypt.call(this, cipher, message, derivedParams.key, cfg); // Mix in derived params ciphertext.mixIn(derivedParams); return ciphertext; }, /** * Decrypts serialized ciphertext using a password. * * @param {Cipher} cipher The cipher algorithm to use. * @param {CipherParams|string} ciphertext The ciphertext to decrypt. * @param {string} password The password. * @param {Object} cfg (Optional) The configuration options to use for this operation. * * @return {WordArray} The plaintext. * * @static * * @example * * var plaintext = CryptoJS.lib.PasswordBasedCipher.decrypt(CryptoJS.algo.AES, formattedCiphertext, 'password', { format: CryptoJS.format.OpenSSL }); * var plaintext = CryptoJS.lib.PasswordBasedCipher.decrypt(CryptoJS.algo.AES, ciphertextParams, 'password', { format: CryptoJS.format.OpenSSL }); */ decrypt: function (cipher, ciphertext, password, cfg) { // Apply config defaults cfg = this.cfg.extend(cfg); // Convert string to CipherParams ciphertext = this._parse(ciphertext, cfg.format); // Derive key and other params var derivedParams = cfg.kdf.execute(password, cipher.keySize, cipher.ivSize, ciphertext.salt); // Add IV to config cfg.iv = derivedParams.iv; // Decrypt var plaintext = SerializableCipher.decrypt.call(this, cipher, ciphertext, derivedParams.key, cfg); return plaintext; } }); }()); })); },{"./core":40}],40:[function(_dereq_,module,exports){ ;(function (root, factory) { if (typeof exports === "object") { // CommonJS module.exports = exports = factory(); } else if (typeof define === "function" && define.amd) { // AMD define([], factory); } else { // Global (browser) root.CryptoJS = factory(); } }(this, function () { /** * CryptoJS core components. */ var CryptoJS = CryptoJS || (function (Math, undefined) { /** * CryptoJS namespace. */ var C = {}; /** * Library namespace. */ var C_lib = C.lib = {}; /** * Base object for prototypal inheritance. */ var Base = C_lib.Base = (function () { function F() {} return { /** * Creates a new object that inherits from this object. * * @param {Object} overrides Properties to copy into the new object. * * @return {Object} The new object. * * @static * * @example * * var MyType = CryptoJS.lib.Base.extend({ * field: 'value', * * method: function () { * } * }); */ extend: function (overrides) { // Spawn F.prototype = this; var subtype = new F(); // Augment if (overrides) { subtype.mixIn(overrides); } // Create default initializer if (!subtype.hasOwnProperty('init')) { subtype.init = function () { subtype.$super.init.apply(this, arguments); }; } // Initializer's prototype is the subtype object subtype.init.prototype = subtype; // Reference supertype subtype.$super = this; return subtype; }, /** * Extends this object and runs the init method. * Arguments to create() will be passed to init(). * * @return {Object} The new object. * * @static * * @example * * var instance = MyType.create(); */ create: function () { var instance = this.extend(); instance.init.apply(instance, arguments); return instance; }, /** * Initializes a newly created object. * Override this method to add some logic when your objects are created. * * @example * * var MyType = CryptoJS.lib.Base.extend({ * init: function () { * // ... * } * }); */ init: function () { }, /** * Copies properties into this object. * * @param {Object} properties The properties to mix in. * * @example * * MyType.mixIn({ * field: 'value' * }); */ mixIn: function (properties) { for (var propertyName in properties) { if (properties.hasOwnProperty(propertyName)) { this[propertyName] = properties[propertyName]; } } // IE won't copy toString using the loop above if (properties.hasOwnProperty('toString')) { this.toString = properties.toString; } }, /** * Creates a copy of this object. * * @return {Object} The clone. * * @example * * var clone = instance.clone(); */ clone: function () { return this.init.prototype.extend(this); } }; }()); /** * An array of 32-bit words. * * @property {Array} words The array of 32-bit words. * @property {number} sigBytes The number of significant bytes in this word array. */ var WordArray = C_lib.WordArray = Base.extend({ /** * Initializes a newly created word array. * * @param {Array} words (Optional) An array of 32-bit words. * @param {number} sigBytes (Optional) The number of significant bytes in the words. * * @example * * var wordArray = CryptoJS.lib.WordArray.create(); * var wordArray = CryptoJS.lib.WordArray.create([0x00010203, 0x04050607]); * var wordArray = CryptoJS.lib.WordArray.create([0x00010203, 0x04050607], 6); */ init: function (words, sigBytes) { words = this.words = words || []; if (sigBytes != undefined) { this.sigBytes = sigBytes; } else { this.sigBytes = words.length * 4; } }, /** * Converts this word array to a string. * * @param {Encoder} encoder (Optional) The encoding strategy to use. Default: CryptoJS.enc.Hex * * @return {string} The stringified word array. * * @example * * var string = wordArray + ''; * var string = wordArray.toString(); * var string = wordArray.toString(CryptoJS.enc.Utf8); */ toString: function (encoder) { return (encoder || Hex).stringify(this); }, /** * Concatenates a word array to this word array. * * @param {WordArray} wordArray The word array to append. * * @return {WordArray} This word array. * * @example * * wordArray1.concat(wordArray2); */ concat: function (wordArray) { // Shortcuts var thisWords = this.words; var thatWords = wordArray.words; var thisSigBytes = this.sigBytes; var thatSigBytes = wordArray.sigBytes; // Clamp excess bits this.clamp(); // Concat if (thisSigBytes % 4) { // Copy one byte at a time for (var i = 0; i < thatSigBytes; i++) { var thatByte = (thatWords[i >>> 2] >>> (24 - (i % 4) * 8)) & 0xff; thisWords[(thisSigBytes + i) >>> 2] |= thatByte << (24 - ((thisSigBytes + i) % 4) * 8); } } else { // Copy one word at a time for (var i = 0; i < thatSigBytes; i += 4) { thisWords[(thisSigBytes + i) >>> 2] = thatWords[i >>> 2]; } } this.sigBytes += thatSigBytes; // Chainable return this; }, /** * Removes insignificant bits. * * @example * * wordArray.clamp(); */ clamp: function () { // Shortcuts var words = this.words; var sigBytes = this.sigBytes; // Clamp words[sigBytes >>> 2] &= 0xffffffff << (32 - (sigBytes % 4) * 8); words.length = Math.ceil(sigBytes / 4); }, /** * Creates a copy of this word array. * * @return {WordArray} The clone. * * @example * * var clone = wordArray.clone(); */ clone: function () { var clone = Base.clone.call(this); clone.words = this.words.slice(0); return clone; }, /** * Creates a word array filled with random bytes. * * @param {number} nBytes The number of random bytes to generate. * * @return {WordArray} The random word array. * * @static * * @example * * var wordArray = CryptoJS.lib.WordArray.random(16); */ random: function (nBytes) { var words = []; var r = (function (m_w) { var m_w = m_w; var m_z = 0x3ade68b1; var mask = 0xffffffff; return function () { m_z = (0x9069 * (m_z & 0xFFFF) + (m_z >> 0x10)) & mask; m_w = (0x4650 * (m_w & 0xFFFF) + (m_w >> 0x10)) & mask; var result = ((m_z << 0x10) + m_w) & mask; result /= 0x100000000; result += 0.5; return result * (Math.random() > .5 ? 1 : -1); } }); for (var i = 0, rcache; i < nBytes; i += 4) { var _r = r((rcache || Math.random()) * 0x100000000); rcache = _r() * 0x3ade67b7; words.push((_r() * 0x100000000) | 0); } return new WordArray.init(words, nBytes); } }); /** * Encoder namespace. */ var C_enc = C.enc = {}; /** * Hex encoding strategy. */ var Hex = C_enc.Hex = { /** * Converts a word array to a hex string. * * @param {WordArray} wordArray The word array. * * @return {string} The hex string. * * @static * * @example * * var hexString = CryptoJS.enc.Hex.stringify(wordArray); */ stringify: function (wordArray) { // Shortcuts var words = wordArray.words; var sigBytes = wordArray.sigBytes; // Convert var hexChars = []; for (var i = 0; i < sigBytes; i++) { var bite = (words[i >>> 2] >>> (24 - (i % 4) * 8)) & 0xff; hexChars.push((bite >>> 4).toString(16)); hexChars.push((bite & 0x0f).toString(16)); } return hexChars.join(''); }, /** * Converts a hex string to a word array. * * @param {string} hexStr The hex string. * * @return {WordArray} The word array. * * @static * * @example * * var wordArray = CryptoJS.enc.Hex.parse(hexString); */ parse: function (hexStr) { // Shortcut var hexStrLength = hexStr.length; // Convert var words = []; for (var i = 0; i < hexStrLength; i += 2) { words[i >>> 3] |= parseInt(hexStr.substr(i, 2), 16) << (24 - (i % 8) * 4); } return new WordArray.init(words, hexStrLength / 2); } }; /** * Latin1 encoding strategy. */ var Latin1 = C_enc.Latin1 = { /** * Converts a word array to a Latin1 string. * * @param {WordArray} wordArray The word array. * * @return {string} The Latin1 string. * * @static * * @example * * var latin1String = CryptoJS.enc.Latin1.stringify(wordArray); */ stringify: function (wordArray) { // Shortcuts var words = wordArray.words; var sigBytes = wordArray.sigBytes; // Convert var latin1Chars = []; for (var i = 0; i < sigBytes; i++) { var bite = (words[i >>> 2] >>> (24 - (i % 4) * 8)) & 0xff; latin1Chars.push(String.fromCharCode(bite)); } return latin1Chars.join(''); }, /** * Converts a Latin1 string to a word array. * * @param {string} latin1Str The Latin1 string. * * @return {WordArray} The word array. * * @static * * @example * * var wordArray = CryptoJS.enc.Latin1.parse(latin1String); */ parse: function (latin1Str) { // Shortcut var latin1StrLength = latin1Str.length; // Convert var words = []; for (var i = 0; i < latin1StrLength; i++) { words[i >>> 2] |= (latin1Str.charCodeAt(i) & 0xff) << (24 - (i % 4) * 8); } return new WordArray.init(words, latin1StrLength); } }; /** * UTF-8 encoding strategy. */ var Utf8 = C_enc.Utf8 = { /** * Converts a word array to a UTF-8 string. * * @param {WordArray} wordArray The word array. * * @return {string} The UTF-8 string. * * @static * * @example * * var utf8String = CryptoJS.enc.Utf8.stringify(wordArray); */ stringify: function (wordArray) { try { return decodeURIComponent(escape(Latin1.stringify(wordArray))); } catch (e) { throw new Error('Malformed UTF-8 data'); } }, /** * Converts a UTF-8 string to a word array. * * @param {string} utf8Str The UTF-8 string. * * @return {WordArray} The word array. * * @static * * @example * * var wordArray = CryptoJS.enc.Utf8.parse(utf8String); */ parse: function (utf8Str) { return Latin1.parse(unescape(encodeURIComponent(utf8Str))); } }; /** * Abstract buffered block algorithm template. * * The property blockSize must be implemented in a concrete subtype. * * @property {number} _minBufferSize The number of blocks that should be kept unprocessed in the buffer. Default: 0 */ var BufferedBlockAlgorithm = C_lib.BufferedBlockAlgorithm = Base.extend({ /** * Resets this block algorithm's data buffer to its initial state. * * @example * * bufferedBlockAlgorithm.reset(); */ reset: function () { // Initial values this._data = new WordArray.init(); this._nDataBytes = 0; }, /** * Adds new data to this block algorithm's buffer. * * @param {WordArray|string} data The data to append. Strings are converted to a WordArray using UTF-8. * * @example * * bufferedBlockAlgorithm._append('data'); * bufferedBlockAlgorithm._append(wordArray); */ _append: function (data) { // Convert string to WordArray, else assume WordArray already if (typeof data == 'string') { data = Utf8.parse(data); } // Append this._data.concat(data); this._nDataBytes += data.sigBytes; }, /** * Processes available data blocks. * * This method invokes _doProcessBlock(offset), which must be implemented by a concrete subtype. * * @param {boolean} doFlush Whether all blocks and partial blocks should be processed. * * @return {WordArray} The processed data. * * @example * * var processedData = bufferedBlockAlgorithm._process(); * var processedData = bufferedBlockAlgorithm._process(!!'flush'); */ _process: function (doFlush) { // Shortcuts var data = this._data; var dataWords = data.words; var dataSigBytes = data.sigBytes; var blockSize = this.blockSize; var blockSizeBytes = blockSize * 4; // Count blocks ready var nBlocksReady = dataSigBytes / blockSizeBytes; if (doFlush) { // Round up to include partial blocks nBlocksReady = Math.ceil(nBlocksReady); } else { // Round down to include only full blocks, // less the number of blocks that must remain in the buffer nBlocksReady = Math.max((nBlocksReady | 0) - this._minBufferSize, 0); } // Count words ready var nWordsReady = nBlocksReady * blockSize; // Count bytes ready var nBytesReady = Math.min(nWordsReady * 4, dataSigBytes); // Process blocks if (nWordsReady) { for (var offset = 0; offset < nWordsReady; offset += blockSize) { // Perform concrete-algorithm logic this._doProcessBlock(dataWords, offset); } // Remove processed words var processedWords = dataWords.splice(0, nWordsReady); data.sigBytes -= nBytesReady; } // Return processed words return new WordArray.init(processedWords, nBytesReady); }, /** * Creates a copy of this object. * * @return {Object} The clone. * * @example * * var clone = bufferedBlockAlgorithm.clone(); */ clone: function () { var clone = Base.clone.call(this); clone._data = this._data.clone(); return clone; }, _minBufferSize: 0 }); /** * Abstract hasher template. * * @property {number} blockSize The number of 32-bit words this hasher operates on. Default: 16 (512 bits) */ var Hasher = C_lib.Hasher = BufferedBlockAlgorithm.extend({ /** * Configuration options. */ cfg: Base.extend(), /** * Initializes a newly created hasher. * * @param {Object} cfg (Optional) The configuration options to use for this hash computation. * * @example * * var hasher = CryptoJS.algo.SHA256.create(); */ init: function (cfg) { // Apply config defaults this.cfg = this.cfg.extend(cfg); // Set initial values this.reset(); }, /** * Resets this hasher to its initial state. * * @example * * hasher.reset(); */ reset: function () { // Reset data buffer BufferedBlockAlgorithm.reset.call(this); // Perform concrete-hasher logic this._doReset(); }, /** * Updates this hasher with a message. * * @param {WordArray|string} messageUpdate The message to append. * * @return {Hasher} This hasher. * * @example * * hasher.update('message'); * hasher.update(wordArray); */ update: function (messageUpdate) { // Append this._append(messageUpdate); // Update the hash this._process(); // Chainable return this; }, /** * Finalizes the hash computation. * Note that the finalize operation is effectively a destructive, read-once operation. * * @param {WordArray|string} messageUpdate (Optional) A final message update. * * @return {WordArray} The hash. * * @example * * var hash = hasher.finalize(); * var hash = hasher.finalize('message'); * var hash = hasher.finalize(wordArray); */ finalize: function (messageUpdate) { // Final message update if (messageUpdate) { this._append(messageUpdate); } // Perform concrete-hasher logic var hash = this._doFinalize(); return hash; }, blockSize: 512/32, /** * Creates a shortcut function to a hasher's object interface. * * @param {Hasher} hasher The hasher to create a helper for. * * @return {Function} The shortcut function. * * @static * * @example * * var SHA256 = CryptoJS.lib.Hasher._createHelper(CryptoJS.algo.SHA256); */ _createHelper: function (hasher) { return function (message, cfg) { return new hasher.init(cfg).finalize(message); }; }, /** * Creates a shortcut function to the HMAC's object interface. * * @param {Hasher} hasher The hasher to use in this HMAC helper. * * @return {Function} The shortcut function. * * @static * * @example * * var HmacSHA256 = CryptoJS.lib.Hasher._createHmacHelper(CryptoJS.algo.SHA256); */ _createHmacHelper: function (hasher) { return function (message, key) { return new C_algo.HMAC.init(hasher, key).finalize(message); }; } }); /** * Algorithm namespace. */ var C_algo = C.algo = {}; return C; }(Math)); return CryptoJS; })); },{}],41:[function(_dereq_,module,exports){ ;(function (root, factory) { if (typeof exports === "object") { // CommonJS module.exports = exports = factory(_dereq_("./core")); } else if (typeof define === "function" && define.amd) { // AMD define(["./core"], factory); } else { // Global (browser) factory(root.CryptoJS); } }(this, function (CryptoJS) { (function () { // Shortcuts var C = CryptoJS; var C_lib = C.lib; var WordArray = C_lib.WordArray; var C_enc = C.enc; /** * Base64 encoding strategy. */ var Base64 = C_enc.Base64 = { /** * Converts a word array to a Base64 string. * * @param {WordArray} wordArray The word array. * * @return {string} The Base64 string. * * @static * * @example * * var base64String = CryptoJS.enc.Base64.stringify(wordArray); */ stringify: function (wordArray) { // Shortcuts var words = wordArray.words; var sigBytes = wordArray.sigBytes; var map = this._map; // Clamp excess bits wordArray.clamp(); // Convert var base64Chars = []; for (var i = 0; i < sigBytes; i += 3) { var byte1 = (words[i >>> 2] >>> (24 - (i % 4) * 8)) & 0xff; var byte2 = (words[(i + 1) >>> 2] >>> (24 - ((i + 1) % 4) * 8)) & 0xff; var byte3 = (words[(i + 2) >>> 2] >>> (24 - ((i + 2) % 4) * 8)) & 0xff; var triplet = (byte1 << 16) | (byte2 << 8) | byte3; for (var j = 0; (j < 4) && (i + j * 0.75 < sigBytes); j++) { base64Chars.push(map.charAt((triplet >>> (6 * (3 - j))) & 0x3f)); } } // Add padding var paddingChar = map.charAt(64); if (paddingChar) { while (base64Chars.length % 4) { base64Chars.push(paddingChar); } } return base64Chars.join(''); }, /** * Converts a Base64 string to a word array. * * @param {string} base64Str The Base64 string. * * @return {WordArray} The word array. * * @static * * @example * * var wordArray = CryptoJS.enc.Base64.parse(base64String); */ parse: function (base64Str) { // Shortcuts var base64StrLength = base64Str.length; var map = this._map; // Ignore padding var paddingChar = map.charAt(64); if (paddingChar) { var paddingIndex = base64Str.indexOf(paddingChar); if (paddingIndex != -1) { base64StrLength = paddingIndex; } } // Convert var words = []; var nBytes = 0; for (var i = 0; i < base64StrLength; i++) { if (i % 4) { var bits1 = map.indexOf(base64Str.charAt(i - 1)) << ((i % 4) * 2); var bits2 = map.indexOf(base64Str.charAt(i)) >>> (6 - (i % 4) * 2); var bitsCombined = bits1 | bits2; words[nBytes >>> 2] |= (bitsCombined) << (24 - (nBytes % 4) * 8); nBytes++; } } return WordArray.create(words, nBytes); }, _map: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=' }; }()); return CryptoJS.enc.Base64; })); },{"./core":40}],42:[function(_dereq_,module,exports){ ;(function (root, factory) { if (typeof exports === "object") { // CommonJS module.exports = exports = factory(_dereq_("./core")); } else if (typeof define === "function" && define.amd) { // AMD define(["./core"], factory); } else { // Global (browser) factory(root.CryptoJS); } }(this, function (CryptoJS) { (function () { // Shortcuts var C = CryptoJS; var C_lib = C.lib; var WordArray = C_lib.WordArray; var C_enc = C.enc; /** * UTF-16 BE encoding strategy. */ var Utf16BE = C_enc.Utf16 = C_enc.Utf16BE = { /** * Converts a word array to a UTF-16 BE string. * * @param {WordArray} wordArray The word array. * * @return {string} The UTF-16 BE string. * * @static * * @example * * var utf16String = CryptoJS.enc.Utf16.stringify(wordArray); */ stringify: function (wordArray) { // Shortcuts var words = wordArray.words; var sigBytes = wordArray.sigBytes; // Convert var utf16Chars = []; for (var i = 0; i < sigBytes; i += 2) { var codePoint = (words[i >>> 2] >>> (16 - (i % 4) * 8)) & 0xffff; utf16Chars.push(String.fromCharCode(codePoint)); } return utf16Chars.join(''); }, /** * Converts a UTF-16 BE string to a word array. * * @param {string} utf16Str The UTF-16 BE string. * * @return {WordArray} The word array. * * @static * * @example * * var wordArray = CryptoJS.enc.Utf16.parse(utf16String); */ parse: function (utf16Str) { // Shortcut var utf16StrLength = utf16Str.length; // Convert var words = []; for (var i = 0; i < utf16StrLength; i++) { words[i >>> 1] |= utf16Str.charCodeAt(i) << (16 - (i % 2) * 16); } return WordArray.create(words, utf16StrLength * 2); } }; /** * UTF-16 LE encoding strategy. */ C_enc.Utf16LE = { /** * Converts a word array to a UTF-16 LE string. * * @param {WordArray} wordArray The word array. * * @return {string} The UTF-16 LE string. * * @static * * @example * * var utf16Str = CryptoJS.enc.Utf16LE.stringify(wordArray); */ stringify: function (wordArray) { // Shortcuts var words = wordArray.words; var sigBytes = wordArray.sigBytes; // Convert var utf16Chars = []; for (var i = 0; i < sigBytes; i += 2) { var codePoint = swapEndian((words[i >>> 2] >>> (16 - (i % 4) * 8)) & 0xffff); utf16Chars.push(String.fromCharCode(codePoint)); } return utf16Chars.join(''); }, /** * Converts a UTF-16 LE string to a word array. * * @param {string} utf16Str The UTF-16 LE string. * * @return {WordArray} The word array. * * @static * * @example * * var wordArray = CryptoJS.enc.Utf16LE.parse(utf16Str); */ parse: function (utf16Str) { // Shortcut var utf16StrLength = utf16Str.length; // Convert var words = []; for (var i = 0; i < utf16StrLength; i++) { words[i >>> 1] |= swapEndian(utf16Str.charCodeAt(i) << (16 - (i % 2) * 16)); } return WordArray.create(words, utf16StrLength * 2); } }; function swapEndian(word) { return ((word << 8) & 0xff00ff00) | ((word >>> 8) & 0x00ff00ff); } }()); return CryptoJS.enc.Utf16; })); },{"./core":40}],43:[function(_dereq_,module,exports){ ;(function (root, factory, undef) { if (typeof exports === "object") { // CommonJS module.exports = exports = factory(_dereq_("./core"), _dereq_("./sha1"), _dereq_("./hmac")); } else if (typeof define === "function" && define.amd) { // AMD define(["./core", "./sha1", "./hmac"], factory); } else { // Global (browser) factory(root.CryptoJS); } }(this, function (CryptoJS) { (function () { // Shortcuts var C = CryptoJS; var C_lib = C.lib; var Base = C_lib.Base; var WordArray = C_lib.WordArray; var C_algo = C.algo; var MD5 = C_algo.MD5; /** * This key derivation function is meant to conform with EVP_BytesToKey. * www.openssl.org/docs/crypto/EVP_BytesToKey.html */ var EvpKDF = C_algo.EvpKDF = Base.extend({ /** * Configuration options. * * @property {number} keySize The key size in words to generate. Default: 4 (128 bits) * @property {Hasher} hasher The hash algorithm to use. Default: MD5 * @property {number} iterations The number of iterations to perform. Default: 1 */ cfg: Base.extend({ keySize: 128/32, hasher: MD5, iterations: 1 }), /** * Initializes a newly created key derivation function. * * @param {Object} cfg (Optional) The configuration options to use for the derivation. * * @example * * var kdf = CryptoJS.algo.EvpKDF.create(); * var kdf = CryptoJS.algo.EvpKDF.create({ keySize: 8 }); * var kdf = CryptoJS.algo.EvpKDF.create({ keySize: 8, iterations: 1000 }); */ init: function (cfg) { this.cfg = this.cfg.extend(cfg); }, /** * Derives a key from a password. * * @param {WordArray|string} password The password. * @param {WordArray|string} salt A salt. * * @return {WordArray} The derived key. * * @example * * var key = kdf.compute(password, salt); */ compute: function (password, salt) { // Shortcut var cfg = this.cfg; // Init hasher var hasher = cfg.hasher.create(); // Initial values var derivedKey = WordArray.create(); // Shortcuts var derivedKeyWords = derivedKey.words; var keySize = cfg.keySize; var iterations = cfg.iterations; // Generate key while (derivedKeyWords.length < keySize) { if (block) { hasher.update(block); } var block = hasher.update(password).finalize(salt); hasher.reset(); // Iterations for (var i = 1; i < iterations; i++) { block = hasher.finalize(block); hasher.reset(); } derivedKey.concat(block); } derivedKey.sigBytes = keySize * 4; return derivedKey; } }); /** * Derives a key from a password. * * @param {WordArray|string} password The password. * @param {WordArray|string} salt A salt. * @param {Object} cfg (Optional) The configuration options to use for this computation. * * @return {WordArray} The derived key. * * @static * * @example * * var key = CryptoJS.EvpKDF(password, salt); * var key = CryptoJS.EvpKDF(password, salt, { keySize: 8 }); * var key = CryptoJS.EvpKDF(password, salt, { keySize: 8, iterations: 1000 }); */ C.EvpKDF = function (password, salt, cfg) { return EvpKDF.create(cfg).compute(password, salt); }; }()); return CryptoJS.EvpKDF; })); },{"./core":40,"./hmac":45,"./sha1":64}],44:[function(_dereq_,module,exports){ ;(function (root, factory, undef) { if (typeof exports === "object") { // CommonJS module.exports = exports = factory(_dereq_("./core"), _dereq_("./cipher-core")); } else if (typeof define === "function" && define.amd) { // AMD define(["./core", "./cipher-core"], factory); } else { // Global (browser) factory(root.CryptoJS); } }(this, function (CryptoJS) { (function (undefined) { // Shortcuts var C = CryptoJS; var C_lib = C.lib; var CipherParams = C_lib.CipherParams; var C_enc = C.enc; var Hex = C_enc.Hex; var C_format = C.format; var HexFormatter = C_format.Hex = { /** * Converts the ciphertext of a cipher params object to a hexadecimally encoded string. * * @param {CipherParams} cipherParams The cipher params object. * * @return {string} The hexadecimally encoded string. * * @static * * @example * * var hexString = CryptoJS.format.Hex.stringify(cipherParams); */ stringify: function (cipherParams) { return cipherParams.ciphertext.toString(Hex); }, /** * Converts a hexadecimally encoded ciphertext string to a cipher params object. * * @param {string} input The hexadecimally encoded string. * * @return {CipherParams} The cipher params object. * * @static * * @example * * var cipherParams = CryptoJS.format.Hex.parse(hexString); */ parse: function (input) { var ciphertext = Hex.parse(input); return CipherParams.create({ ciphertext: ciphertext }); } }; }()); return CryptoJS.format.Hex; })); },{"./cipher-core":39,"./core":40}],45:[function(_dereq_,module,exports){ ;(function (root, factory) { if (typeof exports === "object") { // CommonJS module.exports = exports = factory(_dereq_("./core")); } else if (typeof define === "function" && define.amd) { // AMD define(["./core"], factory); } else { // Global (browser) factory(root.CryptoJS); } }(this, function (CryptoJS) { (function () { // Shortcuts var C = CryptoJS; var C_lib = C.lib; var Base = C_lib.Base; var C_enc = C.enc; var Utf8 = C_enc.Utf8; var C_algo = C.algo; /** * HMAC algorithm. */ var HMAC = C_algo.HMAC = Base.extend({ /** * Initializes a newly created HMAC. * * @param {Hasher} hasher The hash algorithm to use. * @param {WordArray|string} key The secret key. * * @example * * var hmacHasher = CryptoJS.algo.HMAC.create(CryptoJS.algo.SHA256, key); */ init: function (hasher, key) { // Init hasher hasher = this._hasher = new hasher.init(); // Convert string to WordArray, else assume WordArray already if (typeof key == 'string') { key = Utf8.parse(key); } // Shortcuts var hasherBlockSize = hasher.blockSize; var hasherBlockSizeBytes = hasherBlockSize * 4; // Allow arbitrary length keys if (key.sigBytes > hasherBlockSizeBytes) { key = hasher.finalize(key); } // Clamp excess bits key.clamp(); // Clone key for inner and outer pads var oKey = this._oKey = key.clone(); var iKey = this._iKey = key.clone(); // Shortcuts var oKeyWords = oKey.words; var iKeyWords = iKey.words; // XOR keys with pad constants for (var i = 0; i < hasherBlockSize; i++) { oKeyWords[i] ^= 0x5c5c5c5c; iKeyWords[i] ^= 0x36363636; } oKey.sigBytes = iKey.sigBytes = hasherBlockSizeBytes; // Set initial values this.reset(); }, /** * Resets this HMAC to its initial state. * * @example * * hmacHasher.reset(); */ reset: function () { // Shortcut var hasher = this._hasher; // Reset hasher.reset(); hasher.update(this._iKey); }, /** * Updates this HMAC with a message. * * @param {WordArray|string} messageUpdate The message to append. * * @return {HMAC} This HMAC instance. * * @example * * hmacHasher.update('message'); * hmacHasher.update(wordArray); */ update: function (messageUpdate) { this._hasher.update(messageUpdate); // Chainable return this; }, /** * Finalizes the HMAC computation. * Note that the finalize operation is effectively a destructive, read-once operation. * * @param {WordArray|string} messageUpdate (Optional) A final message update. * * @return {WordArray} The HMAC. * * @example * * var hmac = hmacHasher.finalize(); * var hmac = hmacHasher.finalize('message'); * var hmac = hmacHasher.finalize(wordArray); */ finalize: function (messageUpdate) { // Shortcut var hasher = this._hasher; // Compute HMAC var innerHash = hasher.finalize(messageUpdate); hasher.reset(); var hmac = hasher.finalize(this._oKey.clone().concat(innerHash)); return hmac; } }); }()); })); },{"./core":40}],46:[function(_dereq_,module,exports){ ;(function (root, factory, undef) { if (typeof exports === "object") { // CommonJS module.exports = exports = factory(_dereq_("./core"), _dereq_("./x64-core"), _dereq_("./lib-typedarrays"), _dereq_("./enc-utf16"), _dereq_("./enc-base64"), _dereq_("./md5"), _dereq_("./sha1"), _dereq_("./sha256"), _dereq_("./sha224"), _dereq_("./sha512"), _dereq_("./sha384"), _dereq_("./sha3"), _dereq_("./ripemd160"), _dereq_("./hmac"), _dereq_("./pbkdf2"), _dereq_("./evpkdf"), _dereq_("./cipher-core"), _dereq_("./mode-cfb"), _dereq_("./mode-ctr"), _dereq_("./mode-ctr-gladman"), _dereq_("./mode-ofb"), _dereq_("./mode-ecb"), _dereq_("./pad-ansix923"), _dereq_("./pad-iso10126"), _dereq_("./pad-iso97971"), _dereq_("./pad-zeropadding"), _dereq_("./pad-nopadding"), _dereq_("./format-hex"), _dereq_("./aes"), _dereq_("./tripledes"), _dereq_("./rc4"), _dereq_("./rabbit"), _dereq_("./rabbit-legacy")); } else if (typeof define === "function" && define.amd) { // 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"], factory); } else { // Global (browser) root.CryptoJS = factory(root.CryptoJS); } }(this, function (CryptoJS) { return CryptoJS; })); },{"./aes":38,"./cipher-core":39,"./core":40,"./enc-base64":41,"./enc-utf16":42,"./evpkdf":43,"./format-hex":44,"./hmac":45,"./lib-typedarrays":47,"./md5":48,"./mode-cfb":49,"./mode-ctr":51,"./mode-ctr-gladman":50,"./mode-ecb":52,"./mode-ofb":53,"./pad-ansix923":54,"./pad-iso10126":55,"./pad-iso97971":56,"./pad-nopadding":57,"./pad-zeropadding":58,"./pbkdf2":59,"./rabbit":61,"./rabbit-legacy":60,"./rc4":62,"./ripemd160":63,"./sha1":64,"./sha224":65,"./sha256":66,"./sha3":67,"./sha384":68,"./sha512":69,"./tripledes":70,"./x64-core":71}],47:[function(_dereq_,module,exports){ ;(function (root, factory) { if (typeof exports === "object") { // CommonJS module.exports = exports = factory(_dereq_("./core")); } else if (typeof define === "function" && define.amd) { // AMD define(["./core"], factory); } else { // Global (browser) factory(root.CryptoJS); } }(this, function (CryptoJS) { (function () { // Check if typed arrays are supported if (typeof ArrayBuffer != 'function') { return; } // Shortcuts var C = CryptoJS; var C_lib = C.lib; var WordArray = C_lib.WordArray; // Reference original init var superInit = WordArray.init; // Augment WordArray.init to handle typed arrays var subInit = WordArray.init = function (typedArray) { // Convert buffers to uint8 if (typedArray instanceof ArrayBuffer) { typedArray = new Uint8Array(typedArray); } // Convert other array views to uint8 if ( typedArray instanceof Int8Array || (typeof Uint8ClampedArray !== "undefined" && typedArray instanceof Uint8ClampedArray) || typedArray instanceof Int16Array || typedArray instanceof Uint16Array || typedArray instanceof Int32Array || typedArray instanceof Uint32Array || typedArray instanceof Float32Array || typedArray instanceof Float64Array ) { typedArray = new Uint8Array(typedArray.buffer, typedArray.byteOffset, typedArray.byteLength); } // Handle Uint8Array if (typedArray instanceof Uint8Array) { // Shortcut var typedArrayByteLength = typedArray.byteLength; // Extract bytes var words = []; for (var i = 0; i < typedArrayByteLength; i++) { words[i >>> 2] |= typedArray[i] << (24 - (i % 4) * 8); } // Initialize this word array superInit.call(this, words, typedArrayByteLength); } else { // Else call normal init superInit.apply(this, arguments); } }; subInit.prototype = WordArray; }()); return CryptoJS.lib.WordArray; })); },{"./core":40}],48:[function(_dereq_,module,exports){ ;(function (root, factory) { if (typeof exports === "object") { // CommonJS module.exports = exports = factory(_dereq_("./core")); } else if (typeof define === "function" && define.amd) { // AMD define(["./core"], factory); } else { // Global (browser) factory(root.CryptoJS); } }(this, function (CryptoJS) { (function (Math) { // Shortcuts var C = CryptoJS; var C_lib = C.lib; var WordArray = C_lib.WordArray; var Hasher = C_lib.Hasher; var C_algo = C.algo; // Constants table var T = []; // Compute constants (function () { for (var i = 0; i < 64; i++) { T[i] = (Math.abs(Math.sin(i + 1)) * 0x100000000) | 0; } }()); /** * MD5 hash algorithm. */ var MD5 = C_algo.MD5 = Hasher.extend({ _doReset: function () { this._hash = new WordArray.init([ 0x67452301, 0xefcdab89, 0x98badcfe, 0x10325476 ]); }, _doProcessBlock: function (M, offset) { // Swap endian for (var i = 0; i < 16; i++) { // Shortcuts var offset_i = offset + i; var M_offset_i = M[offset_i]; M[offset_i] = ( (((M_offset_i << 8) | (M_offset_i >>> 24)) & 0x00ff00ff) | (((M_offset_i << 24) | (M_offset_i >>> 8)) & 0xff00ff00) ); } // Shortcuts var H = this._hash.words; var M_offset_0 = M[offset + 0]; var M_offset_1 = M[offset + 1]; var M_offset_2 = M[offset + 2]; var M_offset_3 = M[offset + 3]; var M_offset_4 = M[offset + 4]; var M_offset_5 = M[offset + 5]; var M_offset_6 = M[offset + 6]; var M_offset_7 = M[offset + 7]; var M_offset_8 = M[offset + 8]; var M_offset_9 = M[offset + 9]; var M_offset_10 = M[offset + 10]; var M_offset_11 = M[offset + 11]; var M_offset_12 = M[offset + 12]; var M_offset_13 = M[offset + 13]; var M_offset_14 = M[offset + 14]; var M_offset_15 = M[offset + 15]; // Working varialbes var a = H[0]; var b = H[1]; var c = H[2]; var d = H[3]; // Computation a = FF(a, b, c, d, M_offset_0, 7, T[0]); d = FF(d, a, b, c, M_offset_1, 12, T[1]); c = FF(c, d, a, b, M_offset_2, 17, T[2]); b = FF(b, c, d, a, M_offset_3, 22, T[3]); a = FF(a, b, c, d, M_offset_4, 7, T[4]); d = FF(d, a, b, c, M_offset_5, 12, T[5]); c = FF(c, d, a, b, M_offset_6, 17, T[6]); b = FF(b, c, d, a, M_offset_7, 22, T[7]); a = FF(a, b, c, d, M_offset_8, 7, T[8]); d = FF(d, a, b, c, M_offset_9, 12, T[9]); c = FF(c, d, a, b, M_offset_10, 17, T[10]); b = FF(b, c, d, a, M_offset_11, 22, T[11]); a = FF(a, b, c, d, M_offset_12, 7, T[12]); d = FF(d, a, b, c, M_offset_13, 12, T[13]); c = FF(c, d, a, b, M_offset_14, 17, T[14]); b = FF(b, c, d, a, M_offset_15, 22, T[15]); a = GG(a, b, c, d, M_offset_1, 5, T[16]); d = GG(d, a, b, c, M_offset_6, 9, T[17]); c = GG(c, d, a, b, M_offset_11, 14, T[18]); b = GG(b, c, d, a, M_offset_0, 20, T[19]); a = GG(a, b, c, d, M_offset_5, 5, T[20]); d = GG(d, a, b, c, M_offset_10, 9, T[21]); c = GG(c, d, a, b, M_offset_15, 14, T[22]); b = GG(b, c, d, a, M_offset_4, 20, T[23]); a = GG(a, b, c, d, M_offset_9, 5, T[24]); d = GG(d, a, b, c, M_offset_14, 9, T[25]); c = GG(c, d, a, b, M_offset_3, 14, T[26]); b = GG(b, c, d, a, M_offset_8, 20, T[27]); a = GG(a, b, c, d, M_offset_13, 5, T[28]); d = GG(d, a, b, c, M_offset_2, 9, T[29]); c = GG(c, d, a, b, M_offset_7, 14, T[30]); b = GG(b, c, d, a, M_offset_12, 20, T[31]); a = HH(a, b, c, d, M_offset_5, 4, T[32]); d = HH(d, a, b, c, M_offset_8, 11, T[33]); c = HH(c, d, a, b, M_offset_11, 16, T[34]); b = HH(b, c, d, a, M_offset_14, 23, T[35]); a = HH(a, b, c, d, M_offset_1, 4, T[36]); d = HH(d, a, b, c, M_offset_4, 11, T[37]); c = HH(c, d, a, b, M_offset_7, 16, T[38]); b = HH(b, c, d, a, M_offset_10, 23, T[39]); a = HH(a, b, c, d, M_offset_13, 4, T[40]); d = HH(d, a, b, c, M_offset_0, 11, T[41]); c = HH(c, d, a, b, M_offset_3, 16, T[42]); b = HH(b, c, d, a, M_offset_6, 23, T[43]); a = HH(a, b, c, d, M_offset_9, 4, T[44]); d = HH(d, a, b, c, M_offset_12, 11, T[45]); c = HH(c, d, a, b, M_offset_15, 16, T[46]); b = HH(b, c, d, a, M_offset_2, 23, T[47]); a = II(a, b, c, d, M_offset_0, 6, T[48]); d = II(d, a, b, c, M_offset_7, 10, T[49]); c = II(c, d, a, b, M_offset_14, 15, T[50]); b = II(b, c, d, a, M_offset_5, 21, T[51]); a = II(a, b, c, d, M_offset_12, 6, T[52]); d = II(d, a, b, c, M_offset_3, 10, T[53]); c = II(c, d, a, b, M_offset_10, 15, T[54]); b = II(b, c, d, a, M_offset_1, 21, T[55]); a = II(a, b, c, d, M_offset_8, 6, T[56]); d = II(d, a, b, c, M_offset_15, 10, T[57]); c = II(c, d, a, b, M_offset_6, 15, T[58]); b = II(b, c, d, a, M_offset_13, 21, T[59]); a = II(a, b, c, d, M_offset_4, 6, T[60]); d = II(d, a, b, c, M_offset_11, 10, T[61]); c = II(c, d, a, b, M_offset_2, 15, T[62]); b = II(b, c, d, a, M_offset_9, 21, T[63]); // Intermediate hash value H[0] = (H[0] + a) | 0; H[1] = (H[1] + b) | 0; H[2] = (H[2] + c) | 0; H[3] = (H[3] + d) | 0; }, _doFinalize: function () { // Shortcuts var data = this._data; var dataWords = data.words; var nBitsTotal = this._nDataBytes * 8; var nBitsLeft = data.sigBytes * 8; // Add padding dataWords[nBitsLeft >>> 5] |= 0x80 << (24 - nBitsLeft % 32); var nBitsTotalH = Math.floor(nBitsTotal / 0x100000000); var nBitsTotalL = nBitsTotal; dataWords[(((nBitsLeft + 64) >>> 9) << 4) + 15] = ( (((nBitsTotalH << 8) | (nBitsTotalH >>> 24)) & 0x00ff00ff) | (((nBitsTotalH << 24) | (nBitsTotalH >>> 8)) & 0xff00ff00) ); dataWords[(((nBitsLeft + 64) >>> 9) << 4) + 14] = ( (((nBitsTotalL << 8) | (nBitsTotalL >>> 24)) & 0x00ff00ff) | (((nBitsTotalL << 24) | (nBitsTotalL >>> 8)) & 0xff00ff00) ); data.sigBytes = (dataWords.length + 1) * 4; // Hash final blocks this._process(); // Shortcuts var hash = this._hash; var H = hash.words; // Swap endian for (var i = 0; i < 4; i++) { // Shortcut var H_i = H[i]; H[i] = (((H_i << 8) | (H_i >>> 24)) & 0x00ff00ff) | (((H_i << 24) | (H_i >>> 8)) & 0xff00ff00); } // Return final computed hash return hash; }, clone: function () { var clone = Hasher.clone.call(this); clone._hash = this._hash.clone(); return clone; } }); function FF(a, b, c, d, x, s, t) { var n = a + ((b & c) | (~b & d)) + x + t; return ((n << s) | (n >>> (32 - s))) + b; } function GG(a, b, c, d, x, s, t) { var n = a + ((b & d) | (c & ~d)) + x + t; return ((n << s) | (n >>> (32 - s))) + b; } function HH(a, b, c, d, x, s, t) { var n = a + (b ^ c ^ d) + x + t; return ((n << s) | (n >>> (32 - s))) + b; } function II(a, b, c, d, x, s, t) { var n = a + (c ^ (b | ~d)) + x + t; return ((n << s) | (n >>> (32 - s))) + b; } /** * Shortcut function to the hasher's object interface. * * @param {WordArray|string} message The message to hash. * * @return {WordArray} The hash. * * @static * * @example * * var hash = CryptoJS.MD5('message'); * var hash = CryptoJS.MD5(wordArray); */ C.MD5 = Hasher._createHelper(MD5); /** * Shortcut function to the HMAC's object interface. * * @param {WordArray|string} message The message to hash. * @param {WordArray|string} key The secret key. * * @return {WordArray} The HMAC. * * @static * * @example * * var hmac = CryptoJS.HmacMD5(message, key); */ C.HmacMD5 = Hasher._createHmacHelper(MD5); }(Math)); return CryptoJS.MD5; })); },{"./core":40}],49:[function(_dereq_,module,exports){ ;(function (root, factory, undef) { if (typeof exports === "object") { // CommonJS module.exports = exports = factory(_dereq_("./core"), _dereq_("./cipher-core")); } else if (typeof define === "function" && define.amd) { // AMD define(["./core", "./cipher-core"], factory); } else { // Global (browser) factory(root.CryptoJS); } }(this, function (CryptoJS) { /** * Cipher Feedback block mode. */ CryptoJS.mode.CFB = (function () { var CFB = CryptoJS.lib.BlockCipherMode.extend(); CFB.Encryptor = CFB.extend({ processBlock: function (words, offset) { // Shortcuts var cipher = this._cipher; var blockSize = cipher.blockSize; generateKeystreamAndEncrypt.call(this, words, offset, blockSize, cipher); // Remember this block to use with next block this._prevBlock = words.slice(offset, offset + blockSize); } }); CFB.Decryptor = CFB.extend({ processBlock: function (words, offset) { // Shortcuts var cipher = this._cipher; var blockSize = cipher.blockSize; // Remember this block to use with next block var thisBlock = words.slice(offset, offset + blockSize); generateKeystreamAndEncrypt.call(this, words, offset, blockSize, cipher); // This block becomes the previous block this._prevBlock = thisBlock; } }); function generateKeystreamAndEncrypt(words, offset, blockSize, cipher) { // Shortcut var iv = this._iv; // Generate keystream if (iv) { var keystream = iv.slice(0); // Remove IV for subsequent blocks this._iv = undefined; } else { var keystream = this._prevBlock; } cipher.encryptBlock(keystream, 0); // Encrypt for (var i = 0; i < blockSize; i++) { words[offset + i] ^= keystream[i]; } } return CFB; }()); return CryptoJS.mode.CFB; })); },{"./cipher-core":39,"./core":40}],50:[function(_dereq_,module,exports){ ;(function (root, factory, undef) { if (typeof exports === "object") { // CommonJS module.exports = exports = factory(_dereq_("./core"), _dereq_("./cipher-core")); } else if (typeof define === "function" && define.amd) { // AMD define(["./core", "./cipher-core"], factory); } else { // Global (browser) factory(root.CryptoJS); } }(this, function (CryptoJS) { /** @preserve * Counter block mode compatible with Dr Brian Gladman fileenc.c * derived from CryptoJS.mode.CTR * Jan Hruby [email protected] */ CryptoJS.mode.CTRGladman = (function () { var CTRGladman = CryptoJS.lib.BlockCipherMode.extend(); function incWord(word) { if (((word >> 24) & 0xff) === 0xff) { //overflow var b1 = (word >> 16)&0xff; var b2 = (word >> 8)&0xff; var b3 = word & 0xff; if (b1 === 0xff) // overflow b1 { b1 = 0; if (b2 === 0xff) { b2 = 0; if (b3 === 0xff) { b3 = 0; } else { ++b3; } } else { ++b2; } } else { ++b1; } word = 0; word += (b1 << 16); word += (b2 << 8); word += b3; } else { word += (0x01 << 24); } return word; } function incCounter(counter) { if ((counter[0] = incWord(counter[0])) === 0) { // encr_data in fileenc.c from Dr Brian Gladman's counts only with DWORD j < 8 counter[1] = incWord(counter[1]); } return counter; } var Encryptor = CTRGladman.Encryptor = CTRGladman.extend({ processBlock: function (words, offset) { // Shortcuts var cipher = this._cipher var blockSize = cipher.blockSize; var iv = this._iv; var counter = this._counter; // Generate keystream if (iv) { counter = this._counter = iv.slice(0); // Remove IV for subsequent blocks this._iv = undefined; } incCounter(counter); var keystream = counter.slice(0); cipher.encryptBlock(keystream, 0); // Encrypt for (var i = 0; i < blockSize; i++) { words[offset + i] ^= keystream[i]; } } }); CTRGladman.Decryptor = Encryptor; return CTRGladman; }()); return CryptoJS.mode.CTRGladman; })); },{"./cipher-core":39,"./core":40}],51:[function(_dereq_,module,exports){ ;(function (root, factory, undef) { if (typeof exports === "object") { // CommonJS module.exports = exports = factory(_dereq_("./core"), _dereq_("./cipher-core")); } else if (typeof define === "function" && define.amd) { // AMD define(["./core", "./cipher-core"], factory); } else { // Global (browser) factory(root.CryptoJS); } }(this, function (CryptoJS) { /** * Counter block mode. */ CryptoJS.mode.CTR = (function () { var CTR = CryptoJS.lib.BlockCipherMode.extend(); var Encryptor = CTR.Encryptor = CTR.extend({ processBlock: function (words, offset) { // Shortcuts var cipher = this._cipher var blockSize = cipher.blockSize; var iv = this._iv; var counter = this._counter; // Generate keystream if (iv) { counter = this._counter = iv.slice(0); // Remove IV for subsequent blocks this._iv = undefined; } var keystream = counter.slice(0); cipher.encryptBlock(keystream, 0); // Increment counter counter[blockSize - 1] = (counter[blockSize - 1] + 1) | 0 // Encrypt for (var i = 0; i < blockSize; i++) { words[offset + i] ^= keystream[i]; } } }); CTR.Decryptor = Encryptor; return CTR; }()); return CryptoJS.mode.CTR; })); },{"./cipher-core":39,"./core":40}],52:[function(_dereq_,module,exports){ ;(function (root, factory, undef) { if (typeof exports === "object") { // CommonJS module.exports = exports = factory(_dereq_("./core"), _dereq_("./cipher-core")); } else if (typeof define === "function" && define.amd) { // AMD define(["./core", "./cipher-core"], factory); } else { // Global (browser) factory(root.CryptoJS); } }(this, function (CryptoJS) { /** * Electronic Codebook block mode. */ CryptoJS.mode.ECB = (function () { var ECB = CryptoJS.lib.BlockCipherMode.extend(); ECB.Encryptor = ECB.extend({ processBlock: function (words, offset) { this._cipher.encryptBlock(words, offset); } }); ECB.Decryptor = ECB.extend({ processBlock: function (words, offset) { this._cipher.decryptBlock(words, offset); } }); return ECB; }()); return CryptoJS.mode.ECB; })); },{"./cipher-core":39,"./core":40}],53:[function(_dereq_,module,exports){ ;(function (root, factory, undef) { if (typeof exports === "object") { // CommonJS module.exports = exports = factory(_dereq_("./core"), _dereq_("./cipher-core")); } else if (typeof define === "function" && define.amd) { // AMD define(["./core", "./cipher-core"], factory); } else { // Global (browser) factory(root.CryptoJS); } }(this, function (CryptoJS) { /** * Output Feedback block mode. */ CryptoJS.mode.OFB = (function () { var OFB = CryptoJS.lib.BlockCipherMode.extend(); var Encryptor = OFB.Encryptor = OFB.extend({ processBlock: function (words, offset) { // Shortcuts var cipher = this._cipher var blockSize = cipher.blockSize; var iv = this._iv; var keystream = this._keystream; // Generate keystream if (iv) { keystream = this._keystream = iv.slice(0); // Remove IV for subsequent blocks this._iv = undefined; } cipher.encryptBlock(keystream, 0); // Encrypt for (var i = 0; i < blockSize; i++) { words[offset + i] ^= keystream[i]; } } }); OFB.Decryptor = Encryptor; return OFB; }()); return CryptoJS.mode.OFB; })); },{"./cipher-core":39,"./core":40}],54:[function(_dereq_,module,exports){ ;(function (root, factory, undef) { if (typeof exports === "object") { // CommonJS module.exports = exports = factory(_dereq_("./core"), _dereq_("./cipher-core")); } else if (typeof define === "function" && define.amd) { // AMD define(["./core", "./cipher-core"], factory); } else { // Global (browser) factory(root.CryptoJS); } }(this, function (CryptoJS) { /** * ANSI X.923 padding strategy. */ CryptoJS.pad.AnsiX923 = { pad: function (data, blockSize) { // Shortcuts var dataSigBytes = data.sigBytes; var blockSizeBytes = blockSize * 4; // Count padding bytes var nPaddingBytes = blockSizeBytes - dataSigBytes % blockSizeBytes; // Compute last byte position var lastBytePos = dataSigBytes + nPaddingBytes - 1; // Pad data.clamp(); data.words[lastBytePos >>> 2] |= nPaddingBytes << (24 - (lastBytePos % 4) * 8); data.sigBytes += nPaddingBytes; }, unpad: function (data) { // Get number of padding bytes from last byte var nPaddingBytes = data.words[(data.sigBytes - 1) >>> 2] & 0xff; // Remove padding data.sigBytes -= nPaddingBytes; } }; return CryptoJS.pad.Ansix923; })); },{"./cipher-core":39,"./core":40}],55:[function(_dereq_,module,exports){ ;(function (root, factory, undef) { if (typeof exports === "object") { // CommonJS module.exports = exports = factory(_dereq_("./core"), _dereq_("./cipher-core")); } else if (typeof define === "function" && define.amd) { // AMD define(["./core", "./cipher-core"], factory); } else { // Global (browser) factory(root.CryptoJS); } }(this, function (CryptoJS) { /** * ISO 10126 padding strategy. */ CryptoJS.pad.Iso10126 = { pad: function (data, blockSize) { // Shortcut var blockSizeBytes = blockSize * 4; // Count padding bytes var nPaddingBytes = blockSizeBytes - data.sigBytes % blockSizeBytes; // Pad data.concat(CryptoJS.lib.WordArray.random(nPaddingBytes - 1)). concat(CryptoJS.lib.WordArray.create([nPaddingBytes << 24], 1)); }, unpad: function (data) { // Get number of padding bytes from last byte var nPaddingBytes = data.words[(data.sigBytes - 1) >>> 2] & 0xff; // Remove padding data.sigBytes -= nPaddingBytes; } }; return CryptoJS.pad.Iso10126; })); },{"./cipher-core":39,"./core":40}],56:[function(_dereq_,module,exports){ ;(function (root, factory, undef) { if (typeof exports === "object") { // CommonJS module.exports = exports = factory(_dereq_("./core"), _dereq_("./cipher-core")); } else if (typeof define === "function" && define.amd) { // AMD define(["./core", "./cipher-core"], factory); } else { // Global (browser) factory(root.CryptoJS); } }(this, function (CryptoJS) { /** * ISO/IEC 9797-1 Padding Method 2. */ CryptoJS.pad.Iso97971 = { pad: function (data, blockSize) { // Add 0x80 byte data.concat(CryptoJS.lib.WordArray.create([0x80000000], 1)); // Zero pad the rest CryptoJS.pad.ZeroPadding.pad(data, blockSize); }, unpad: function (data) { // Remove zero padding CryptoJS.pad.ZeroPadding.unpad(data); // Remove one more byte -- the 0x80 byte data.sigBytes--; } }; return CryptoJS.pad.Iso97971; })); },{"./cipher-core":39,"./core":40}],57:[function(_dereq_,module,exports){ ;(function (root, factory, undef) { if (typeof exports === "object") { // CommonJS module.exports = exports = factory(_dereq_("./core"), _dereq_("./cipher-core")); } else if (typeof define === "function" && define.amd) { // AMD define(["./core", "./cipher-core"], factory); } else { // Global (browser) factory(root.CryptoJS); } }(this, function (CryptoJS) { /** * A noop padding strategy. */ CryptoJS.pad.NoPadding = { pad: function () { }, unpad: function () { } }; return CryptoJS.pad.NoPadding; })); },{"./cipher-core":39,"./core":40}],58:[function(_dereq_,module,exports){ ;(function (root, factory, undef) { if (typeof exports === "object") { // CommonJS module.exports = exports = factory(_dereq_("./core"), _dereq_("./cipher-core")); } else if (typeof define === "function" && define.amd) { // AMD define(["./core", "./cipher-core"], factory); } else { // Global (browser) factory(root.CryptoJS); } }(this, function (CryptoJS) { /** * Zero padding strategy. */ CryptoJS.pad.ZeroPadding = { pad: function (data, blockSize) { // Shortcut var blockSizeBytes = blockSize * 4; // Pad data.clamp(); data.sigBytes += blockSizeBytes - ((data.sigBytes % blockSizeBytes) || blockSizeBytes); }, unpad: function (data) { // Shortcut var dataWords = data.words; // Unpad var i = data.sigBytes - 1; while (!((dataWords[i >>> 2] >>> (24 - (i % 4) * 8)) & 0xff)) { i--; } data.sigBytes = i + 1; } }; return CryptoJS.pad.ZeroPadding; })); },{"./cipher-core":39,"./core":40}],59:[function(_dereq_,module,exports){ ;(function (root, factory, undef) { if (typeof exports === "object") { // CommonJS module.exports = exports = factory(_dereq_("./core"), _dereq_("./sha1"), _dereq_("./hmac")); } else if (typeof define === "function" && define.amd) { // AMD define(["./core", "./sha1", "./hmac"], factory); } else { // Global (browser) factory(root.CryptoJS); } }(this, function (CryptoJS) { (function () { // Shortcuts var C = CryptoJS; var C_lib = C.lib; var Base = C_lib.Base; var WordArray = C_lib.WordArray; var C_algo = C.algo; var SHA1 = C_algo.SHA1; var HMAC = C_algo.HMAC; /** * Password-Based Key Derivation Function 2 algorithm. */ var PBKDF2 = C_algo.PBKDF2 = Base.extend({ /** * Configuration options. * * @property {number} keySize The key size in words to generate. Default: 4 (128 bits) * @property {Hasher} hasher The hasher to use. Default: SHA1 * @property {number} iterations The number of iterations to perform. Default: 1 */ cfg: Base.extend({ keySize: 128/32, hasher: SHA1, iterations: 1 }), /** * Initializes a newly created key derivation function. * * @param {Object} cfg (Optional) The configuration options to use for the derivation. * * @example * * var kdf = CryptoJS.algo.PBKDF2.create(); * var kdf = CryptoJS.algo.PBKDF2.create({ keySize: 8 }); * var kdf = CryptoJS.algo.PBKDF2.create({ keySize: 8, iterations: 1000 }); */ init: function (cfg) { this.cfg = this.cfg.extend(cfg); }, /** * Computes the Password-Based Key Derivation Function 2. * * @param {WordArray|string} password The password. * @param {WordArray|string} salt A salt. * * @return {WordArray} The derived key. * * @example * * var key = kdf.compute(password, salt); */ compute: function (password, salt) { // Shortcut var cfg = this.cfg; // Init HMAC var hmac = HMAC.create(cfg.hasher, password); // Initial values var derivedKey = WordArray.create(); var blockIndex = WordArray.create([0x00000001]); // Shortcuts var derivedKeyWords = derivedKey.words; var blockIndexWords = blockIndex.words; var keySize = cfg.keySize; var iterations = cfg.iterations; // Generate key while (derivedKeyWords.length < keySize) { var block = hmac.update(salt).finalize(blockIndex); hmac.reset(); // Shortcuts var blockWords = block.words; var blockWordsLength = blockWords.length; // Iterations var intermediate = block; for (var i = 1; i < iterations; i++) { intermediate = hmac.finalize(intermediate); hmac.reset(); // Shortcut var intermediateWords = intermediate.words; // XOR intermediate with block for (var j = 0; j < blockWordsLength; j++) { blockWords[j] ^= intermediateWords[j]; } } derivedKey.concat(block); blockIndexWords[0]++; } derivedKey.sigBytes = keySize * 4; return derivedKey; } }); /** * Computes the Password-Based Key Derivation Function 2. * * @param {WordArray|string} password The password. * @param {WordArray|string} salt A salt. * @param {Object} cfg (Optional) The configuration options to use for this computation. * * @return {WordArray} The derived key. * * @static * * @example * * var key = CryptoJS.PBKDF2(password, salt); * var key = CryptoJS.PBKDF2(password, salt, { keySize: 8 }); * var key = CryptoJS.PBKDF2(password, salt, { keySize: 8, iterations: 1000 }); */ C.PBKDF2 = function (password, salt, cfg) { return PBKDF2.create(cfg).compute(password, salt); }; }()); return CryptoJS.PBKDF2; })); },{"./core":40,"./hmac":45,"./sha1":64}],60:[function(_dereq_,module,exports){ ;(function (root, factory, undef) { if (typeof exports === "object") { // CommonJS module.exports = exports = factory(_dereq_("./core"), _dereq_("./enc-base64"), _dereq_("./md5"), _dereq_("./evpkdf"), _dereq_("./cipher-core")); } else if (typeof define === "function" && define.amd) { // AMD define(["./core", "./enc-base64", "./md5", "./evpkdf", "./cipher-core"], factory); } else { // Global (browser) factory(root.CryptoJS); } }(this, function (CryptoJS) { (function () { // Shortcuts var C = CryptoJS; var C_lib = C.lib; var StreamCipher = C_lib.StreamCipher; var C_algo = C.algo; // Reusable objects var S = []; var C_ = []; var G = []; /** * Rabbit stream cipher algorithm. * * This is a legacy version that neglected to convert the key to little-endian. * This error doesn't affect the cipher's security, * but it does affect its compatibility with other implementations. */ var RabbitLegacy = C_algo.RabbitLegacy = StreamCipher.extend({ _doReset: function () { // Shortcuts var K = this._key.words; var iv = this.cfg.iv; // Generate initial state values var X = this._X = [ K[0], (K[3] << 16) | (K[2] >>> 16), K[1], (K[0] << 16) | (K[3] >>> 16), K[2], (K[1] << 16) | (K[0] >>> 16), K[3], (K[2] << 16) | (K[1] >>> 16) ]; // Generate initial counter values var C = this._C = [ (K[2] << 16) | (K[2] >>> 16), (K[0] & 0xffff0000) | (K[1] & 0x0000ffff), (K[3] << 16) | (K[3] >>> 16), (K[1] & 0xffff0000) | (K[2] & 0x0000ffff), (K[0] << 16) | (K[0] >>> 16), (K[2] & 0xffff0000) | (K[3] & 0x0000ffff), (K[1] << 16) | (K[1] >>> 16), (K[3] & 0xffff0000) | (K[0] & 0x0000ffff) ]; // Carry bit this._b = 0; // Iterate the system four times for (var i = 0; i < 4; i++) { nextState.call(this); } // Modify the counters for (var i = 0; i < 8; i++) { C[i] ^= X[(i + 4) & 7]; } // IV setup if (iv) { // Shortcuts var IV = iv.words; var IV_0 = IV[0]; var IV_1 = IV[1]; // Generate four subvectors var i0 = (((IV_0 << 8) | (IV_0 >>> 24)) & 0x00ff00ff) | (((IV_0 << 24) | (IV_0 >>> 8)) & 0xff00ff00); var i2 = (((IV_1 << 8) | (IV_1 >>> 24)) & 0x00ff00ff) | (((IV_1 << 24) | (IV_1 >>> 8)) & 0xff00ff00); var i1 = (i0 >>> 16) | (i2 & 0xffff0000); var i3 = (i2 << 16) | (i0 & 0x0000ffff); // Modify counter values C[0] ^= i0; C[1] ^= i1; C[2] ^= i2; C[3] ^= i3; C[4] ^= i0; C[5] ^= i1; C[6] ^= i2; C[7] ^= i3; // Iterate the system four times for (var i = 0; i < 4; i++) { nextState.call(this); } } }, _doProcessBlock: function (M, offset) { // Shortcut var X = this._X; // Iterate the system nextState.call(this); // Generate four keystream words S[0] = X[0] ^ (X[5] >>> 16) ^ (X[3] << 16); S[1] = X[2] ^ (X[7] >>> 16) ^ (X[5] << 16); S[2] = X[4] ^ (X[1] >>> 16) ^ (X[7] << 16); S[3] = X[6] ^ (X[3] >>> 16) ^ (X[1] << 16); for (var i = 0; i < 4; i++) { // Swap endian S[i] = (((S[i] << 8) | (S[i] >>> 24)) & 0x00ff00ff) | (((S[i] << 24) | (S[i] >>> 8)) & 0xff00ff00); // Encrypt M[offset + i] ^= S[i]; } }, blockSize: 128/32, ivSize: 64/32 }); function nextState() { // Shortcuts var X = this._X; var C = this._C; // Save old counter values for (var i = 0; i < 8; i++) { C_[i] = C[i]; } // Calculate new counter values C[0] = (C[0] + 0x4d34d34d + this._b) | 0; C[1] = (C[1] + 0xd34d34d3 + ((C[0] >>> 0) < (C_[0] >>> 0) ? 1 : 0)) | 0; C[2] = (C[2] + 0x34d34d34 + ((C[1] >>> 0) < (C_[1] >>> 0) ? 1 : 0)) | 0; C[3] = (C[3] + 0x4d34d34d + ((C[2] >>> 0) < (C_[2] >>> 0) ? 1 : 0)) | 0; C[4] = (C[4] + 0xd34d34d3 + ((C[3] >>> 0) < (C_[3] >>> 0) ? 1 : 0)) | 0; C[5] = (C[5] + 0x34d34d34 + ((C[4] >>> 0) < (C_[4] >>> 0) ? 1 : 0)) | 0; C[6] = (C[6] + 0x4d34d34d + ((C[5] >>> 0) < (C_[5] >>> 0) ? 1 : 0)) | 0; C[7] = (C[7] + 0xd34d34d3 + ((C[6] >>> 0) < (C_[6] >>> 0) ? 1 : 0)) | 0; this._b = (C[7] >>> 0) < (C_[7] >>> 0) ? 1 : 0; // Calculate the g-values for (var i = 0; i < 8; i++) { var gx = X[i] + C[i]; // Construct high and low argument for squaring var ga = gx & 0xffff; var gb = gx >>> 16; // Calculate high and low result of squaring var gh = ((((ga * ga) >>> 17) + ga * gb) >>> 15) + gb * gb; var gl = (((gx & 0xffff0000) * gx) | 0) + (((gx & 0x0000ffff) * gx) | 0); // High XOR low G[i] = gh ^ gl; } // Calculate new state values X[0] = (G[0] + ((G[7] << 16) | (G[7] >>> 16)) + ((G[6] << 16) | (G[6] >>> 16))) | 0; X[1] = (G[1] + ((G[0] << 8) | (G[0] >>> 24)) + G[7]) | 0; X[2] = (G[2] + ((G[1] << 16) | (G[1] >>> 16)) + ((G[0] << 16) | (G[0] >>> 16))) | 0; X[3] = (G[3] + ((G[2] << 8) | (G[2] >>> 24)) + G[1]) | 0; X[4] = (G[4] + ((G[3] << 16) | (G[3] >>> 16)) + ((G[2] << 16) | (G[2] >>> 16))) | 0; X[5] = (G[5] + ((G[4] << 8) | (G[4] >>> 24)) + G[3]) | 0; X[6] = (G[6] + ((G[5] << 16) | (G[5] >>> 16)) + ((G[4] << 16) | (G[4] >>> 16))) | 0; X[7] = (G[7] + ((G[6] << 8) | (G[6] >>> 24)) + G[5]) | 0; } /** * Shortcut functions to the cipher's object interface. * * @example * * var ciphertext = CryptoJS.RabbitLegacy.encrypt(message, key, cfg); * var plaintext = CryptoJS.RabbitLegacy.decrypt(ciphertext, key, cfg); */ C.RabbitLegacy = StreamCipher._createHelper(RabbitLegacy); }()); return CryptoJS.RabbitLegacy; })); },{"./cipher-core":39,"./core":40,"./enc-base64":41,"./evpkdf":43,"./md5":48}],61:[function(_dereq_,module,exports){ ;(function (root, factory, undef) { if (typeof exports === "object") { // CommonJS module.exports = exports = factory(_dereq_("./core"), _dereq_("./enc-base64"), _dereq_("./md5"), _dereq_("./evpkdf"), _dereq_("./cipher-core")); } else if (typeof define === "function" && define.amd) { // AMD define(["./core", "./enc-base64", "./md5", "./evpkdf", "./cipher-core"], factory); } else { // Global (browser) factory(root.CryptoJS); } }(this, function (CryptoJS) { (function () { // Shortcuts var C = CryptoJS; var C_lib = C.lib; var StreamCipher = C_lib.StreamCipher; var C_algo = C.algo; // Reusable objects var S = []; var C_ = []; var G = []; /** * Rabbit stream cipher algorithm */ var Rabbit = C_algo.Rabbit = StreamCipher.extend({ _doReset: function () { // Shortcuts var K = this._key.words; var iv = this.cfg.iv; // Swap endian for (var i = 0; i < 4; i++) { K[i] = (((K[i] << 8) | (K[i] >>> 24)) & 0x00ff00ff) | (((K[i] << 24) | (K[i] >>> 8)) & 0xff00ff00); } // Generate initial state values var X = this._X = [ K[0], (K[3] << 16) | (K[2] >>> 16), K[1], (K[0] << 16) | (K[3] >>> 16), K[2], (K[1] << 16) | (K[0] >>> 16), K[3], (K[2] << 16) | (K[1] >>> 16) ]; // Generate initial counter values var C = this._C = [ (K[2] << 16) | (K[2] >>> 16), (K[0] & 0xffff0000) | (K[1] & 0x0000ffff), (K[3] << 16) | (K[3] >>> 16), (K[1] & 0xffff0000) | (K[2] & 0x0000ffff), (K[0] << 16) | (K[0] >>> 16), (K[2] & 0xffff0000) | (K[3] & 0x0000ffff), (K[1] << 16) | (K[1] >>> 16), (K[3] & 0xffff0000) | (K[0] & 0x0000ffff) ]; // Carry bit this._b = 0; // Iterate the system four times for (var i = 0; i < 4; i++) { nextState.call(this); } // Modify the counters for (var i = 0; i < 8; i++) { C[i] ^= X[(i + 4) & 7]; } // IV setup if (iv) { // Shortcuts var IV = iv.words; var IV_0 = IV[0]; var IV_1 = IV[1]; // Generate four subvectors var i0 = (((IV_0 << 8) | (IV_0 >>> 24)) & 0x00ff00ff) | (((IV_0 << 24) | (IV_0 >>> 8)) & 0xff00ff00); var i2 = (((IV_1 << 8) | (IV_1 >>> 24)) & 0x00ff00ff) | (((IV_1 << 24) | (IV_1 >>> 8)) & 0xff00ff00); var i1 = (i0 >>> 16) | (i2 & 0xffff0000); var i3 = (i2 << 16) | (i0 & 0x0000ffff); // Modify counter values C[0] ^= i0; C[1] ^= i1; C[2] ^= i2; C[3] ^= i3; C[4] ^= i0; C[5] ^= i1; C[6] ^= i2; C[7] ^= i3; // Iterate the system four times for (var i = 0; i < 4; i++) { nextState.call(this); } } }, _doProcessBlock: function (M, offset) { // Shortcut var X = this._X; // Iterate the system nextState.call(this); // Generate four keystream words S[0] = X[0] ^ (X[5] >>> 16) ^ (X[3] << 16); S[1] = X[2] ^ (X[7] >>> 16) ^ (X[5] << 16); S[2] = X[4] ^ (X[1] >>> 16) ^ (X[7] << 16); S[3] = X[6] ^ (X[3] >>> 16) ^ (X[1] << 16); for (var i = 0; i < 4; i++) { // Swap endian S[i] = (((S[i] << 8) | (S[i] >>> 24)) & 0x00ff00ff) | (((S[i] << 24) | (S[i] >>> 8)) & 0xff00ff00); // Encrypt M[offset + i] ^= S[i]; } }, blockSize: 128/32, ivSize: 64/32 }); function nextState() { // Shortcuts var X = this._X; var C = this._C; // Save old counter values for (var i = 0; i < 8; i++) { C_[i] = C[i]; } // Calculate new counter values C[0] = (C[0] + 0x4d34d34d + this._b) | 0; C[1] = (C[1] + 0xd34d34d3 + ((C[0] >>> 0) < (C_[0] >>> 0) ? 1 : 0)) | 0; C[2] = (C[2] + 0x34d34d34 + ((C[1] >>> 0) < (C_[1] >>> 0) ? 1 : 0)) | 0; C[3] = (C[3] + 0x4d34d34d + ((C[2] >>> 0) < (C_[2] >>> 0) ? 1 : 0)) | 0; C[4] = (C[4] + 0xd34d34d3 + ((C[3] >>> 0) < (C_[3] >>> 0) ? 1 : 0)) | 0; C[5] = (C[5] + 0x34d34d34 + ((C[4] >>> 0) < (C_[4] >>> 0) ? 1 : 0)) | 0; C[6] = (C[6] + 0x4d34d34d + ((C[5] >>> 0) < (C_[5] >>> 0) ? 1 : 0)) | 0; C[7] = (C[7] + 0xd34d34d3 + ((C[6] >>> 0) < (C_[6] >>> 0) ? 1 : 0)) | 0; this._b = (C[7] >>> 0) < (C_[7] >>> 0) ? 1 : 0; // Calculate the g-values for (var i = 0; i < 8; i++) { var gx = X[i] + C[i]; // Construct high and low argument for squaring var ga = gx & 0xffff; var gb = gx >>> 16; // Calculate high and low result of squaring var gh = ((((ga * ga) >>> 17) + ga * gb) >>> 15) + gb * gb; var gl = (((gx & 0xffff0000) * gx) | 0) + (((gx & 0x0000ffff) * gx) | 0); // High XOR low G[i] = gh ^ gl; } // Calculate new state values X[0] = (G[0] + ((G[7] << 16) | (G[7] >>> 16)) + ((G[6] << 16) | (G[6] >>> 16))) | 0; X[1] = (G[1] + ((G[0] << 8) | (G[0] >>> 24)) + G[7]) | 0; X[2] = (G[2] + ((G[1] << 16) | (G[1] >>> 16)) + ((G[0] << 16) | (G[0] >>> 16))) | 0; X[3] = (G[3] + ((G[2] << 8) | (G[2] >>> 24)) + G[1]) | 0; X[4] = (G[4] + ((G[3] << 16) | (G[3] >>> 16)) + ((G[2] << 16) | (G[2] >>> 16))) | 0; X[5] = (G[5] + ((G[4] << 8) | (G[4] >>> 24)) + G[3]) | 0; X[6] = (G[6] + ((G[5] << 16) | (G[5] >>> 16)) + ((G[4] << 16) | (G[4] >>> 16))) | 0; X[7] = (G[7] + ((G[6] << 8) | (G[6] >>> 24)) + G[5]) | 0; } /** * Shortcut functions to the cipher's object interface. * * @example * * var ciphertext = CryptoJS.Rabbit.encrypt(message, key, cfg); * var plaintext = CryptoJS.Rabbit.decrypt(ciphertext, key, cfg); */ C.Rabbit = StreamCipher._createHelper(Rabbit); }()); return CryptoJS.Rabbit; })); },{"./cipher-core":39,"./core":40,"./enc-base64":41,"./evpkdf":43,"./md5":48}],62:[function(_dereq_,module,exports){ ;(function (root, factory, undef) { if (typeof exports === "object") { // CommonJS module.exports = exports = factory(_dereq_("./core"), _dereq_("./enc-base64"), _dereq_("./md5"), _dereq_("./evpkdf"), _dereq_("./cipher-core")); } else if (typeof define === "function" && define.amd) { // AMD define(["./core", "./enc-base64", "./md5", "./evpkdf", "./cipher-core"], factory); } else { // Global (browser) factory(root.CryptoJS); } }(this, function (CryptoJS) { (function () { // Shortcuts var C = CryptoJS; var C_lib = C.lib; var StreamCipher = C_lib.StreamCipher; var C_algo = C.algo; /** * RC4 stream cipher algorithm. */ var RC4 = C_algo.RC4 = StreamCipher.extend({ _doReset: function () { // Shortcuts var key = this._key; var keyWords = key.words; var keySigBytes = key.sigBytes; // Init sbox var S = this._S = []; for (var i = 0; i < 256; i++) { S[i] = i; } // Key setup for (var i = 0, j = 0; i < 256; i++) { var keyByteIndex = i % keySigBytes; var keyByte = (keyWords[keyByteIndex >>> 2] >>> (24 - (keyByteIndex % 4) * 8)) & 0xff; j = (j + S[i] + keyByte) % 256; // Swap var t = S[i]; S[i] = S[j]; S[j] = t; } // Counters this._i = this._j = 0; }, _doProcessBlock: function (M, offset) { M[offset] ^= generateKeystreamWord.call(this); }, keySize: 256/32, ivSize: 0 }); function generateKeystreamWord() { // Shortcuts var S = this._S; var i = this._i; var j = this._j; // Generate keystream word var keystreamWord = 0; for (var n = 0; n < 4; n++) { i = (i + 1) % 256; j = (j + S[i]) % 256; // Swap var t = S[i]; S[i] = S[j]; S[j] = t; keystreamWord |= S[(S[i] + S[j]) % 256] << (24 - n * 8); } // Update counters this._i = i; this._j = j; return keystreamWord; } /** * Shortcut functions to the cipher's object interface. * * @example * * var ciphertext = CryptoJS.RC4.encrypt(message, key, cfg); * var plaintext = CryptoJS.RC4.decrypt(ciphertext, key, cfg); */ C.RC4 = StreamCipher._createHelper(RC4); /** * Modified RC4 stream cipher algorithm. */ var RC4Drop = C_algo.RC4Drop = RC4.extend({ /** * Configuration options. * * @property {number} drop The number of keystream words to drop. Default 192 */ cfg: RC4.cfg.extend({ drop: 192 }), _doReset: function () { RC4._doReset.call(this); // Drop for (var i = this.cfg.drop; i > 0; i--) { generateKeystreamWord.call(this); } } }); /** * Shortcut functions to the cipher's object interface. * * @example * * var ciphertext = CryptoJS.RC4Drop.encrypt(message, key, cfg); * var plaintext = CryptoJS.RC4Drop.decrypt(ciphertext, key, cfg); */ C.RC4Drop = StreamCipher._createHelper(RC4Drop); }()); return CryptoJS.RC4; })); },{"./cipher-core":39,"./core":40,"./enc-base64":41,"./evpkdf":43,"./md5":48}],63:[function(_dereq_,module,exports){ ;(function (root, factory) { if (typeof exports === "object") { // CommonJS module.exports = exports = factory(_dereq_("./core")); } else if (typeof define === "function" && define.amd) { // AMD define(["./core"], factory); } else { // Global (browser) factory(root.CryptoJS); } }(this, function (CryptoJS) { /** @preserve (c) 2012 by Cédric Mesnil. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: - Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. - Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ (function (Math) { // Shortcuts var C = CryptoJS; var C_lib = C.lib; var WordArray = C_lib.WordArray; var Hasher = C_lib.Hasher; var C_algo = C.algo; // Constants table var _zl = WordArray.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]); var _zr = WordArray.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]); var _sl = WordArray.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 ]); var _sr = WordArray.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 ]); var _hl = WordArray.create([ 0x00000000, 0x5A827999, 0x6ED9EBA1, 0x8F1BBCDC, 0xA953FD4E]); var _hr = WordArray.create([ 0x50A28BE6, 0x5C4DD124, 0x6D703EF3, 0x7A6D76E9, 0x00000000]); /** * RIPEMD160 hash algorithm. */ var RIPEMD160 = C_algo.RIPEMD160 = Hasher.extend({ _doReset: function () { this._hash = WordArray.create([0x67452301, 0xEFCDAB89, 0x98BADCFE, 0x10325476, 0xC3D2E1F0]); }, _doProcessBlock: function (M, offset) { // Swap endian for (var i = 0; i < 16; i++) { // Shortcuts var offset_i = offset + i; var M_offset_i = M[offset_i]; // Swap M[offset_i] = ( (((M_offset_i << 8) | (M_offset_i >>> 24)) & 0x00ff00ff) | (((M_offset_i << 24) | (M_offset_i >>> 8)) & 0xff00ff00) ); } // Shortcut var H = this._hash.words; var hl = _hl.words; var hr = _hr.words; var zl = _zl.words; var zr = _zr.words; var sl = _sl.words; var sr = _sr.words; // Working variables var al, bl, cl, dl, el; var ar, br, cr, dr, er; ar = al = H[0]; br = bl = H[1]; cr = cl = H[2]; dr = dl = H[3]; er = el = H[4]; // Computation var t; for (var i = 0; i < 80; i += 1) { t = (al + M[offset+zl[i]])|0; if (i<16){ t += f1(bl,cl,dl) + hl[0]; } else if (i<32) { t += f2(bl,cl,dl) + hl[1]; } else if (i<48) { t += f3(bl,cl,dl) + hl[2]; } else if (i<64) { t += f4(bl,cl,dl) + hl[3]; } else {// if (i<80) { t += f5(bl,cl,dl) + hl[4]; } t = t|0; t = rotl(t,sl[i]); t = (t+el)|0; al = el; el = dl; dl = rotl(cl, 10); cl = bl; bl = t; t = (ar + M[offset+zr[i]])|0; if (i<16){ t += f5(br,cr,dr) + hr[0]; } else if (i<32) { t += f4(br,cr,dr) + hr[1]; } else if (i<48) { t += f3(br,cr,dr) + hr[2]; } else if (i<64) { t += f2(br,cr,dr) + hr[3]; } else {// if (i<80) { t += f1(br,cr,dr) + hr[4]; } t = t|0; t = rotl(t,sr[i]) ; t = (t+er)|0; ar = er; er = dr; dr = rotl(cr, 10); cr = br; br = t; } // Intermediate hash value t = (H[1] + cl + dr)|0; H[1] = (H[2] + dl + er)|0; H[2] = (H[3] + el + ar)|0; H[3] = (H[4] + al + br)|0; H[4] = (H[0] + bl + cr)|0; H[0] = t; }, _doFinalize: function () { // Shortcuts var data = this._data; var dataWords = data.words; var nBitsTotal = this._nDataBytes * 8; var nBitsLeft = data.sigBytes * 8; // Add padding dataWords[nBitsLeft >>> 5] |= 0x80 << (24 - nBitsLeft % 32); dataWords[(((nBitsLeft + 64) >>> 9) << 4) + 14] = ( (((nBitsTotal << 8) | (nBitsTotal >>> 24)) & 0x00ff00ff) | (((nBitsTotal << 24) | (nBitsTotal >>> 8)) & 0xff00ff00) ); data.sigBytes = (dataWords.length + 1) * 4; // Hash final blocks this._process(); // Shortcuts var hash = this._hash; var H = hash.words; // Swap endian for (var i = 0; i < 5; i++) { // Shortcut var H_i = H[i]; // Swap H[i] = (((H_i << 8) | (H_i >>> 24)) & 0x00ff00ff) | (((H_i << 24) | (H_i >>> 8)) & 0xff00ff00); } // Return final computed hash return hash; }, clone: function () { var clone = Hasher.clone.call(this); clone._hash = this._hash.clone(); return clone; } }); function f1(x, y, z) { return ((x) ^ (y) ^ (z)); } function f2(x, y, z) { return (((x)&(y)) | ((~x)&(z))); } function f3(x, y, z) { return (((x) | (~(y))) ^ (z)); } function f4(x, y, z) { return (((x) & (z)) | ((y)&(~(z)))); } function f5(x, y, z) { return ((x) ^ ((y) |(~(z)))); } function rotl(x,n) { return (x<<n) | (x>>>(32-n)); } /** * Shortcut function to the hasher's object interface. * * @param {WordArray|string} message The message to hash. * * @return {WordArray} The hash. * * @static * * @example * * var hash = CryptoJS.RIPEMD160('message'); * var hash = CryptoJS.RIPEMD160(wordArray); */ C.RIPEMD160 = Hasher._createHelper(RIPEMD160); /** * Shortcut function to the HMAC's object interface. * * @param {WordArray|string} message The message to hash. * @param {WordArray|string} key The secret key. * * @return {WordArray} The HMAC. * * @static * * @example * * var hmac = CryptoJS.HmacRIPEMD160(message, key); */ C.HmacRIPEMD160 = Hasher._createHmacHelper(RIPEMD160); }(Math)); return CryptoJS.RIPEMD160; })); },{"./core":40}],64:[function(_dereq_,module,exports){ ;(function (root, factory) { if (typeof exports === "object") { // CommonJS module.exports = exports = factory(_dereq_("./core")); } else if (typeof define === "function" && define.amd) { // AMD define(["./core"], factory); } else { // Global (browser) factory(root.CryptoJS); } }(this, function (CryptoJS) { (function () { // Shortcuts var C = CryptoJS; var C_lib = C.lib; var WordArray = C_lib.WordArray; var Hasher = C_lib.Hasher; var C_algo = C.algo; // Reusable object var W = []; /** * SHA-1 hash algorithm. */ var SHA1 = C_algo.SHA1 = Hasher.extend({ _doReset: function () { this._hash = new WordArray.init([ 0x67452301, 0xefcdab89, 0x98badcfe, 0x10325476, 0xc3d2e1f0 ]); }, _doProcessBlock: function (M, offset) { // Shortcut var H = this._hash.words; // Working variables var a = H[0]; var b = H[1]; var c = H[2]; var d = H[3]; var e = H[4]; // Computation for (var i = 0; i < 80; i++) { if (i < 16) { W[i] = M[offset + i] | 0; } else { var n = W[i - 3] ^ W[i - 8] ^ W[i - 14] ^ W[i - 16]; W[i] = (n << 1) | (n >>> 31); } var t = ((a << 5) | (a >>> 27)) + e + W[i]; if (i < 20) { t += ((b & c) | (~b & d)) + 0x5a827999; } else if (i < 40) { t += (b ^ c ^ d) + 0x6ed9eba1; } else if (i < 60) { t += ((b & c) | (b & d) | (c & d)) - 0x70e44324; } else /* if (i < 80) */ { t += (b ^ c ^ d) - 0x359d3e2a; } e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t; } // Intermediate hash value H[0] = (H[0] + a) | 0; H[1] = (H[1] + b) | 0; H[2] = (H[2] + c) | 0; H[3] = (H[3] + d) | 0; H[4] = (H[4] + e) | 0; }, _doFinalize: function () { // Shortcuts var data = this._data; var dataWords = data.words; var nBitsTotal = this._nDataBytes * 8; var nBitsLeft = data.sigBytes * 8; // Add padding dataWords[nBitsLeft >>> 5] |= 0x80 << (24 - nBitsLeft % 32); dataWords[(((nBitsLeft + 64) >>> 9) << 4) + 14] = Math.floor(nBitsTotal / 0x100000000); dataWords[(((nBitsLeft + 64) >>> 9) << 4) + 15] = nBitsTotal; data.sigBytes = dataWords.length * 4; // Hash final blocks this._process(); // Return final computed hash return this._hash; }, clone: function () { var clone = Hasher.clone.call(this); clone._hash = this._hash.clone(); return clone; } }); /** * Shortcut function to the hasher's object interface. * * @param {WordArray|string} message The message to hash. * * @return {WordArray} The hash. * * @static * * @example * * var hash = CryptoJS.SHA1('message'); * var hash = CryptoJS.SHA1(wordArray); */ C.SHA1 = Hasher._createHelper(SHA1); /** * Shortcut function to the HMAC's object interface. * * @param {WordArray|string} message The message to hash. * @param {WordArray|string} key The secret key. * * @return {WordArray} The HMAC. * * @static * * @example * * var hmac = CryptoJS.HmacSHA1(message, key); */ C.HmacSHA1 = Hasher._createHmacHelper(SHA1); }()); return CryptoJS.SHA1; })); },{"./core":40}],65:[function(_dereq_,module,exports){ ;(function (root, factory, undef) { if (typeof exports === "object") { // CommonJS module.exports = exports = factory(_dereq_("./core"), _dereq_("./sha256")); } else if (typeof define === "function" && define.amd) { // AMD define(["./core", "./sha256"], factory); } else { // Global (browser) factory(root.CryptoJS); } }(this, function (CryptoJS) { (function () { // Shortcuts var C = CryptoJS; var C_lib = C.lib; var WordArray = C_lib.WordArray; var C_algo = C.algo; var SHA256 = C_algo.SHA256; /** * SHA-224 hash algorithm. */ var SHA224 = C_algo.SHA224 = SHA256.extend({ _doReset: function () { this._hash = new WordArray.init([ 0xc1059ed8, 0x367cd507, 0x3070dd17, 0xf70e5939, 0xffc00b31, 0x68581511, 0x64f98fa7, 0xbefa4fa4 ]); }, _doFinalize: function () { var hash = SHA256._doFinalize.call(this); hash.sigBytes -= 4; return hash; } }); /** * Shortcut function to the hasher's object interface. * * @param {WordArray|string} message The message to hash. * * @return {WordArray} The hash. * * @static * * @example * * var hash = CryptoJS.SHA224('message'); * var hash = CryptoJS.SHA224(wordArray); */ C.SHA224 = SHA256._createHelper(SHA224); /** * Shortcut function to the HMAC's object interface. * * @param {WordArray|string} message The message to hash. * @param {WordArray|string} key The secret key. * * @return {WordArray} The HMAC. * * @static * * @example * * var hmac = CryptoJS.HmacSHA224(message, key); */ C.HmacSHA224 = SHA256._createHmacHelper(SHA224); }()); return CryptoJS.SHA224; })); },{"./core":40,"./sha256":66}],66:[function(_dereq_,module,exports){ ;(function (root, factory) { if (typeof exports === "object") { // CommonJS module.exports = exports = factory(_dereq_("./core")); } else if (typeof define === "function" && define.amd) { // AMD define(["./core"], factory); } else { // Global (browser) factory(root.CryptoJS); } }(this, function (CryptoJS) { (function (Math) { // Shortcuts var C = CryptoJS; var C_lib = C.lib; var WordArray = C_lib.WordArray; var Hasher = C_lib.Hasher; var C_algo = C.algo; // Initialization and round constants tables var H = []; var K = []; // Compute constants (function () { function isPrime(n) { var sqrtN = Math.sqrt(n); for (var factor = 2; factor <= sqrtN; factor++) { if (!(n % factor)) { return false; } } return true; } function getFractionalBits(n) { return ((n - (n | 0)) * 0x100000000) | 0; } var n = 2; var nPrime = 0; while (nPrime < 64) { if (isPrime(n)) { if (nPrime < 8) { H[nPrime] = getFractionalBits(Math.pow(n, 1 / 2)); } K[nPrime] = getFractionalBits(Math.pow(n, 1 / 3)); nPrime++; } n++; } }()); // Reusable object var W = []; /** * SHA-256 hash algorithm. */ var SHA256 = C_algo.SHA256 = Hasher.extend({ _doReset: function () { this._hash = new WordArray.init(H.slice(0)); }, _doProcessBlock: function (M, offset) { // Shortcut var H = this._hash.words; // Working variables var a = H[0]; var b = H[1]; var c = H[2]; var d = H[3]; var e = H[4]; var f = H[5]; var g = H[6]; var h = H[7]; // Computation for (var i = 0; i < 64; i++) { if (i < 16) { W[i] = M[offset + i] | 0; } else { var gamma0x = W[i - 15]; var gamma0 = ((gamma0x << 25) | (gamma0x >>> 7)) ^ ((gamma0x << 14) | (gamma0x >>> 18)) ^ (gamma0x >>> 3); var gamma1x = W[i - 2]; var gamma1 = ((gamma1x << 15) | (gamma1x >>> 17)) ^ ((gamma1x << 13) | (gamma1x >>> 19)) ^ (gamma1x >>> 10); W[i] = gamma0 + W[i - 7] + gamma1 + W[i - 16]; } var ch = (e & f) ^ (~e & g); var maj = (a & b) ^ (a & c) ^ (b & c); var sigma0 = ((a << 30) | (a >>> 2)) ^ ((a << 19) | (a >>> 13)) ^ ((a << 10) | (a >>> 22)); var sigma1 = ((e << 26) | (e >>> 6)) ^ ((e << 21) | (e >>> 11)) ^ ((e << 7) | (e >>> 25)); var t1 = h + sigma1 + ch + K[i] + W[i]; var t2 = sigma0 + maj; h = g; g = f; f = e; e = (d + t1) | 0; d = c; c = b; b = a; a = (t1 + t2) | 0; } // Intermediate hash value H[0] = (H[0] + a) | 0; H[1] = (H[1] + b) | 0; H[2] = (H[2] + c) | 0; H[3] = (H[3] + d) | 0; H[4] = (H[4] + e) | 0; H[5] = (H[5] + f) | 0; H[6] = (H[6] + g) | 0; H[7] = (H[7] + h) | 0; }, _doFinalize: function () { // Shortcuts var data = this._data; var dataWords = data.words; var nBitsTotal = this._nDataBytes * 8; var nBitsLeft = data.sigBytes * 8; // Add padding dataWords[nBitsLeft >>> 5] |= 0x80 << (24 - nBitsLeft % 32); dataWords[(((nBitsLeft + 64) >>> 9) << 4) + 14] = Math.floor(nBitsTotal / 0x100000000); dataWords[(((nBitsLeft + 64) >>> 9) << 4) + 15] = nBitsTotal; data.sigBytes = dataWords.length * 4; // Hash final blocks this._process(); // Return final computed hash return this._hash; }, clone: function () { var clone = Hasher.clone.call(this); clone._hash = this._hash.clone(); return clone; } }); /** * Shortcut function to the hasher's object interface. * * @param {WordArray|string} message The message to hash. * * @return {WordArray} The hash. * * @static * * @example * * var hash = CryptoJS.SHA256('message'); * var hash = CryptoJS.SHA256(wordArray); */ C.SHA256 = Hasher._createHelper(SHA256); /** * Shortcut function to the HMAC's object interface. * * @param {WordArray|string} message The message to hash. * @param {WordArray|string} key The secret key. * * @return {WordArray} The HMAC. * * @static * * @example * * var hmac = CryptoJS.HmacSHA256(message, key); */ C.HmacSHA256 = Hasher._createHmacHelper(SHA256); }(Math)); return CryptoJS.SHA256; })); },{"./core":40}],67:[function(_dereq_,module,exports){ ;(function (root, factory, undef) { if (typeof exports === "object") { // CommonJS module.exports = exports = factory(_dereq_("./core"), _dereq_("./x64-core")); } else if (typeof define === "function" && define.amd) { // AMD define(["./core", "./x64-core"], factory); } else { // Global (browser) factory(root.CryptoJS); } }(this, function (CryptoJS) { (function (Math) { // Shortcuts var C = CryptoJS; var C_lib = C.lib; var WordArray = C_lib.WordArray; var Hasher = C_lib.Hasher; var C_x64 = C.x64; var X64Word = C_x64.Word; var C_algo = C.algo; // Constants tables var RHO_OFFSETS = []; var PI_INDEXES = []; var ROUND_CONSTANTS = []; // Compute Constants (function () { // Compute rho offset constants var x = 1, y = 0; for (var t = 0; t < 24; t++) { RHO_OFFSETS[x + 5 * y] = ((t + 1) * (t + 2) / 2) % 64; var newX = y % 5; var newY = (2 * x + 3 * y) % 5; x = newX; y = newY; } // Compute pi index constants for (var x = 0; x < 5; x++) { for (var y = 0; y < 5; y++) { PI_INDEXES[x + 5 * y] = y + ((2 * x + 3 * y) % 5) * 5; } } // Compute round constants var LFSR = 0x01; for (var i = 0; i < 24; i++) { var roundConstantMsw = 0; var roundConstantLsw = 0; for (var j = 0; j < 7; j++) { if (LFSR & 0x01) { var bitPosition = (1 << j) - 1; if (bitPosition < 32) { roundConstantLsw ^= 1 << bitPosition; } else /* if (bitPosition >= 32) */ { roundConstantMsw ^= 1 << (bitPosition - 32); } } // Compute next LFSR if (LFSR & 0x80) { // Primitive polynomial over GF(2): x^8 + x^6 + x^5 + x^4 + 1 LFSR = (LFSR << 1) ^ 0x71; } else { LFSR <<= 1; } } ROUND_CONSTANTS[i] = X64Word.create(roundConstantMsw, roundConstantLsw); } }()); // Reusable objects for temporary values var T = []; (function () { for (var i = 0; i < 25; i++) { T[i] = X64Word.create(); } }()); /** * SHA-3 hash algorithm. */ var SHA3 = C_algo.SHA3 = Hasher.extend({ /** * Configuration options. * * @property {number} outputLength * The desired number of bits in the output hash. * Only values permitted are: 224, 256, 384, 512. * Default: 512 */ cfg: Hasher.cfg.extend({ outputLength: 512 }), _doReset: function () { var state = this._state = [] for (var i = 0; i < 25; i++) { state[i] = new X64Word.init(); } this.blockSize = (1600 - 2 * this.cfg.outputLength) / 32; }, _doProcessBlock: function (M, offset) { // Shortcuts var state = this._state; var nBlockSizeLanes = this.blockSize / 2; // Absorb for (var i = 0; i < nBlockSizeLanes; i++) { // Shortcuts var M2i = M[offset + 2 * i]; var M2i1 = M[offset + 2 * i + 1]; // Swap endian M2i = ( (((M2i << 8) | (M2i >>> 24)) & 0x00ff00ff) | (((M2i << 24) | (M2i >>> 8)) & 0xff00ff00) ); M2i1 = ( (((M2i1 << 8) | (M2i1 >>> 24)) & 0x00ff00ff) | (((M2i1 << 24) | (M2i1 >>> 8)) & 0xff00ff00) ); // Absorb message into state var lane = state[i]; lane.high ^= M2i1; lane.low ^= M2i; } // Rounds for (var round = 0; round < 24; round++) { // Theta for (var x = 0; x < 5; x++) { // Mix column lanes var tMsw = 0, tLsw = 0; for (var y = 0; y < 5; y++) { var lane = state[x + 5 * y]; tMsw ^= lane.high; tLsw ^= lane.low; } // Temporary values var Tx = T[x]; Tx.high = tMsw; Tx.low = tLsw; } for (var x = 0; x < 5; x++) { // Shortcuts var Tx4 = T[(x + 4) % 5]; var Tx1 = T[(x + 1) % 5]; var Tx1Msw = Tx1.high; var Tx1Lsw = Tx1.low; // Mix surrounding columns var tMsw = Tx4.high ^ ((Tx1Msw << 1) | (Tx1Lsw >>> 31)); var tLsw = Tx4.low ^ ((Tx1Lsw << 1) | (Tx1Msw >>> 31)); for (var y = 0; y < 5; y++) { var lane = state[x + 5 * y]; lane.high ^= tMsw; lane.low ^= tLsw; } } // Rho Pi for (var laneIndex = 1; laneIndex < 25; laneIndex++) { // Shortcuts var lane = state[laneIndex]; var laneMsw = lane.high; var laneLsw = lane.low; var rhoOffset = RHO_OFFSETS[laneIndex]; // Rotate lanes if (rhoOffset < 32) { var tMsw = (laneMsw << rhoOffset) | (laneLsw >>> (32 - rhoOffset)); var tLsw = (laneLsw << rhoOffset) | (laneMsw >>> (32 - rhoOffset)); } else /* if (rhoOffset >= 32) */ { var tMsw = (laneLsw << (rhoOffset - 32)) | (laneMsw >>> (64 - rhoOffset)); var tLsw = (laneMsw << (rhoOffset - 32)) | (laneLsw >>> (64 - rhoOffset)); } // Transpose lanes var TPiLane = T[PI_INDEXES[laneIndex]]; TPiLane.high = tMsw; TPiLane.low = tLsw; } // Rho pi at x = y = 0 var T0 = T[0]; var state0 = state[0]; T0.high = state0.high; T0.low = state0.low; // Chi for (var x = 0; x < 5; x++) { for (var y = 0; y < 5; y++) { // Shortcuts var laneIndex = x + 5 * y; var lane = state[laneIndex]; var TLane = T[laneIndex]; var Tx1Lane = T[((x + 1) % 5) + 5 * y]; var Tx2Lane = T[((x + 2) % 5) + 5 * y]; // Mix rows lane.high = TLane.high ^ (~Tx1Lane.high & Tx2Lane.high); lane.low = TLane.low ^ (~Tx1Lane.low & Tx2Lane.low); } } // Iota var lane = state[0]; var roundConstant = ROUND_CONSTANTS[round]; lane.high ^= roundConstant.high; lane.low ^= roundConstant.low;; } }, _doFinalize: function () { // Shortcuts var data = this._data; var dataWords = data.words; var nBitsTotal = this._nDataBytes * 8; var nBitsLeft = data.sigBytes * 8; var blockSizeBits = this.blockSize * 32; // Add padding dataWords[nBitsLeft >>> 5] |= 0x1 << (24 - nBitsLeft % 32); dataWords[((Math.ceil((nBitsLeft + 1) / blockSizeBits) * blockSizeBits) >>> 5) - 1] |= 0x80; data.sigBytes = dataWords.length * 4; // Hash final blocks this._process(); // Shortcuts var state = this._state; var outputLengthBytes = this.cfg.outputLength / 8; var outputLengthLanes = outputLengthBytes / 8; // Squeeze var hashWords = []; for (var i = 0; i < outputLengthLanes; i++) { // Shortcuts var lane = state[i]; var laneMsw = lane.high; var laneLsw = lane.low; // Swap endian laneMsw = ( (((laneMsw << 8) | (laneMsw >>> 24)) & 0x00ff00ff) | (((laneMsw << 24) | (laneMsw >>> 8)) & 0xff00ff00) ); laneLsw = ( (((laneLsw << 8) | (laneLsw >>> 24)) & 0x00ff00ff) | (((laneLsw << 24) | (laneLsw >>> 8)) & 0xff00ff00) ); // Squeeze state to retrieve hash hashWords.push(laneLsw); hashWords.push(laneMsw); } // Return final computed hash return new WordArray.init(hashWords, outputLengthBytes); }, clone: function () { var clone = Hasher.clone.call(this); var state = clone._state = this._state.slice(0); for (var i = 0; i < 25; i++) { state[i] = state[i].clone(); } return clone; } }); /** * Shortcut function to the hasher's object interface. * * @param {WordArray|string} message The message to hash. * * @return {WordArray} The hash. * * @static * * @example * * var hash = CryptoJS.SHA3('message'); * var hash = CryptoJS.SHA3(wordArray); */ C.SHA3 = Hasher._createHelper(SHA3); /** * Shortcut function to the HMAC's object interface. * * @param {WordArray|string} message The message to hash. * @param {WordArray|string} key The secret key. * * @return {WordArray} The HMAC. * * @static * * @example * * var hmac = CryptoJS.HmacSHA3(message, key); */ C.HmacSHA3 = Hasher._createHmacHelper(SHA3); }(Math)); return CryptoJS.SHA3; })); },{"./core":40,"./x64-core":71}],68:[function(_dereq_,module,exports){ ;(function (root, factory, undef) { if (typeof exports === "object") { // CommonJS module.exports = exports = factory(_dereq_("./core"), _dereq_("./x64-core"), _dereq_("./sha512")); } else if (typeof define === "function" && define.amd) { // AMD define(["./core", "./x64-core", "./sha512"], factory); } else { // Global (browser) factory(root.CryptoJS); } }(this, function (CryptoJS) { (function () { // Shortcuts var C = CryptoJS; var C_x64 = C.x64; var X64Word = C_x64.Word; var X64WordArray = C_x64.WordArray; var C_algo = C.algo; var SHA512 = C_algo.SHA512; /** * SHA-384 hash algorithm. */ var SHA384 = C_algo.SHA384 = SHA512.extend({ _doReset: function () { this._hash = new X64WordArray.init([ new X64Word.init(0xcbbb9d5d, 0xc1059ed8), new X64Word.init(0x629a292a, 0x367cd507), new X64Word.init(0x9159015a, 0x3070dd17), new X64Word.init(0x152fecd8, 0xf70e5939), new X64Word.init(0x67332667, 0xffc00b31), new X64Word.init(0x8eb44a87, 0x68581511), new X64Word.init(0xdb0c2e0d, 0x64f98fa7), new X64Word.init(0x47b5481d, 0xbefa4fa4) ]); }, _doFinalize: function () { var hash = SHA512._doFinalize.call(this); hash.sigBytes -= 16; return hash; } }); /** * Shortcut function to the hasher's object interface. * * @param {WordArray|string} message The message to hash. * * @return {WordArray} The hash. * * @static * * @example * * var hash = CryptoJS.SHA384('message'); * var hash = CryptoJS.SHA384(wordArray); */ C.SHA384 = SHA512._createHelper(SHA384); /** * Shortcut function to the HMAC's object interface. * * @param {WordArray|string} message The message to hash. * @param {WordArray|string} key The secret key. * * @return {WordArray} The HMAC. * * @static * * @example * * var hmac = CryptoJS.HmacSHA384(message, key); */ C.HmacSHA384 = SHA512._createHmacHelper(SHA384); }()); return CryptoJS.SHA384; })); },{"./core":40,"./sha512":69,"./x64-core":71}],69:[function(_dereq_,module,exports){ ;(function (root, factory, undef) { if (typeof exports === "object") { // CommonJS module.exports = exports = factory(_dereq_("./core"), _dereq_("./x64-core")); } else if (typeof define === "function" && define.amd) { // AMD define(["./core", "./x64-core"], factory); } else { // Global (browser) factory(root.CryptoJS); } }(this, function (CryptoJS) { (function () { // Shortcuts var C = CryptoJS; var C_lib = C.lib; var Hasher = C_lib.Hasher; var C_x64 = C.x64; var X64Word = C_x64.Word; var X64WordArray = C_x64.WordArray; var C_algo = C.algo; function X64Word_create() { return X64Word.create.apply(X64Word, arguments); } // Constants var K = [ X64Word_create(0x428a2f98, 0xd728ae22), X64Word_create(0x71374491, 0x23ef65cd), X64Word_create(0xb5c0fbcf, 0xec4d3b2f), X64Word_create(0xe9b5dba5, 0x8189dbbc), X64Word_create(0x3956c25b, 0xf348b538), X64Word_create(0x59f111f1, 0xb605d019), X64Word_create(0x923f82a4, 0xaf194f9b), X64Word_create(0xab1c5ed5, 0xda6d8118), X64Word_create(0xd807aa98, 0xa3030242), X64Word_create(0x12835b01, 0x45706fbe), X64Word_create(0x243185be, 0x4ee4b28c), X64Word_create(0x550c7dc3, 0xd5ffb4e2), X64Word_create(0x72be5d74, 0xf27b896f), X64Word_create(0x80deb1fe, 0x3b1696b1), X64Word_create(0x9bdc06a7, 0x25c71235), X64Word_create(0xc19bf174, 0xcf692694), X64Word_create(0xe49b69c1, 0x9ef14ad2), X64Word_create(0xefbe4786, 0x384f25e3), X64Word_create(0x0fc19dc6, 0x8b8cd5b5), X64Word_create(0x240ca1cc, 0x77ac9c65), X64Word_create(0x2de92c6f, 0x592b0275), X64Word_create(0x4a7484aa, 0x6ea6e483), X64Word_create(0x5cb0a9dc, 0xbd41fbd4), X64Word_create(0x76f988da, 0x831153b5), X64Word_create(0x983e5152, 0xee66dfab), X64Word_create(0xa831c66d, 0x2db43210), X64Word_create(0xb00327c8, 0x98fb213f), X64Word_create(0xbf597fc7, 0xbeef0ee4), X64Word_create(0xc6e00bf3, 0x3da88fc2), X64Word_create(0xd5a79147, 0x930aa725), X64Word_create(0x06ca6351, 0xe003826f), X64Word_create(0x14292967, 0x0a0e6e70), X64Word_create(0x27b70a85, 0x46d22ffc), X64Word_create(0x2e1b2138, 0x5c26c926), X64Word_create(0x4d2c6dfc, 0x5ac42aed), X64Word_create(0x53380d13, 0x9d95b3df), X64Word_create(0x650a7354, 0x8baf63de), X64Word_create(0x766a0abb, 0x3c77b2a8), X64Word_create(0x81c2c92e, 0x47edaee6), X64Word_create(0x92722c85, 0x1482353b), X64Word_create(0xa2bfe8a1, 0x4cf10364), X64Word_create(0xa81a664b, 0xbc423001), X64Word_create(0xc24b8b70, 0xd0f89791), X64Word_create(0xc76c51a3, 0x0654be30), X64Word_create(0xd192e819, 0xd6ef5218), X64Word_create(0xd6990624, 0x5565a910), X64Word_create(0xf40e3585, 0x5771202a), X64Word_create(0x106aa070, 0x32bbd1b8), X64Word_create(0x19a4c116, 0xb8d2d0c8), X64Word_create(0x1e376c08, 0x5141ab53), X64Word_create(0x2748774c, 0xdf8eeb99), X64Word_create(0x34b0bcb5, 0xe19b48a8), X64Word_create(0x391c0cb3, 0xc5c95a63), X64Word_create(0x4ed8aa4a, 0xe3418acb), X64Word_create(0x5b9cca4f, 0x7763e373), X64Word_create(0x682e6ff3, 0xd6b2b8a3), X64Word_create(0x748f82ee, 0x5defb2fc), X64Word_create(0x78a5636f, 0x43172f60), X64Word_create(0x84c87814, 0xa1f0ab72), X64Word_create(0x8cc70208, 0x1a6439ec), X64Word_create(0x90befffa, 0x23631e28), X64Word_create(0xa4506ceb, 0xde82bde9), X64Word_create(0xbef9a3f7, 0xb2c67915), X64Word_create(0xc67178f2, 0xe372532b), X64Word_create(0xca273ece, 0xea26619c), X64Word_create(0xd186b8c7, 0x21c0c207), X64Word_create(0xeada7dd6, 0xcde0eb1e), X64Word_create(0xf57d4f7f, 0xee6ed178), X64Word_create(0x06f067aa, 0x72176fba), X64Word_create(0x0a637dc5, 0xa2c898a6), X64Word_create(0x113f9804, 0xbef90dae), X64Word_create(0x1b710b35, 0x131c471b), X64Word_create(0x28db77f5, 0x23047d84), X64Word_create(0x32caab7b, 0x40c72493), X64Word_create(0x3c9ebe0a, 0x15c9bebc), X64Word_create(0x431d67c4, 0x9c100d4c), X64Word_create(0x4cc5d4be, 0xcb3e42b6), X64Word_create(0x597f299c, 0xfc657e2a), X64Word_create(0x5fcb6fab, 0x3ad6faec), X64Word_create(0x6c44198c, 0x4a475817) ]; // Reusable objects var W = []; (function () { for (var i = 0; i < 80; i++) { W[i] = X64Word_create(); } }()); /** * SHA-512 hash algorithm. */ var SHA512 = C_algo.SHA512 = Hasher.extend({ _doReset: function () { this._hash = new X64WordArray.init([ new X64Word.init(0x6a09e667, 0xf3bcc908), new X64Word.init(0xbb67ae85, 0x84caa73b), new X64Word.init(0x3c6ef372, 0xfe94f82b), new X64Word.init(0xa54ff53a, 0x5f1d36f1), new X64Word.init(0x510e527f, 0xade682d1), new X64Word.init(0x9b05688c, 0x2b3e6c1f), new X64Word.init(0x1f83d9ab, 0xfb41bd6b), new X64Word.init(0x5be0cd19, 0x137e2179) ]); }, _doProcessBlock: function (M, offset) { // Shortcuts var H = this._hash.words; var H0 = H[0]; var H1 = H[1]; var H2 = H[2]; var H3 = H[3]; var H4 = H[4]; var H5 = H[5]; var H6 = H[6]; var H7 = H[7]; var H0h = H0.high; var H0l = H0.low; var H1h = H1.high; var H1l = H1.low; var H2h = H2.high; var H2l = H2.low; var H3h = H3.high; var H3l = H3.low; var H4h = H4.high; var H4l = H4.low; var H5h = H5.high; var H5l = H5.low; var H6h = H6.high; var H6l = H6.low; var H7h = H7.high; var H7l = H7.low; // Working variables var ah = H0h; var al = H0l; var bh = H1h; var bl = H1l; var ch = H2h; var cl = H2l; var dh = H3h; var dl = H3l; var eh = H4h; var el = H4l; var fh = H5h; var fl = H5l; var gh = H6h; var gl = H6l; var hh = H7h; var hl = H7l; // Rounds for (var i = 0; i < 80; i++) { // Shortcut var Wi = W[i]; // Extend message if (i < 16) { var Wih = Wi.high = M[offset + i * 2] | 0; var Wil = Wi.low = M[offset + i * 2 + 1] | 0; } else { // Gamma0 var gamma0x = W[i - 15]; var gamma0xh = gamma0x.high; var gamma0xl = gamma0x.low; var gamma0h = ((gamma0xh >>> 1) | (gamma0xl << 31)) ^ ((gamma0xh >>> 8) | (gamma0xl << 24)) ^ (gamma0xh >>> 7); var gamma0l = ((gamma0xl >>> 1) | (gamma0xh << 31)) ^ ((gamma0xl >>> 8) | (gamma0xh << 24)) ^ ((gamma0xl >>> 7) | (gamma0xh << 25)); // Gamma1 var gamma1x = W[i - 2]; var gamma1xh = gamma1x.high; var gamma1xl = gamma1x.low; var gamma1h = ((gamma1xh >>> 19) | (gamma1xl << 13)) ^ ((gamma1xh << 3) | (gamma1xl >>> 29)) ^ (gamma1xh >>> 6); var gamma1l = ((gamma1xl >>> 19) | (gamma1xh << 13)) ^ ((gamma1xl << 3) | (gamma1xh >>> 29)) ^ ((gamma1xl >>> 6) | (gamma1xh << 26)); // W[i] = gamma0 + W[i - 7] + gamma1 + W[i - 16] var Wi7 = W[i - 7]; var Wi7h = Wi7.high; var Wi7l = Wi7.low; var Wi16 = W[i - 16]; var Wi16h = Wi16.high; var Wi16l = Wi16.low; var Wil = gamma0l + Wi7l; var Wih = gamma0h + Wi7h + ((Wil >>> 0) < (gamma0l >>> 0) ? 1 : 0); var Wil = Wil + gamma1l; var Wih = Wih + gamma1h + ((Wil >>> 0) < (gamma1l >>> 0) ? 1 : 0); var Wil = Wil + Wi16l; var Wih = Wih + Wi16h + ((Wil >>> 0) < (Wi16l >>> 0) ? 1 : 0); Wi.high = Wih; Wi.low = Wil; } var chh = (eh & fh) ^ (~eh & gh); var chl = (el & fl) ^ (~el & gl); var majh = (ah & bh) ^ (ah & ch) ^ (bh & ch); var majl = (al & bl) ^ (al & cl) ^ (bl & cl); var sigma0h = ((ah >>> 28) | (al << 4)) ^ ((ah << 30) | (al >>> 2)) ^ ((ah << 25) | (al >>> 7)); var sigma0l = ((al >>> 28) | (ah << 4)) ^ ((al << 30) | (ah >>> 2)) ^ ((al << 25) | (ah >>> 7)); var sigma1h = ((eh >>> 14) | (el << 18)) ^ ((eh >>> 18) | (el << 14)) ^ ((eh << 23) | (el >>> 9)); var sigma1l = ((el >>> 14) | (eh << 18)) ^ ((el >>> 18) | (eh << 14)) ^ ((el << 23) | (eh >>> 9)); // t1 = h + sigma1 + ch + K[i] + W[i] var Ki = K[i]; var Kih = Ki.high; var Kil = Ki.low; var t1l = hl + sigma1l; var t1h = hh + sigma1h + ((t1l >>> 0) < (hl >>> 0) ? 1 : 0); var t1l = t1l + chl; var t1h = t1h + chh + ((t1l >>> 0) < (chl >>> 0) ? 1 : 0); var t1l = t1l + Kil; var t1h = t1h + Kih + ((t1l >>> 0) < (Kil >>> 0) ? 1 : 0); var t1l = t1l + Wil; var t1h = t1h + Wih + ((t1l >>> 0) < (Wil >>> 0) ? 1 : 0); // t2 = sigma0 + maj var t2l = sigma0l + majl; var t2h = sigma0h + majh + ((t2l >>> 0) < (sigma0l >>> 0) ? 1 : 0); // Update working variables hh = gh; hl = gl; gh = fh; gl = fl; fh = eh; fl = el; el = (dl + t1l) | 0; eh = (dh + t1h + ((el >>> 0) < (dl >>> 0) ? 1 : 0)) | 0; dh = ch; dl = cl; ch = bh; cl = bl; bh = ah; bl = al; al = (t1l + t2l) | 0; ah = (t1h + t2h + ((al >>> 0) < (t1l >>> 0) ? 1 : 0)) | 0; } // Intermediate hash value H0l = H0.low = (H0l + al); H0.high = (H0h + ah + ((H0l >>> 0) < (al >>> 0) ? 1 : 0)); H1l = H1.low = (H1l + bl); H1.high = (H1h + bh + ((H1l >>> 0) < (bl >>> 0) ? 1 : 0)); H2l = H2.low = (H2l + cl); H2.high = (H2h + ch + ((H2l >>> 0) < (cl >>> 0) ? 1 : 0)); H3l = H3.low = (H3l + dl); H3.high = (H3h + dh + ((H3l >>> 0) < (dl >>> 0) ? 1 : 0)); H4l = H4.low = (H4l + el); H4.high = (H4h + eh + ((H4l >>> 0) < (el >>> 0) ? 1 : 0)); H5l = H5.low = (H5l + fl); H5.high = (H5h + fh + ((H5l >>> 0) < (fl >>> 0) ? 1 : 0)); H6l = H6.low = (H6l + gl); H6.high = (H6h + gh + ((H6l >>> 0) < (gl >>> 0) ? 1 : 0)); H7l = H7.low = (H7l + hl); H7.high = (H7h + hh + ((H7l >>> 0) < (hl >>> 0) ? 1 : 0)); }, _doFinalize: function () { // Shortcuts var data = this._data; var dataWords = data.words; var nBitsTotal = this._nDataBytes * 8; var nBitsLeft = data.sigBytes * 8; // Add padding dataWords[nBitsLeft >>> 5] |= 0x80 << (24 - nBitsLeft % 32); dataWords[(((nBitsLeft + 128) >>> 10) << 5) + 30] = Math.floor(nBitsTotal / 0x100000000); dataWords[(((nBitsLeft + 128) >>> 10) << 5) + 31] = nBitsTotal; data.sigBytes = dataWords.length * 4; // Hash final blocks this._process(); // Convert hash to 32-bit word array before returning var hash = this._hash.toX32(); // Return final computed hash return hash; }, clone: function () { var clone = Hasher.clone.call(this); clone._hash = this._hash.clone(); return clone; }, blockSize: 1024/32 }); /** * Shortcut function to the hasher's object interface. * * @param {WordArray|string} message The message to hash. * * @return {WordArray} The hash. * * @static * * @example * * var hash = CryptoJS.SHA512('message'); * var hash = CryptoJS.SHA512(wordArray); */ C.SHA512 = Hasher._createHelper(SHA512); /** * Shortcut function to the HMAC's object interface. * * @param {WordArray|string} message The message to hash. * @param {WordArray|string} key The secret key. * * @return {WordArray} The HMAC. * * @static * * @example * * var hmac = CryptoJS.HmacSHA512(message, key); */ C.HmacSHA512 = Hasher._createHmacHelper(SHA512); }()); return CryptoJS.SHA512; })); },{"./core":40,"./x64-core":71}],70:[function(_dereq_,module,exports){ ;(function (root, factory, undef) { if (typeof exports === "object") { // CommonJS module.exports = exports = factory(_dereq_("./core"), _dereq_("./enc-base64"), _dereq_("./md5"), _dereq_("./evpkdf"), _dereq_("./cipher-core")); } else if (typeof define === "function" && define.amd) { // AMD define(["./core", "./enc-base64", "./md5", "./evpkdf", "./cipher-core"], factory); } else { // Global (browser) factory(root.CryptoJS); } }(this, function (CryptoJS) { (function () { // Shortcuts var C = CryptoJS; var C_lib = C.lib; var WordArray = C_lib.WordArray; var BlockCipher = C_lib.BlockCipher; var C_algo = C.algo; // Permuted Choice 1 constants var PC1 = [ 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 ]; // Permuted Choice 2 constants var PC2 = [ 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 ]; // Cumulative bit shift constants var BIT_SHIFTS = [1, 2, 4, 6, 8, 10, 12, 14, 15, 17, 19, 21, 23, 25, 27, 28]; // SBOXes and round permutation constants var SBOX_P = [ { 0x0: 0x808200, 0x10000000: 0x8000, 0x20000000: 0x808002, 0x30000000: 0x2, 0x40000000: 0x200, 0x50000000: 0x808202, 0x60000000: 0x800202, 0x70000000: 0x800000, 0x80000000: 0x202, 0x90000000: 0x800200, 0xa0000000: 0x8200, 0xb0000000: 0x808000, 0xc0000000: 0x8002, 0xd0000000: 0x800002, 0xe0000000: 0x0, 0xf0000000: 0x8202, 0x8000000: 0x0, 0x18000000: 0x808202, 0x28000000: 0x8202, 0x38000000: 0x8000, 0x48000000: 0x808200, 0x58000000: 0x200, 0x68000000: 0x808002, 0x78000000: 0x2, 0x88000000: 0x800200, 0x98000000: 0x8200, 0xa8000000: 0x808000, 0xb8000000: 0x800202, 0xc8000000: 0x800002, 0xd8000000: 0x8002, 0xe8000000: 0x202, 0xf8000000: 0x800000, 0x1: 0x8000, 0x10000001: 0x2, 0x20000001: 0x808200, 0x30000001: 0x800000, 0x40000001: 0x808002, 0x50000001: 0x8200, 0x60000001: 0x200, 0x70000001: 0x800202, 0x80000001: 0x808202, 0x90000001: 0x808000, 0xa0000001: 0x800002, 0xb0000001: 0x8202, 0xc0000001: 0x202, 0xd0000001: 0x800200, 0xe0000001: 0x8002, 0xf0000001: 0x0, 0x8000001: 0x808202, 0x18000001: 0x808000, 0x28000001: 0x800000, 0x38000001: 0x200, 0x48000001: 0x8000, 0x58000001: 0x800002, 0x68000001: 0x2, 0x78000001: 0x8202, 0x88000001: 0x8002, 0x98000001: 0x800202, 0xa8000001: 0x202, 0xb8000001: 0x808200, 0xc8000001: 0x800200, 0xd8000001: 0x0, 0xe8000001: 0x8200, 0xf8000001: 0x808002 }, { 0x0: 0x40084010, 0x1000000: 0x4000, 0x2000000: 0x80000, 0x3000000: 0x40080010, 0x4000000: 0x40000010, 0x5000000: 0x40084000, 0x6000000: 0x40004000, 0x7000000: 0x10, 0x8000000: 0x84000, 0x9000000: 0x40004010, 0xa000000: 0x40000000, 0xb000000: 0x84010, 0xc000000: 0x80010, 0xd000000: 0x0, 0xe000000: 0x4010, 0xf000000: 0x40080000, 0x800000: 0x40004000, 0x1800000: 0x84010, 0x2800000: 0x10, 0x3800000: 0x40004010, 0x4800000: 0x40084010, 0x5800000: 0x40000000, 0x6800000: 0x80000, 0x7800000: 0x40080010, 0x8800000: 0x80010, 0x9800000: 0x0, 0xa800000: 0x4000, 0xb800000: 0x40080000, 0xc800000: 0x40000010, 0xd800000: 0x84000, 0xe800000: 0x40084000, 0xf800000: 0x4010, 0x10000000: 0x0, 0x11000000: 0x40080010, 0x12000000: 0x40004010, 0x13000000: 0x40084000, 0x14000000: 0x40080000, 0x15000000: 0x10, 0x16000000: 0x84010, 0x17000000: 0x4000, 0x18000000: 0x4010, 0x19000000: 0x80000, 0x1a000000: 0x80010, 0x1b000000: 0x40000010, 0x1c000000: 0x84000, 0x1d000000: 0x40004000, 0x1e000000: 0x40000000, 0x1f000000: 0x40084010, 0x10800000: 0x84010, 0x11800000: 0x80000, 0x12800000: 0x40080000, 0x13800000: 0x4000, 0x14800000: 0x40004000, 0x15800000: 0x40084010, 0x16800000: 0x10, 0x17800000: 0x40000000, 0x18800000: 0x40084000, 0x19800000: 0x40000010, 0x1a800000: 0x40004010, 0x1b800000: 0x80010, 0x1c800000: 0x0, 0x1d800000: 0x4010, 0x1e800000: 0x40080010, 0x1f800000: 0x84000 }, { 0x0: 0x104, 0x100000: 0x0, 0x200000: 0x4000100, 0x300000: 0x10104, 0x400000: 0x10004, 0x500000: 0x4000004, 0x600000: 0x4010104, 0x700000: 0x4010000, 0x800000: 0x4000000, 0x900000: 0x4010100, 0xa00000: 0x10100, 0xb00000: 0x4010004, 0xc00000: 0x4000104, 0xd00000: 0x10000, 0xe00000: 0x4, 0xf00000: 0x100, 0x80000: 0x4010100, 0x180000: 0x4010004, 0x280000: 0x0, 0x380000: 0x4000100, 0x480000: 0x4000004, 0x580000: 0x10000, 0x680000: 0x10004, 0x780000: 0x104, 0x880000: 0x4, 0x980000: 0x100, 0xa80000: 0x4010000, 0xb80000: 0x10104, 0xc80000: 0x10100, 0xd80000: 0x4000104, 0xe80000: 0x4010104, 0xf80000: 0x4000000, 0x1000000: 0x4010100, 0x1100000: 0x10004, 0x1200000: 0x10000, 0x1300000: 0x4000100, 0x1400000: 0x100, 0x1500000: 0x4010104, 0x1600000: 0x4000004, 0x1700000: 0x0, 0x1800000: 0x4000104, 0x1900000: 0x4000000, 0x1a00000: 0x4, 0x1b00000: 0x10100, 0x1c00000: 0x4010000, 0x1d00000: 0x104, 0x1e00000: 0x10104, 0x1f00000: 0x4010004, 0x1080000: 0x4000000, 0x1180000: 0x104, 0x1280000: 0x4010100, 0x1380000: 0x0, 0x1480000: 0x10004, 0x1580000: 0x4000100, 0x1680000: 0x100, 0x1780000: 0x4010004, 0x1880000: 0x10000, 0x1980000: 0x4010104, 0x1a80000: 0x10104, 0x1b80000: 0x4000004, 0x1c80000: 0x4000104, 0x1d80000: 0x4010000, 0x1e80000: 0x4, 0x1f80000: 0x10100 }, { 0x0: 0x80401000, 0x10000: 0x80001040, 0x20000: 0x401040, 0x30000: 0x80400000, 0x40000: 0x0, 0x50000: 0x401000, 0x60000: 0x80000040, 0x70000: 0x400040, 0x80000: 0x80000000, 0x90000: 0x400000, 0xa0000: 0x40, 0xb0000: 0x80001000, 0xc0000: 0x80400040, 0xd0000: 0x1040, 0xe0000: 0x1000, 0xf0000: 0x80401040, 0x8000: 0x80001040, 0x18000: 0x40, 0x28000: 0x80400040, 0x38000: 0x80001000, 0x48000: 0x401000, 0x58000: 0x80401040, 0x68000: 0x0, 0x78000: 0x80400000, 0x88000: 0x1000, 0x98000: 0x80401000, 0xa8000: 0x400000, 0xb8000: 0x1040, 0xc8000: 0x80000000, 0xd8000: 0x400040, 0xe8000: 0x401040, 0xf8000: 0x80000040, 0x100000: 0x400040, 0x110000: 0x401000, 0x120000: 0x80000040, 0x130000: 0x0, 0x140000: 0x1040, 0x150000: 0x80400040, 0x160000: 0x80401000, 0x170000: 0x80001040, 0x180000: 0x80401040, 0x190000: 0x80000000, 0x1a0000: 0x80400000, 0x1b0000: 0x401040, 0x1c0000: 0x80001000, 0x1d0000: 0x400000, 0x1e0000: 0x40, 0x1f0000: 0x1000, 0x108000: 0x80400000, 0x118000: 0x80401040, 0x128000: 0x0, 0x138000: 0x401000, 0x148000: 0x400040, 0x158000: 0x80000000, 0x168000: 0x80001040, 0x178000: 0x40, 0x188000: 0x80000040, 0x198000: 0x1000, 0x1a8000: 0x80001000, 0x1b8000: 0x80400040, 0x1c8000: 0x1040, 0x1d8000: 0x80401000, 0x1e8000: 0x400000, 0x1f8000: 0x401040 }, { 0x0: 0x80, 0x1000: 0x1040000, 0x2000: 0x40000, 0x3000: 0x20000000, 0x4000: 0x20040080, 0x5000: 0x1000080, 0x6000: 0x21000080, 0x7000: 0x40080, 0x8000: 0x1000000, 0x9000: 0x20040000, 0xa000: 0x20000080, 0xb000: 0x21040080, 0xc000: 0x21040000, 0xd000: 0x0, 0xe000: 0x1040080, 0xf000: 0x21000000, 0x800: 0x1040080, 0x1800: 0x21000080, 0x2800: 0x80, 0x3800: 0x1040000, 0x4800: 0x40000, 0x5800: 0x20040080, 0x6800: 0x21040000, 0x7800: 0x20000000, 0x8800: 0x20040000, 0x9800: 0x0, 0xa800: 0x21040080, 0xb800: 0x1000080, 0xc800: 0x20000080, 0xd800: 0x21000000, 0xe800: 0x1000000, 0xf800: 0x40080, 0x10000: 0x40000, 0x11000: 0x80, 0x12000: 0x20000000, 0x13000: 0x21000080, 0x14000: 0x1000080, 0x15000: 0x21040000, 0x16000: 0x20040080, 0x17000: 0x1000000, 0x18000: 0x21040080, 0x19000: 0x21000000, 0x1a000: 0x1040000, 0x1b000: 0x20040000, 0x1c000: 0x40080, 0x1d000: 0x20000080, 0x1e000: 0x0, 0x1f000: 0x1040080, 0x10800: 0x21000080, 0x11800: 0x1000000, 0x12800: 0x1040000, 0x13800: 0x20040080, 0x14800: 0x20000000, 0x15800: 0x1040080, 0x16800: 0x80, 0x17800: 0x21040000, 0x18800: 0x40080, 0x19800: 0x21040080, 0x1a800: 0x0, 0x1b800: 0x21000000, 0x1c800: 0x1000080, 0x1d800: 0x40000, 0x1e800: 0x20040000, 0x1f800: 0x20000080 }, { 0x0: 0x10000008, 0x100: 0x2000, 0x200: 0x10200000, 0x300: 0x10202008, 0x400: 0x10002000, 0x500: 0x200000, 0x600: 0x200008, 0x700: 0x10000000, 0x800: 0x0, 0x900: 0x10002008, 0xa00: 0x202000, 0xb00: 0x8, 0xc00: 0x10200008, 0xd00: 0x202008, 0xe00: 0x2008, 0xf00: 0x10202000, 0x80: 0x10200000, 0x180: 0x10202008, 0x280: 0x8, 0x380: 0x200000, 0x480: 0x202008, 0x580: 0x10000008, 0x680: 0x10002000, 0x780: 0x2008, 0x880: 0x200008, 0x980: 0x2000, 0xa80: 0x10002008, 0xb80: 0x10200008, 0xc80: 0x0, 0xd80: 0x10202000, 0xe80: 0x202000, 0xf80: 0x10000000, 0x1000: 0x10002000, 0x1100: 0x10200008, 0x1200: 0x10202008, 0x1300: 0x2008, 0x1400: 0x200000, 0x1500: 0x10000000, 0x1600: 0x10000008, 0x1700: 0x202000, 0x1800: 0x202008, 0x1900: 0x0, 0x1a00: 0x8, 0x1b00: 0x10200000, 0x1c00: 0x2000, 0x1d00: 0x10002008, 0x1e00: 0x10202000, 0x1f00: 0x200008, 0x1080: 0x8, 0x1180: 0x202000, 0x1280: 0x200000, 0x1380: 0x10000008, 0x1480: 0x10002000, 0x1580: 0x2008, 0x1680: 0x10202008, 0x1780: 0x10200000, 0x1880: 0x10202000, 0x1980: 0x10200008, 0x1a80: 0x2000, 0x1b80: 0x202008, 0x1c80: 0x200008, 0x1d80: 0x0, 0x1e80: 0x10000000, 0x1f80: 0x10002008 }, { 0x0: 0x100000, 0x10: 0x2000401, 0x20: 0x400, 0x30: 0x100401, 0x40: 0x2100401, 0x50: 0x0, 0x60: 0x1, 0x70: 0x2100001, 0x80: 0x2000400, 0x90: 0x100001, 0xa0: 0x2000001, 0xb0: 0x2100400, 0xc0: 0x2100000, 0xd0: 0x401, 0xe0: 0x100400, 0xf0: 0x2000000, 0x8: 0x2100001, 0x18: 0x0, 0x28: 0x2000401, 0x38: 0x2100400, 0x48: 0x100000, 0x58: 0x2000001, 0x68: 0x2000000, 0x78: 0x401, 0x88: 0x100401, 0x98: 0x2000400, 0xa8: 0x2100000, 0xb8: 0x100001, 0xc8: 0x400, 0xd8: 0x2100401, 0xe8: 0x1, 0xf8: 0x100400, 0x100: 0x2000000, 0x110: 0x100000, 0x120: 0x2000401, 0x130: 0x2100001, 0x140: 0x100001, 0x150: 0x2000400, 0x160: 0x2100400, 0x170: 0x100401, 0x180: 0x401, 0x190: 0x2100401, 0x1a0: 0x100400, 0x1b0: 0x1, 0x1c0: 0x0, 0x1d0: 0x2100000, 0x1e0: 0x2000001, 0x1f0: 0x400, 0x108: 0x100400, 0x118: 0x2000401, 0x128: 0x2100001, 0x138: 0x1, 0x148: 0x2000000, 0x158: 0x100000, 0x168: 0x401, 0x178: 0x2100400, 0x188: 0x2000001, 0x198: 0x2100000, 0x1a8: 0x0, 0x1b8: 0x2100401, 0x1c8: 0x100401, 0x1d8: 0x400, 0x1e8: 0x2000400, 0x1f8: 0x100001 }, { 0x0: 0x8000820, 0x1: 0x20000, 0x2: 0x8000000, 0x3: 0x20, 0x4: 0x20020, 0x5: 0x8020820, 0x6: 0x8020800, 0x7: 0x800, 0x8: 0x8020000, 0x9: 0x8000800, 0xa: 0x20800, 0xb: 0x8020020, 0xc: 0x820, 0xd: 0x0, 0xe: 0x8000020, 0xf: 0x20820, 0x80000000: 0x800, 0x80000001: 0x8020820, 0x80000002: 0x8000820, 0x80000003: 0x8000000, 0x80000004: 0x8020000, 0x80000005: 0x20800, 0x80000006: 0x20820, 0x80000007: 0x20, 0x80000008: 0x8000020, 0x80000009: 0x820, 0x8000000a: 0x20020, 0x8000000b: 0x8020800, 0x8000000c: 0x0, 0x8000000d: 0x8020020, 0x8000000e: 0x8000800, 0x8000000f: 0x20000, 0x10: 0x20820, 0x11: 0x8020800, 0x12: 0x20, 0x13: 0x800, 0x14: 0x8000800, 0x15: 0x8000020, 0x16: 0x8020020, 0x17: 0x20000, 0x18: 0x0, 0x19: 0x20020, 0x1a: 0x8020000, 0x1b: 0x8000820, 0x1c: 0x8020820, 0x1d: 0x20800, 0x1e: 0x820, 0x1f: 0x8000000, 0x80000010: 0x20000, 0x80000011: 0x800, 0x80000012: 0x8020020, 0x80000013: 0x20820, 0x80000014: 0x20, 0x80000015: 0x8020000, 0x80000016: 0x8000000, 0x80000017: 0x8000820, 0x80000018: 0x8020820, 0x80000019: 0x8000020, 0x8000001a: 0x8000800, 0x8000001b: 0x0, 0x8000001c: 0x20800, 0x8000001d: 0x820, 0x8000001e: 0x20020, 0x8000001f: 0x8020800 } ]; // Masks that select the SBOX input var SBOX_MASK = [ 0xf8000001, 0x1f800000, 0x01f80000, 0x001f8000, 0x0001f800, 0x00001f80, 0x000001f8, 0x8000001f ]; /** * DES block cipher algorithm. */ var DES = C_algo.DES = BlockCipher.extend({ _doReset: function () { // Shortcuts var key = this._key; var keyWords = key.words; // Select 56 bits according to PC1 var keyBits = []; for (var i = 0; i < 56; i++) { var keyBitPos = PC1[i] - 1; keyBits[i] = (keyWords[keyBitPos >>> 5] >>> (31 - keyBitPos % 32)) & 1; } // Assemble 16 subkeys var subKeys = this._subKeys = []; for (var nSubKey = 0; nSubKey < 16; nSubKey++) { // Create subkey var subKey = subKeys[nSubKey] = []; // Shortcut var bitShift = BIT_SHIFTS[nSubKey]; // Select 48 bits according to PC2 for (var i = 0; i < 24; i++) { // Select from the left 28 key bits subKey[(i / 6) | 0] |= keyBits[((PC2[i] - 1) + bitShift) % 28] << (31 - i % 6); // Select from the right 28 key bits subKey[4 + ((i / 6) | 0)] |= keyBits[28 + (((PC2[i + 24] - 1) + bitShift) % 28)] << (31 - i % 6); } // Since each subkey is applied to an expanded 32-bit input, // the subkey can be broken into 8 values scaled to 32-bits, // which allows the key to be used without expansion subKey[0] = (subKey[0] << 1) | (subKey[0] >>> 31); for (var i = 1; i < 7; i++) { subKey[i] = subKey[i] >>> ((i - 1) * 4 + 3); } subKey[7] = (subKey[7] << 5) | (subKey[7] >>> 27); } // Compute inverse subkeys var invSubKeys = this._invSubKeys = []; for (var i = 0; i < 16; i++) { invSubKeys[i] = subKeys[15 - i]; } }, encryptBlock: function (M, offset) { this._doCryptBlock(M, offset, this._subKeys); }, decryptBlock: function (M, offset) { this._doCryptBlock(M, offset, this._invSubKeys); }, _doCryptBlock: function (M, offset, subKeys) { // Get input this._lBlock = M[offset]; this._rBlock = M[offset + 1]; // Initial permutation exchangeLR.call(this, 4, 0x0f0f0f0f); exchangeLR.call(this, 16, 0x0000ffff); exchangeRL.call(this, 2, 0x33333333); exchangeRL.call(this, 8, 0x00ff00ff); exchangeLR.call(this, 1, 0x55555555); // Rounds for (var round = 0; round < 16; round++) { // Shortcuts var subKey = subKeys[round]; var lBlock = this._lBlock; var rBlock = this._rBlock; // Feistel function var f = 0; for (var i = 0; i < 8; i++) { f |= SBOX_P[i][((rBlock ^ subKey[i]) & SBOX_MASK[i]) >>> 0]; } this._lBlock = rBlock; this._rBlock = lBlock ^ f; } // Undo swap from last round var t = this._lBlock; this._lBlock = this._rBlock; this._rBlock = t; // Final permutation exchangeLR.call(this, 1, 0x55555555); exchangeRL.call(this, 8, 0x00ff00ff); exchangeRL.call(this, 2, 0x33333333); exchangeLR.call(this, 16, 0x0000ffff); exchangeLR.call(this, 4, 0x0f0f0f0f); // Set output M[offset] = this._lBlock; M[offset + 1] = this._rBlock; }, keySize: 64/32, ivSize: 64/32, blockSize: 64/32 }); // Swap bits across the left and right words function exchangeLR(offset, mask) { var t = ((this._lBlock >>> offset) ^ this._rBlock) & mask; this._rBlock ^= t; this._lBlock ^= t << offset; } function exchangeRL(offset, mask) { var t = ((this._rBlock >>> offset) ^ this._lBlock) & mask; this._lBlock ^= t; this._rBlock ^= t << offset; } /** * Shortcut functions to the cipher's object interface. * * @example * * var ciphertext = CryptoJS.DES.encrypt(message, key, cfg); * var plaintext = CryptoJS.DES.decrypt(ciphertext, key, cfg); */ C.DES = BlockCipher._createHelper(DES); /** * Triple-DES block cipher algorithm. */ var TripleDES = C_algo.TripleDES = BlockCipher.extend({ _doReset: function () { // Shortcuts var key = this._key; var keyWords = key.words; // Create DES instances this._des1 = DES.createEncryptor(WordArray.create(keyWords.slice(0, 2))); this._des2 = DES.createEncryptor(WordArray.create(keyWords.slice(2, 4))); this._des3 = DES.createEncryptor(WordArray.create(keyWords.slice(4, 6))); }, encryptBlock: function (M, offset) { this._des1.encryptBlock(M, offset); this._des2.decryptBlock(M, offset); this._des3.encryptBlock(M, offset); }, decryptBlock: function (M, offset) { this._des3.decryptBlock(M, offset); this._des2.encryptBlock(M, offset); this._des1.decryptBlock(M, offset); }, keySize: 192/32, ivSize: 64/32, blockSize: 64/32 }); /** * Shortcut functions to the cipher's object interface. * * @example * * var ciphertext = CryptoJS.TripleDES.encrypt(message, key, cfg); * var plaintext = CryptoJS.TripleDES.decrypt(ciphertext, key, cfg); */ C.TripleDES = BlockCipher._createHelper(TripleDES); }()); return CryptoJS.TripleDES; })); },{"./cipher-core":39,"./core":40,"./enc-base64":41,"./evpkdf":43,"./md5":48}],71:[function(_dereq_,module,exports){ ;(function (root, factory) { if (typeof exports === "object") { // CommonJS module.exports = exports = factory(_dereq_("./core")); } else if (typeof define === "function" && define.amd) { // AMD define(["./core"], factory); } else { // Global (browser) factory(root.CryptoJS); } }(this, function (CryptoJS) { (function (undefined) { // Shortcuts var C = CryptoJS; var C_lib = C.lib; var Base = C_lib.Base; var X32WordArray = C_lib.WordArray; /** * x64 namespace. */ var C_x64 = C.x64 = {}; /** * A 64-bit word. */ var X64Word = C_x64.Word = Base.extend({ /** * Initializes a newly created 64-bit word. * * @param {number} high The high 32 bits. * @param {number} low The low 32 bits. * * @example * * var x64Word = CryptoJS.x64.Word.create(0x00010203, 0x04050607); */ init: function (high, low) { this.high = high; this.low = low; } /** * Bitwise NOTs this word. * * @return {X64Word} A new x64-Word object after negating. * * @example * * var negated = x64Word.not(); */ // not: function () { // var high = ~this.high; // var low = ~this.low; // return X64Word.create(high, low); // }, /** * Bitwise ANDs this word with the passed word. * * @param {X64Word} word The x64-Word to AND with this word. * * @return {X64Word} A new x64-Word object after ANDing. * * @example * * var anded = x64Word.and(anotherX64Word); */ // and: function (word) { // var high = this.high & word.high; // var low = this.low & word.low; // return X64Word.create(high, low); // }, /** * Bitwise ORs this word with the passed word. * * @param {X64Word} word The x64-Word to OR with this word. * * @return {X64Word} A new x64-Word object after ORing. * * @example * * var ored = x64Word.or(anotherX64Word); */ // or: function (word) { // var high = this.high | word.high; // var low = this.low | word.low; // return X64Word.create(high, low); // }, /** * Bitwise XORs this word with the passed word. * * @param {X64Word} word The x64-Word to XOR with this word. * * @return {X64Word} A new x64-Word object after XORing. * * @example * * var xored = x64Word.xor(anotherX64Word); */ // xor: function (word) { // var high = this.high ^ word.high; // var low = this.low ^ word.low; // return X64Word.create(high, low); // }, /** * Shifts this word n bits to the left. * * @param {number} n The number of bits to shift. * * @return {X64Word} A new x64-Word object after shifting. * * @example * * var shifted = x64Word.shiftL(25); */ // shiftL: function (n) { // if (n < 32) { // var high = (this.high << n) | (this.low >>> (32 - n)); // var low = this.low << n; // } else { // var high = this.low << (n - 32); // var low = 0; // } // return X64Word.create(high, low); // }, /** * Shifts this word n bits to the right. * * @param {number} n The number of bits to shift. * * @return {X64Word} A new x64-Word object after shifting. * * @example * * var shifted = x64Word.shiftR(7); */ // shiftR: function (n) { // if (n < 32) { // var low = (this.low >>> n) | (this.high << (32 - n)); // var high = this.high >>> n; // } else { // var low = this.high >>> (n - 32); // var high = 0; // } // return X64Word.create(high, low); // }, /** * Rotates this word n bits to the left. * * @param {number} n The number of bits to rotate. * * @return {X64Word} A new x64-Word object after rotating. * * @example * * var rotated = x64Word.rotL(25); */ // rotL: function (n) { // return this.shiftL(n).or(this.shiftR(64 - n)); // }, /** * Rotates this word n bits to the right. * * @param {number} n The number of bits to rotate. * * @return {X64Word} A new x64-Word object after rotating. * * @example * * var rotated = x64Word.rotR(7); */ // rotR: function (n) { // return this.shiftR(n).or(this.shiftL(64 - n)); // }, /** * Adds this word with the passed word. * * @param {X64Word} word The x64-Word to add with this word. * * @return {X64Word} A new x64-Word object after adding. * * @example * * var added = x64Word.add(anotherX64Word); */ // add: function (word) { // var low = (this.low + word.low) | 0; // var carry = (low >>> 0) < (this.low >>> 0) ? 1 : 0; // var high = (this.high + word.high + carry) | 0; // return X64Word.create(high, low); // } }); /** * An array of 64-bit words. * * @property {Array} words The array of CryptoJS.x64.Word objects. * @property {number} sigBytes The number of significant bytes in this word array. */ var X64WordArray = C_x64.WordArray = Base.extend({ /** * Initializes a newly created word array. * * @param {Array} words (Optional) An array of CryptoJS.x64.Word objects. * @param {number} sigBytes (Optional) The number of significant bytes in the words. * * @example * * var wordArray = CryptoJS.x64.WordArray.create(); * * var wordArray = CryptoJS.x64.WordArray.create([ * CryptoJS.x64.Word.create(0x00010203, 0x04050607), * CryptoJS.x64.Word.create(0x18191a1b, 0x1c1d1e1f) * ]); * * var wordArray = CryptoJS.x64.WordArray.create([ * CryptoJS.x64.Word.create(0x00010203, 0x04050607), * CryptoJS.x64.Word.create(0x18191a1b, 0x1c1d1e1f) * ], 10); */ init: function (words, sigBytes) { words = this.words = words || []; if (sigBytes != undefined) { this.sigBytes = sigBytes; } else { this.sigBytes = words.length * 8; } }, /** * Converts this 64-bit word array to a 32-bit word array. * * @return {CryptoJS.lib.WordArray} This word array's data as a 32-bit word array. * * @example * * var x32WordArray = x64WordArray.toX32(); */ toX32: function () { // Shortcuts var x64Words = this.words; var x64WordsLength = x64Words.length; // Convert var x32Words = []; for (var i = 0; i < x64WordsLength; i++) { var x64Word = x64Words[i]; x32Words.push(x64Word.high); x32Words.push(x64Word.low); } return X32WordArray.create(x32Words, this.sigBytes); }, /** * Creates a copy of this word array. * * @return {X64WordArray} The clone. * * @example * * var clone = x64WordArray.clone(); */ clone: function () { var clone = Base.clone.call(this); // Clone "words" array var words = clone.words = this.words.slice(0); // Clone each X64Word object var wordsLength = words.length; for (var i = 0; i < wordsLength; i++) { words[i] = words[i].clone(); } return clone; } }); }()); return CryptoJS; })); },{"./core":40}],72:[function(_dereq_,module,exports){ // Some code originally from async_storage.js in // [Gaia](https://github.com/mozilla-b2g/gaia). (function() { 'use strict'; // Originally found in https://github.com/mozilla-b2g/gaia/blob/e8f624e4cc9ea945727278039b3bc9bcb9f8667a/shared/js/async_storage.js // Promises! var Promise = (typeof module !== 'undefined' && module.exports && typeof _dereq_ !== 'undefined') ? _dereq_('promise') : this.Promise; // Initialize IndexedDB; fall back to vendor-prefixed versions if needed. var indexedDB = indexedDB || this.indexedDB || this.webkitIndexedDB || this.mozIndexedDB || this.OIndexedDB || this.msIndexedDB; // If IndexedDB isn't available, we get outta here! if (!indexedDB) { return; } var DETECT_BLOB_SUPPORT_STORE = 'local-forage-detect-blob-support'; var supportsBlobs; // Abstracts constructing a Blob object, so it also works in older // browsers that don't support the native Blob constructor. (i.e. // old QtWebKit versions, at least). function _createBlob(parts, properties) { parts = parts || []; properties = properties || {}; try { return new Blob(parts, properties); } catch (e) { if (e.name !== 'TypeError') { throw e; } var BlobBuilder = window.BlobBuilder || window.MSBlobBuilder || window.MozBlobBuilder || window.WebKitBlobBuilder; var builder = new BlobBuilder(); for (var i = 0; i < parts.length; i += 1) { builder.append(parts[i]); } return builder.getBlob(properties.type); } } // Transform a binary string to an array buffer, because otherwise // weird stuff happens when you try to work with the binary string directly. // It is known. // From http://stackoverflow.com/questions/14967647/ (continues on next line) // encode-decode-image-with-base64-breaks-image (2013-04-21) function _binStringToArrayBuffer(bin) { var length = bin.length; var buf = new ArrayBuffer(length); var arr = new Uint8Array(buf); for (var i = 0; i < length; i++) { arr[i] = bin.charCodeAt(i); } return buf; } // Fetch a blob using ajax. This reveals bugs in Chrome < 43. // For details on all this junk: // https://github.com/nolanlawson/state-of-binary-data-in-the-browser#readme function _blobAjax(url) { return new Promise(function(resolve, reject) { var xhr = new XMLHttpRequest(); xhr.open('GET', url); xhr.withCredentials = true; xhr.responseType = 'arraybuffer'; xhr.onreadystatechange = function() { if (xhr.readyState !== 4) { return; } if (xhr.status === 200) { return resolve({ response: xhr.response, type: xhr.getResponseHeader('Content-Type') }); } reject({status: xhr.status, response: xhr.response}); }; xhr.send(); }); } // // Detect blob support. Chrome didn't support it until version 38. // In version 37 they had a broken version where PNGs (and possibly // other binary types) aren't stored correctly, because when you fetch // them, the content type is always null. // // Furthermore, they have some outstanding bugs where blobs occasionally // are read by FileReader as null, or by ajax as 404s. // // Sadly we use the 404 bug to detect the FileReader bug, so if they // get fixed independently and released in different versions of Chrome, // then the bug could come back. So it's worthwhile to watch these issues: // 404 bug: https://code.google.com/p/chromium/issues/detail?id=447916 // FileReader bug: https://code.google.com/p/chromium/issues/detail?id=447836 // function _checkBlobSupportWithoutCaching(idb) { return new Promise(function(resolve, reject) { var blob = _createBlob([''], {type: 'image/png'}); var txn = idb.transaction([DETECT_BLOB_SUPPORT_STORE], 'readwrite'); txn.objectStore(DETECT_BLOB_SUPPORT_STORE).put(blob, 'key'); txn.oncomplete = function() { // have to do it in a separate transaction, else the correct // content type is always returned var blobTxn = idb.transaction([DETECT_BLOB_SUPPORT_STORE], 'readwrite'); var getBlobReq = blobTxn.objectStore( DETECT_BLOB_SUPPORT_STORE).get('key'); getBlobReq.onerror = reject; getBlobReq.onsuccess = function(e) { var storedBlob = e.target.result; var url = URL.createObjectURL(storedBlob); _blobAjax(url).then(function(res) { resolve(!!(res && res.type === 'image/png')); }, function() { resolve(false); }).then(function() { URL.revokeObjectURL(url); }); }; }; })['catch'](function() { return false; // error, so assume unsupported }); } function _checkBlobSupport(idb) { if (typeof supportsBlobs === 'boolean') { return Promise.resolve(supportsBlobs); } return _checkBlobSupportWithoutCaching(idb).then(function(value) { supportsBlobs = value; return supportsBlobs; }); } // encode a blob for indexeddb engines that don't support blobs function _encodeBlob(blob) { return new Promise(function(resolve, reject) { var reader = new FileReader(); reader.onerror = reject; reader.onloadend = function(e) { var base64 = btoa(e.target.result || ''); resolve({ __local_forage_encoded_blob: true, data: base64, type: blob.type }); }; reader.readAsBinaryString(blob); }); } // decode an encoded blob function _decodeBlob(encodedBlob) { var arrayBuff = _binStringToArrayBuffer(atob(encodedBlob.data)); return _createBlob([arrayBuff], { type: encodedBlob.type}); } // is this one of our fancy encoded blobs? function _isEncodedBlob(value) { return value && value.__local_forage_encoded_blob; } // Open the IndexedDB database (automatically creates one if one didn't // previously exist), using any options set in the config. function _initStorage(options) { var self = this; var dbInfo = { db: null }; if (options) { for (var i in options) { dbInfo[i] = options[i]; } } return new Promise(function(resolve, reject) { var openreq = indexedDB.open(dbInfo.name, dbInfo.version); openreq.onerror = function() { reject(openreq.error); }; openreq.onupgradeneeded = function(e) { // First time setup: create an empty object store openreq.result.createObjectStore(dbInfo.storeName); if (e.oldVersion <= 1) { // added when support for blob shims was added openreq.result.createObjectStore(DETECT_BLOB_SUPPORT_STORE); } }; openreq.onsuccess = function() { dbInfo.db = openreq.result; self._dbInfo = dbInfo; resolve(); }; }); } function getItem(key, callback) { var self = this; // Cast the key to a string, as that's all we can set as a key. if (typeof key !== 'string') { window.console.warn(key + ' used as a key, but it is not a string.'); key = String(key); } var promise = new Promise(function(resolve, reject) { self.ready().then(function() { var dbInfo = self._dbInfo; var store = dbInfo.db.transaction(dbInfo.storeName, 'readonly') .objectStore(dbInfo.storeName); var req = store.get(key); req.onsuccess = function() { var value = req.result; if (value === undefined) { value = null; } if (_isEncodedBlob(value)) { value = _decodeBlob(value); } resolve(value); }; req.onerror = function() { reject(req.error); }; })['catch'](reject); }); executeCallback(promise, callback); return promise; } // Iterate over all items stored in database. function iterate(iterator, callback) { var self = this; var promise = new Promise(function(resolve, reject) { self.ready().then(function() { var dbInfo = self._dbInfo; var store = dbInfo.db.transaction(dbInfo.storeName, 'readonly') .objectStore(dbInfo.storeName); var req = store.openCursor(); var iterationNumber = 1; req.onsuccess = function() { var cursor = req.result; if (cursor) { var value = cursor.value; if (_isEncodedBlob(value)) { value = _decodeBlob(value); } var result = iterator(value, cursor.key, iterationNumber++); if (result !== void(0)) { resolve(result); } else { cursor['continue'](); } } else { resolve(); } }; req.onerror = function() { reject(req.error); }; })['catch'](reject); }); executeCallback(promise, callback); return promise; } function setItem(key, value, callback) { var self = this; // Cast the key to a string, as that's all we can set as a key. if (typeof key !== 'string') { window.console.warn(key + ' used as a key, but it is not a string.'); key = String(key); } var promise = new Promise(function(resolve, reject) { var dbInfo; self.ready().then(function() { dbInfo = self._dbInfo; return _checkBlobSupport(dbInfo.db); }).then(function(blobSupport) { if (!blobSupport && value instanceof Blob) { return _encodeBlob(value); } return value; }).then(function(value) { var transaction = dbInfo.db.transaction(dbInfo.storeName, 'readwrite'); var store = transaction.objectStore(dbInfo.storeName); // The reason we don't _save_ null is because IE 10 does // not support saving the `null` type in IndexedDB. How // ironic, given the bug below! // See: https://github.com/mozilla/localForage/issues/161 if (value === null) { value = undefined; } var req = store.put(value, key); transaction.oncomplete = function() { // Cast to undefined so the value passed to // callback/promise is the same as what one would get out // of `getItem()` later. This leads to some weirdness // (setItem('foo', undefined) will return `null`), but // it's not my fault localStorage is our baseline and that // it's weird. if (value === undefined) { value = null; } resolve(value); }; transaction.onabort = transaction.onerror = function() { var err = req.error ? req.error : req.transaction.error; reject(err); }; })['catch'](reject); }); executeCallback(promise, callback); return promise; } function removeItem(key, callback) { var self = this; // Cast the key to a string, as that's all we can set as a key. if (typeof key !== 'string') { window.console.warn(key + ' used as a key, but it is not a string.'); key = String(key); } var promise = new Promise(function(resolve, reject) { self.ready().then(function() { var dbInfo = self._dbInfo; var transaction = dbInfo.db.transaction(dbInfo.storeName, 'readwrite'); var store = transaction.objectStore(dbInfo.storeName); // We use a Grunt task to make this safe for IE and some // versions of Android (including those used by Cordova). // Normally IE won't like `['delete']()` and will insist on // using `['delete']()`, but we have a build step that // fixes this for us now. var req = store['delete'](key); transaction.oncomplete = function() { resolve(); }; transaction.onerror = function() { reject(req.error); }; // The request will be also be aborted if we've exceeded our storage // space. transaction.onabort = function() { var err = req.error ? req.error : req.transaction.error; reject(err); }; })['catch'](reject); }); executeCallback(promise, callback); return promise; } function clear(callback) { var self = this; var promise = new Promise(function(resolve, reject) { self.ready().then(function() { var dbInfo = self._dbInfo; var transaction = dbInfo.db.transaction(dbInfo.storeName, 'readwrite'); var store = transaction.objectStore(dbInfo.storeName); var req = store.clear(); transaction.oncomplete = function() { resolve(); }; transaction.onabort = transaction.onerror = function() { var err = req.error ? req.error : req.transaction.error; reject(err); }; })['catch'](reject); }); executeCallback(promise, callback); return promise; } function length(callback) { var self = this; var promise = new Promise(function(resolve, reject) { self.ready().then(function() { var dbInfo = self._dbInfo; var store = dbInfo.db.transaction(dbInfo.storeName, 'readonly') .objectStore(dbInfo.storeName); var req = store.count(); req.onsuccess = function() { resolve(req.result); }; req.onerror = function() { reject(req.error); }; })['catch'](reject); }); executeCallback(promise, callback); return promise; } function key(n, callback) { var self = this; var promise = new Promise(function(resolve, reject) { if (n < 0) { resolve(null); return; } self.ready().then(function() { var dbInfo = self._dbInfo; var store = dbInfo.db.transaction(dbInfo.storeName, 'readonly') .objectStore(dbInfo.storeName); var advanced = false; var req = store.openCursor(); req.onsuccess = function() { var cursor = req.result; if (!cursor) { // this means there weren't enough keys resolve(null); return; } if (n === 0) { // We have the first key, return it if that's what they // wanted. resolve(cursor.key); } else { if (!advanced) { // Otherwise, ask the cursor to skip ahead n // records. advanced = true; cursor.advance(n); } else { // When we get here, we've got the nth key. resolve(cursor.key); } } }; req.onerror = function() { reject(req.error); }; })['catch'](reject); }); executeCallback(promise, callback); return promise; } function keys(callback) { var self = this; var promise = new Promise(function(resolve, reject) { self.ready().then(function() { var dbInfo = self._dbInfo; var store = dbInfo.db.transaction(dbInfo.storeName, 'readonly') .objectStore(dbInfo.storeName); var req = store.openCursor(); var keys = []; req.onsuccess = function() { var cursor = req.result; if (!cursor) { resolve(keys); return; } keys.push(cursor.key); cursor['continue'](); }; req.onerror = function() { reject(req.error); }; })['catch'](reject); }); executeCallback(promise, callback); return promise; } function executeCallback(promise, callback) { if (callback) { promise.then(function(result) { callback(null, result); }, function(error) { callback(error); }); } } var asyncStorage = { _driver: 'asyncStorage', _initStorage: _initStorage, iterate: iterate, getItem: getItem, setItem: setItem, removeItem: removeItem, clear: clear, length: length, key: key, keys: keys }; if (typeof module !== 'undefined' && module.exports && typeof _dereq_ !== 'undefined') { module.exports = asyncStorage; } else if (typeof define === 'function' && define.amd) { define('asyncStorage', function() { return asyncStorage; }); } else { this.asyncStorage = asyncStorage; } }).call(window); },{"promise":95}],73:[function(_dereq_,module,exports){ // If IndexedDB isn't available, we'll fall back to localStorage. // Note that this will have considerable performance and storage // side-effects (all data will be serialized on save and only data that // can be converted to a string via `JSON.stringify()` will be saved). (function() { 'use strict'; // Promises! var Promise = (typeof module !== 'undefined' && module.exports && typeof _dereq_ !== 'undefined') ? _dereq_('promise') : this.Promise; var globalObject = this; var serializer = null; var localStorage = null; // If the app is running inside a Google Chrome packaged webapp, or some // other context where localStorage isn't available, we don't use // localStorage. This feature detection is preferred over the old // `if (window.chrome && window.chrome.runtime)` code. // See: https://github.com/mozilla/localForage/issues/68 try { // If localStorage isn't available, we get outta here! // This should be inside a try catch if (!this.localStorage || !('setItem' in this.localStorage)) { return; } // Initialize localStorage and create a variable to use throughout // the code. localStorage = this.localStorage; } catch (e) { return; } var ModuleType = { DEFINE: 1, EXPORT: 2, WINDOW: 3 }; // Attaching to window (i.e. no module loader) is the assumed, // simple default. var moduleType = ModuleType.WINDOW; // Find out what kind of module setup we have; if none, we'll just attach // localForage to the main window. if (typeof module !== 'undefined' && module.exports && typeof _dereq_ !== 'undefined') { moduleType = ModuleType.EXPORT; } else if (typeof define === 'function' && define.amd) { moduleType = ModuleType.DEFINE; } // Config the localStorage backend, using options set in the config. function _initStorage(options) { var self = this; var dbInfo = {}; if (options) { for (var i in options) { dbInfo[i] = options[i]; } } dbInfo.keyPrefix = dbInfo.name + '/'; self._dbInfo = dbInfo; var serializerPromise = new Promise(function(resolve/*, reject*/) { // We allow localForage to be declared as a module or as a // library available without AMD/require.js. if (moduleType === ModuleType.DEFINE) { _dereq_(['localforageSerializer'], resolve); } else if (moduleType === ModuleType.EXPORT) { // Making it browserify friendly resolve(_dereq_('./../utils/serializer')); } else { resolve(globalObject.localforageSerializer); } }); return serializerPromise.then(function(lib) { serializer = lib; return Promise.resolve(); }); } // Remove all keys from the datastore, effectively destroying all data in // the app's key/value store! function clear(callback) { var self = this; var promise = self.ready().then(function() { var keyPrefix = self._dbInfo.keyPrefix; for (var i = localStorage.length - 1; i >= 0; i--) { var key = localStorage.key(i); if (key.indexOf(keyPrefix) === 0) { localStorage.removeItem(key); } } }); executeCallback(promise, callback); return promise; } // Retrieve an item from the store. Unlike the original async_storage // library in Gaia, we don't modify return values at all. If a key's value // is `undefined`, we pass that value to the callback function. function getItem(key, callback) { var self = this; // Cast the key to a string, as that's all we can set as a key. if (typeof key !== 'string') { window.console.warn(key + ' used as a key, but it is not a string.'); key = String(key); } var promise = self.ready().then(function() { var dbInfo = self._dbInfo; var result = localStorage.getItem(dbInfo.keyPrefix + key); // If a result was found, parse it from the serialized // string into a JS object. If result isn't truthy, the key // is likely undefined and we'll pass it straight to the // callback. if (result) { result = serializer.deserialize(result); } return result; }); executeCallback(promise, callback); return promise; } // Iterate over all items in the store. function iterate(iterator, callback) { var self = this; var promise = self.ready().then(function() { var keyPrefix = self._dbInfo.keyPrefix; var keyPrefixLength = keyPrefix.length; var length = localStorage.length; // We use a dedicated iterator instead of the `i` variable below // so other keys we fetch in localStorage aren't counted in // the `iterationNumber` argument passed to the `iterate()` // callback. // // See: github.com/mozilla/localForage/pull/435#discussion_r38061530 var iterationNumber = 1; for (var i = 0; i < length; i++) { var key = localStorage.key(i); if (key.indexOf(keyPrefix) !== 0) { continue; } var value = localStorage.getItem(key); // If a result was found, parse it from the serialized // string into a JS object. If result isn't truthy, the // key is likely undefined and we'll pass it straight // to the iterator. if (value) { value = serializer.deserialize(value); } value = iterator(value, key.substring(keyPrefixLength), iterationNumber++); if (value !== void(0)) { return value; } } }); executeCallback(promise, callback); return promise; } // Same as localStorage's key() method, except takes a callback. function key(n, callback) { var self = this; var promise = self.ready().then(function() { var dbInfo = self._dbInfo; var result; try { result = localStorage.key(n); } catch (error) { result = null; } // Remove the prefix from the key, if a key is found. if (result) { result = result.substring(dbInfo.keyPrefix.length); } return result; }); executeCallback(promise, callback); return promise; } function keys(callback) { var self = this; var promise = self.ready().then(function() { var dbInfo = self._dbInfo; var length = localStorage.length; var keys = []; for (var i = 0; i < length; i++) { if (localStorage.key(i).indexOf(dbInfo.keyPrefix) === 0) { keys.push(localStorage.key(i).substring(dbInfo.keyPrefix.length)); } } return keys; }); executeCallback(promise, callback); return promise; } // Supply the number of keys in the datastore to the callback function. function length(callback) { var self = this; var promise = self.keys().then(function(keys) { return keys.length; }); executeCallback(promise, callback); return promise; } // Remove an item from the store, nice and simple. function removeItem(key, callback) { var self = this; // Cast the key to a string, as that's all we can set as a key. if (typeof key !== 'string') { window.console.warn(key + ' used as a key, but it is not a string.'); key = String(key); } var promise = self.ready().then(function() { var dbInfo = self._dbInfo; localStorage.removeItem(dbInfo.keyPrefix + key); }); executeCallback(promise, callback); return promise; } // Set a key's value and run an optional callback once the value is set. // Unlike Gaia's implementation, the callback function is passed the value, // in case you want to operate on that value only after you're sure it // saved, or something like that. function setItem(key, value, callback) { var self = this; // Cast the key to a string, as that's all we can set as a key. if (typeof key !== 'string') { window.console.warn(key + ' used as a key, but it is not a string.'); key = String(key); } var promise = self.ready().then(function() { // Convert undefined values to null. // https://github.com/mozilla/localForage/pull/42 if (value === undefined) { value = null; } // Save the original value to pass to the callback. var originalValue = value; return new Promise(function(resolve, reject) { serializer.serialize(value, function(value, error) { if (error) { reject(error); } else { try { var dbInfo = self._dbInfo; localStorage.setItem(dbInfo.keyPrefix + key, value); resolve(originalValue); } catch (e) { // localStorage capacity exceeded. // TODO: Make this a specific error/event. if (e.name === 'QuotaExceededError' || e.name === 'NS_ERROR_DOM_QUOTA_REACHED') { reject(e); } reject(e); } } }); }); }); executeCallback(promise, callback); return promise; } function executeCallback(promise, callback) { if (callback) { promise.then(function(result) { callback(null, result); }, function(error) { callback(error); }); } } var localStorageWrapper = { _driver: 'localStorageWrapper', _initStorage: _initStorage, // Default API, from Gaia/localStorage. iterate: iterate, getItem: getItem, setItem: setItem, removeItem: removeItem, clear: clear, length: length, key: key, keys: keys }; if (moduleType === ModuleType.EXPORT) { module.exports = localStorageWrapper; } else if (moduleType === ModuleType.DEFINE) { define('localStorageWrapper', function() { return localStorageWrapper; }); } else { this.localStorageWrapper = localStorageWrapper; } }).call(window); },{"./../utils/serializer":76,"promise":95}],74:[function(_dereq_,module,exports){ /* * Includes code from: * * base64-arraybuffer * https://github.com/niklasvh/base64-arraybuffer * * Copyright (c) 2012 Niklas von Hertzen * Licensed under the MIT license. */ (function() { 'use strict'; // Promises! var Promise = (typeof module !== 'undefined' && module.exports && typeof _dereq_ !== 'undefined') ? _dereq_('promise') : this.Promise; var globalObject = this; var serializer = null; var openDatabase = this.openDatabase; // If WebSQL methods aren't available, we can stop now. if (!openDatabase) { return; } var ModuleType = { DEFINE: 1, EXPORT: 2, WINDOW: 3 }; // Attaching to window (i.e. no module loader) is the assumed, // simple default. var moduleType = ModuleType.WINDOW; // Find out what kind of module setup we have; if none, we'll just attach // localForage to the main window. if (typeof module !== 'undefined' && module.exports && typeof _dereq_ !== 'undefined') { moduleType = ModuleType.EXPORT; } else if (typeof define === 'function' && define.amd) { moduleType = ModuleType.DEFINE; } // Open the WebSQL database (automatically creates one if one didn't // previously exist), using any options set in the config. function _initStorage(options) { var self = this; var dbInfo = { db: null }; if (options) { for (var i in options) { dbInfo[i] = typeof(options[i]) !== 'string' ? options[i].toString() : options[i]; } } var serializerPromise = new Promise(function(resolve/*, reject*/) { // We allow localForage to be declared as a module or as a // library available without AMD/require.js. if (moduleType === ModuleType.DEFINE) { _dereq_(['localforageSerializer'], resolve); } else if (moduleType === ModuleType.EXPORT) { // Making it browserify friendly resolve(_dereq_('./../utils/serializer')); } else { resolve(globalObject.localforageSerializer); } }); var dbInfoPromise = new Promise(function(resolve, reject) { // Open the database; the openDatabase API will automatically // create it for us if it doesn't exist. try { dbInfo.db = openDatabase(dbInfo.name, String(dbInfo.version), dbInfo.description, dbInfo.size); } catch (e) { return self.setDriver(self.LOCALSTORAGE).then(function() { return self._initStorage(options); }).then(resolve)['catch'](reject); } // Create our key/value table if it doesn't exist. dbInfo.db.transaction(function(t) { t.executeSql('CREATE TABLE IF NOT EXISTS ' + dbInfo.storeName + ' (id INTEGER PRIMARY KEY, key unique, value)', [], function() { self._dbInfo = dbInfo; resolve(); }, function(t, error) { reject(error); }); }); }); return serializerPromise.then(function(lib) { serializer = lib; return dbInfoPromise; }); } function getItem(key, callback) { var self = this; // Cast the key to a string, as that's all we can set as a key. if (typeof key !== 'string') { window.console.warn(key + ' used as a key, but it is not a string.'); key = String(key); } var promise = new Promise(function(resolve, reject) { self.ready().then(function() { var dbInfo = self._dbInfo; dbInfo.db.transaction(function(t) { t.executeSql('SELECT * FROM ' + dbInfo.storeName + ' WHERE key = ? LIMIT 1', [key], function(t, results) { var result = results.rows.length ? results.rows.item(0).value : null; // Check to see if this is serialized content we need to // unpack. if (result) { result = serializer.deserialize(result); } resolve(result); }, function(t, error) { reject(error); }); }); })['catch'](reject); }); executeCallback(promise, callback); return promise; } function iterate(iterator, callback) { var self = this; var promise = new Promise(function(resolve, reject) { self.ready().then(function() { var dbInfo = self._dbInfo; dbInfo.db.transaction(function(t) { t.executeSql('SELECT * FROM ' + dbInfo.storeName, [], function(t, results) { var rows = results.rows; var length = rows.length; for (var i = 0; i < length; i++) { var item = rows.item(i); var result = item.value; // Check to see if this is serialized content // we need to unpack. if (result) { result = serializer.deserialize(result); } result = iterator(result, item.key, i + 1); // void(0) prevents problems with redefinition // of `undefined`. if (result !== void(0)) { resolve(result); return; } } resolve(); }, function(t, error) { reject(error); }); }); })['catch'](reject); }); executeCallback(promise, callback); return promise; } function setItem(key, value, callback) { var self = this; // Cast the key to a string, as that's all we can set as a key. if (typeof key !== 'string') { window.console.warn(key + ' used as a key, but it is not a string.'); key = String(key); } var promise = new Promise(function(resolve, reject) { self.ready().then(function() { // The localStorage API doesn't return undefined values in an // "expected" way, so undefined is always cast to null in all // drivers. See: https://github.com/mozilla/localForage/pull/42 if (value === undefined) { value = null; } // Save the original value to pass to the callback. var originalValue = value; serializer.serialize(value, function(value, error) { if (error) { reject(error); } else { var dbInfo = self._dbInfo; dbInfo.db.transaction(function(t) { t.executeSql('INSERT OR REPLACE INTO ' + dbInfo.storeName + ' (key, value) VALUES (?, ?)', [key, value], function() { resolve(originalValue); }, function(t, error) { reject(error); }); }, function(sqlError) { // The transaction failed; check // to see if it's a quota error. if (sqlError.code === sqlError.QUOTA_ERR) { // We reject the callback outright for now, but // it's worth trying to re-run the transaction. // Even if the user accepts the prompt to use // more storage on Safari, this error will // be called. // // TODO: Try to re-run the transaction. reject(sqlError); } }); } }); })['catch'](reject); }); executeCallback(promise, callback); return promise; } function removeItem(key, callback) { var self = this; // Cast the key to a string, as that's all we can set as a key. if (typeof key !== 'string') { window.console.warn(key + ' used as a key, but it is not a string.'); key = String(key); } var promise = new Promise(function(resolve, reject) { self.ready().then(function() { var dbInfo = self._dbInfo; dbInfo.db.transaction(function(t) { t.executeSql('DELETE FROM ' + dbInfo.storeName + ' WHERE key = ?', [key], function() { resolve(); }, function(t, error) { reject(error); }); }); })['catch'](reject); }); executeCallback(promise, callback); return promise; } // Deletes every item in the table. // TODO: Find out if this resets the AUTO_INCREMENT number. function clear(callback) { var self = this; var promise = new Promise(function(resolve, reject) { self.ready().then(function() { var dbInfo = self._dbInfo; dbInfo.db.transaction(function(t) { t.executeSql('DELETE FROM ' + dbInfo.storeName, [], function() { resolve(); }, function(t, error) { reject(error); }); }); })['catch'](reject); }); executeCallback(promise, callback); return promise; } // Does a simple `COUNT(key)` to get the number of items stored in // localForage. function length(callback) { var self = this; var promise = new Promise(function(resolve, reject) { self.ready().then(function() { var dbInfo = self._dbInfo; dbInfo.db.transaction(function(t) { // Ahhh, SQL makes this one soooooo easy. t.executeSql('SELECT COUNT(key) as c FROM ' + dbInfo.storeName, [], function(t, results) { var result = results.rows.item(0).c; resolve(result); }, function(t, error) { reject(error); }); }); })['catch'](reject); }); executeCallback(promise, callback); return promise; } // Return the key located at key index X; essentially gets the key from a // `WHERE id = ?`. This is the most efficient way I can think to implement // this rarely-used (in my experience) part of the API, but it can seem // inconsistent, because we do `INSERT OR REPLACE INTO` on `setItem()`, so // the ID of each key will change every time it's updated. Perhaps a stored // procedure for the `setItem()` SQL would solve this problem? // TODO: Don't change ID on `setItem()`. function key(n, callback) { var self = this; var promise = new Promise(function(resolve, reject) { self.ready().then(function() { var dbInfo = self._dbInfo; dbInfo.db.transaction(function(t) { t.executeSql('SELECT key FROM ' + dbInfo.storeName + ' WHERE id = ? LIMIT 1', [n + 1], function(t, results) { var result = results.rows.length ? results.rows.item(0).key : null; resolve(result); }, function(t, error) { reject(error); }); }); })['catch'](reject); }); executeCallback(promise, callback); return promise; } function keys(callback) { var self = this; var promise = new Promise(function(resolve, reject) { self.ready().then(function() { var dbInfo = self._dbInfo; dbInfo.db.transaction(function(t) { t.executeSql('SELECT key FROM ' + dbInfo.storeName, [], function(t, results) { var keys = []; for (var i = 0; i < results.rows.length; i++) { keys.push(results.rows.item(i).key); } resolve(keys); }, function(t, error) { reject(error); }); }); })['catch'](reject); }); executeCallback(promise, callback); return promise; } function executeCallback(promise, callback) { if (callback) { promise.then(function(result) { callback(null, result); }, function(error) { callback(error); }); } } var webSQLStorage = { _driver: 'webSQLStorage', _initStorage: _initStorage, iterate: iterate, getItem: getItem, setItem: setItem, removeItem: removeItem, clear: clear, length: length, key: key, keys: keys }; if (moduleType === ModuleType.DEFINE) { define('webSQLStorage', function() { return webSQLStorage; }); } else if (moduleType === ModuleType.EXPORT) { module.exports = webSQLStorage; } else { this.webSQLStorage = webSQLStorage; } }).call(window); },{"./../utils/serializer":76,"promise":95}],75:[function(_dereq_,module,exports){ (function() { 'use strict'; // Promises! var Promise = (typeof module !== 'undefined' && module.exports && typeof _dereq_ !== 'undefined') ? _dereq_('promise') : this.Promise; // Custom drivers are stored here when `defineDriver()` is called. // They are shared across all instances of localForage. var CustomDrivers = {}; var DriverType = { INDEXEDDB: 'asyncStorage', LOCALSTORAGE: 'localStorageWrapper', WEBSQL: 'webSQLStorage' }; var DefaultDriverOrder = [ DriverType.INDEXEDDB, DriverType.WEBSQL, DriverType.LOCALSTORAGE ]; var LibraryMethods = [ 'clear', 'getItem', 'iterate', 'key', 'keys', 'length', 'removeItem', 'setItem' ]; var ModuleType = { DEFINE: 1, EXPORT: 2, WINDOW: 3 }; var DefaultConfig = { description: '', driver: DefaultDriverOrder.slice(), name: 'localforage', // Default DB size is _JUST UNDER_ 5MB, as it's the highest size // we can use without a prompt. size: 4980736, storeName: 'keyvaluepairs', version: 1.0 }; // Attaching to window (i.e. no module loader) is the assumed, // simple default. var moduleType = ModuleType.WINDOW; // Find out what kind of module setup we have; if none, we'll just attach // localForage to the main window. if (typeof module !== 'undefined' && module.exports && typeof _dereq_ !== 'undefined') { moduleType = ModuleType.EXPORT; } else if (typeof define === 'function' && define.amd) { moduleType = ModuleType.DEFINE; } // Check to see if IndexedDB is available and if it is the latest // implementation; it's our preferred backend library. We use "_spec_test" // as the name of the database because it's not the one we'll operate on, // but it's useful to make sure its using the right spec. // See: https://github.com/mozilla/localForage/issues/128 var driverSupport = (function(self) { // Initialize IndexedDB; fall back to vendor-prefixed versions // if needed. var indexedDB = indexedDB || self.indexedDB || self.webkitIndexedDB || self.mozIndexedDB || self.OIndexedDB || self.msIndexedDB; var result = {}; result[DriverType.WEBSQL] = !!self.openDatabase; result[DriverType.INDEXEDDB] = !!(function() { // We mimic PouchDB here; just UA test for Safari (which, as of // iOS 8/Yosemite, doesn't properly support IndexedDB). // IndexedDB support is broken and different from Blink's. // This is faster than the test case (and it's sync), so we just // do this. *SIGH* // http://bl.ocks.org/nolanlawson/raw/c83e9039edf2278047e9/ // // We test for openDatabase because IE Mobile identifies itself // as Safari. Oh the lulz... if (typeof self.openDatabase !== 'undefined' && self.navigator && self.navigator.userAgent && /Safari/.test(self.navigator.userAgent) && !/Chrome/.test(self.navigator.userAgent)) { return false; } try { return indexedDB && typeof indexedDB.open === 'function' && // Some Samsung/HTC Android 4.0-4.3 devices // have older IndexedDB specs; if this isn't available // their IndexedDB is too old for us to use. // (Replaces the onupgradeneeded test.) typeof self.IDBKeyRange !== 'undefined'; } catch (e) { return false; } })(); result[DriverType.LOCALSTORAGE] = !!(function() { try { return (self.localStorage && ('setItem' in self.localStorage) && (self.localStorage.setItem)); } catch (e) { return false; } })(); return result; })(this); var isArray = Array.isArray || function(arg) { return Object.prototype.toString.call(arg) === '[object Array]'; }; function callWhenReady(localForageInstance, libraryMethod) { localForageInstance[libraryMethod] = function() { var _args = arguments; return localForageInstance.ready().then(function() { return localForageInstance[libraryMethod].apply(localForageInstance, _args); }); }; } function extend() { for (var i = 1; i < arguments.length; i++) { var arg = arguments[i]; if (arg) { for (var key in arg) { if (arg.hasOwnProperty(key)) { if (isArray(arg[key])) { arguments[0][key] = arg[key].slice(); } else { arguments[0][key] = arg[key]; } } } } } return arguments[0]; } function isLibraryDriver(driverName) { for (var driver in DriverType) { if (DriverType.hasOwnProperty(driver) && DriverType[driver] === driverName) { return true; } } return false; } var globalObject = this; function LocalForage(options) { this._config = extend({}, DefaultConfig, options); this._driverSet = null; this._ready = false; this._dbInfo = null; // Add a stub for each driver API method that delays the call to the // corresponding driver method until localForage is ready. These stubs // will be replaced by the driver methods as soon as the driver is // loaded, so there is no performance impact. for (var i = 0; i < LibraryMethods.length; i++) { callWhenReady(this, LibraryMethods[i]); } this.setDriver(this._config.driver); } LocalForage.prototype.INDEXEDDB = DriverType.INDEXEDDB; LocalForage.prototype.LOCALSTORAGE = DriverType.LOCALSTORAGE; LocalForage.prototype.WEBSQL = DriverType.WEBSQL; // Set any config values for localForage; can be called anytime before // the first API call (e.g. `getItem`, `setItem`). // We loop through options so we don't overwrite existing config // values. LocalForage.prototype.config = function(options) { // If the options argument is an object, we use it to set values. // Otherwise, we return either a specified config value or all // config values. if (typeof(options) === 'object') { // If localforage is ready and fully initialized, we can't set // any new configuration values. Instead, we return an error. if (this._ready) { return new Error("Can't call config() after localforage " + 'has been used.'); } for (var i in options) { if (i === 'storeName') { options[i] = options[i].replace(/\W/g, '_'); } this._config[i] = options[i]; } // after all config options are set and // the driver option is used, try setting it if ('driver' in options && options.driver) { this.setDriver(this._config.driver); } return true; } else if (typeof(options) === 'string') { return this._config[options]; } else { return this._config; } }; // Used to define a custom driver, shared across all instances of // localForage. LocalForage.prototype.defineDriver = function(driverObject, callback, errorCallback) { var defineDriver = new Promise(function(resolve, reject) { try { var driverName = driverObject._driver; var complianceError = new Error( 'Custom driver not compliant; see ' + 'https://mozilla.github.io/localForage/#definedriver' ); var namingError = new Error( 'Custom driver name already in use: ' + driverObject._driver ); // A driver name should be defined and not overlap with the // library-defined, default drivers. if (!driverObject._driver) { reject(complianceError); return; } if (isLibraryDriver(driverObject._driver)) { reject(namingError); return; } var customDriverMethods = LibraryMethods.concat('_initStorage'); for (var i = 0; i < customDriverMethods.length; i++) { var customDriverMethod = customDriverMethods[i]; if (!customDriverMethod || !driverObject[customDriverMethod] || typeof driverObject[customDriverMethod] !== 'function') { reject(complianceError); return; } } var supportPromise = Promise.resolve(true); if ('_support' in driverObject) { if (driverObject._support && typeof driverObject._support === 'function') { supportPromise = driverObject._support(); } else { supportPromise = Promise.resolve(!!driverObject._support); } } supportPromise.then(function(supportResult) { driverSupport[driverName] = supportResult; CustomDrivers[driverName] = driverObject; resolve(); }, reject); } catch (e) { reject(e); } }); defineDriver.then(callback, errorCallback); return defineDriver; }; LocalForage.prototype.driver = function() { return this._driver || null; }; LocalForage.prototype.ready = function(callback) { var self = this; var ready = new Promise(function(resolve, reject) { self._driverSet.then(function() { if (self._ready === null) { self._ready = self._initStorage(self._config); } self._ready.then(resolve, reject); })['catch'](reject); }); ready.then(callback, callback); return ready; }; LocalForage.prototype.setDriver = function(drivers, callback, errorCallback) { var self = this; if (typeof drivers === 'string') { drivers = [drivers]; } this._driverSet = new Promise(function(resolve, reject) { var driverName = self._getFirstSupportedDriver(drivers); var error = new Error('No available storage method found.'); if (!driverName) { self._driverSet = Promise.reject(error); reject(error); return; } self._dbInfo = null; self._ready = null; if (isLibraryDriver(driverName)) { var driverPromise = new Promise(function(resolve/*, reject*/) { // We allow localForage to be declared as a module or as a // library available without AMD/require.js. if (moduleType === ModuleType.DEFINE) { _dereq_([driverName], resolve); } else if (moduleType === ModuleType.EXPORT) { // Making it browserify friendly switch (driverName) { case self.INDEXEDDB: resolve(_dereq_('./drivers/indexeddb')); break; case self.LOCALSTORAGE: resolve(_dereq_('./drivers/localstorage')); break; case self.WEBSQL: resolve(_dereq_('./drivers/websql')); break; } } else { resolve(globalObject[driverName]); } }); driverPromise.then(function(driver) { self._extend(driver); resolve(); }); } else if (CustomDrivers[driverName]) { self._extend(CustomDrivers[driverName]); resolve(); } else { self._driverSet = Promise.reject(error); reject(error); } }); function setDriverToConfig() { self._config.driver = self.driver(); } this._driverSet.then(setDriverToConfig, setDriverToConfig); this._driverSet.then(callback, errorCallback); return this._driverSet; }; LocalForage.prototype.supports = function(driverName) { return !!driverSupport[driverName]; }; LocalForage.prototype._extend = function(libraryMethodsAndProperties) { extend(this, libraryMethodsAndProperties); }; // Used to determine which driver we should use as the backend for this // instance of localForage. LocalForage.prototype._getFirstSupportedDriver = function(drivers) { if (drivers && isArray(drivers)) { for (var i = 0; i < drivers.length; i++) { var driver = drivers[i]; if (this.supports(driver)) { return driver; } } } return null; }; LocalForage.prototype.createInstance = function(options) { return new LocalForage(options); }; // The actual localForage object that we expose as a module or via a // global. It's extended by pulling in one of our other libraries. var localForage = new LocalForage(); // We allow localForage to be declared as a module or as a library // available without AMD/require.js. if (moduleType === ModuleType.DEFINE) { define('localforage', function() { return localForage; }); } else if (moduleType === ModuleType.EXPORT) { module.exports = localForage; } else { this.localforage = localForage; } }).call(window); },{"./drivers/indexeddb":72,"./drivers/localstorage":73,"./drivers/websql":74,"promise":95}],76:[function(_dereq_,module,exports){ (function() { 'use strict'; // Sadly, the best way to save binary data in WebSQL/localStorage is serializing // it to Base64, so this is how we store it to prevent very strange errors with less // verbose ways of binary <-> string data storage. var BASE_CHARS = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'; var BLOB_TYPE_PREFIX = '~~local_forage_type~'; var BLOB_TYPE_PREFIX_REGEX = /^~~local_forage_type~([^~]+)~/; var SERIALIZED_MARKER = '__lfsc__:'; var SERIALIZED_MARKER_LENGTH = SERIALIZED_MARKER.length; // OMG the serializations! var TYPE_ARRAYBUFFER = 'arbf'; var TYPE_BLOB = 'blob'; var TYPE_INT8ARRAY = 'si08'; var TYPE_UINT8ARRAY = 'ui08'; var TYPE_UINT8CLAMPEDARRAY = 'uic8'; var TYPE_INT16ARRAY = 'si16'; var TYPE_INT32ARRAY = 'si32'; var TYPE_UINT16ARRAY = 'ur16'; var TYPE_UINT32ARRAY = 'ui32'; var TYPE_FLOAT32ARRAY = 'fl32'; var TYPE_FLOAT64ARRAY = 'fl64'; var TYPE_SERIALIZED_MARKER_LENGTH = SERIALIZED_MARKER_LENGTH + TYPE_ARRAYBUFFER.length; // Get out of our habit of using `window` inline, at least. var globalObject = this; // Abstracts constructing a Blob object, so it also works in older // browsers that don't support the native Blob constructor. (i.e. // old QtWebKit versions, at least). function _createBlob(parts, properties) { parts = parts || []; properties = properties || {}; try { return new Blob(parts, properties); } catch (err) { if (err.name !== 'TypeError') { throw err; } var BlobBuilder = globalObject.BlobBuilder || globalObject.MSBlobBuilder || globalObject.MozBlobBuilder || globalObject.WebKitBlobBuilder; var builder = new BlobBuilder(); for (var i = 0; i < parts.length; i += 1) { builder.append(parts[i]); } return builder.getBlob(properties.type); } } // Serialize a value, afterwards executing a callback (which usually // instructs the `setItem()` callback/promise to be executed). This is how // we store binary data with localStorage. function serialize(value, callback) { var valueString = ''; if (value) { valueString = value.toString(); } // Cannot use `value instanceof ArrayBuffer` or such here, as these // checks fail when running the tests using casper.js... // // TODO: See why those tests fail and use a better solution. if (value && (value.toString() === '[object ArrayBuffer]' || value.buffer && value.buffer.toString() === '[object ArrayBuffer]')) { // Convert binary arrays to a string and prefix the string with // a special marker. var buffer; var marker = SERIALIZED_MARKER; if (value instanceof ArrayBuffer) { buffer = value; marker += TYPE_ARRAYBUFFER; } else { buffer = value.buffer; if (valueString === '[object Int8Array]') { marker += TYPE_INT8ARRAY; } else if (valueString === '[object Uint8Array]') { marker += TYPE_UINT8ARRAY; } else if (valueString === '[object Uint8ClampedArray]') { marker += TYPE_UINT8CLAMPEDARRAY; } else if (valueString === '[object Int16Array]') { marker += TYPE_INT16ARRAY; } else if (valueString === '[object Uint16Array]') { marker += TYPE_UINT16ARRAY; } else if (valueString === '[object Int32Array]') { marker += TYPE_INT32ARRAY; } else if (valueString === '[object Uint32Array]') { marker += TYPE_UINT32ARRAY; } else if (valueString === '[object Float32Array]') { marker += TYPE_FLOAT32ARRAY; } else if (valueString === '[object Float64Array]') { marker += TYPE_FLOAT64ARRAY; } else { callback(new Error('Failed to get type for BinaryArray')); } } callback(marker + bufferToString(buffer)); } else if (valueString === '[object Blob]') { // Conver the blob to a binaryArray and then to a string. var fileReader = new FileReader(); fileReader.onload = function() { // Backwards-compatible prefix for the blob type. var str = BLOB_TYPE_PREFIX + value.type + '~' + bufferToString(this.result); callback(SERIALIZED_MARKER + TYPE_BLOB + str); }; fileReader.readAsArrayBuffer(value); } else { try { callback(JSON.stringify(value)); } catch (e) { console.error("Couldn't convert value into a JSON string: ", value); callback(null, e); } } } // Deserialize data we've inserted into a value column/field. We place // special markers into our strings to mark them as encoded; this isn't // as nice as a meta field, but it's the only sane thing we can do whilst // keeping localStorage support intact. // // Oftentimes this will just deserialize JSON content, but if we have a // special marker (SERIALIZED_MARKER, defined above), we will extract // some kind of arraybuffer/binary data/typed array out of the string. function deserialize(value) { // If we haven't marked this string as being specially serialized (i.e. // something other than serialized JSON), we can just return it and be // done with it. if (value.substring(0, SERIALIZED_MARKER_LENGTH) !== SERIALIZED_MARKER) { return JSON.parse(value); } // The following code deals with deserializing some kind of Blob or // TypedArray. First we separate out the type of data we're dealing // with from the data itself. var serializedString = value.substring(TYPE_SERIALIZED_MARKER_LENGTH); var type = value.substring(SERIALIZED_MARKER_LENGTH, TYPE_SERIALIZED_MARKER_LENGTH); var blobType; // Backwards-compatible blob type serialization strategy. // DBs created with older versions of localForage will simply not have the blob type. if (type === TYPE_BLOB && BLOB_TYPE_PREFIX_REGEX.test(serializedString)) { var matcher = serializedString.match(BLOB_TYPE_PREFIX_REGEX); blobType = matcher[1]; serializedString = serializedString.substring(matcher[0].length); } var buffer = stringToBuffer(serializedString); // Return the right type based on the code/type set during // serialization. switch (type) { case TYPE_ARRAYBUFFER: return buffer; case TYPE_BLOB: return _createBlob([buffer], {type: blobType}); case TYPE_INT8ARRAY: return new Int8Array(buffer); case TYPE_UINT8ARRAY: return new Uint8Array(buffer); case TYPE_UINT8CLAMPEDARRAY: return new Uint8ClampedArray(buffer); case TYPE_INT16ARRAY: return new Int16Array(buffer); case TYPE_UINT16ARRAY: return new Uint16Array(buffer); case TYPE_INT32ARRAY: return new Int32Array(buffer); case TYPE_UINT32ARRAY: return new Uint32Array(buffer); case TYPE_FLOAT32ARRAY: return new Float32Array(buffer); case TYPE_FLOAT64ARRAY: return new Float64Array(buffer); default: throw new Error('Unkown type: ' + type); } } function stringToBuffer(serializedString) { // Fill the string into a ArrayBuffer. var bufferLength = serializedString.length * 0.75; var len = serializedString.length; var i; var p = 0; var encoded1, encoded2, encoded3, encoded4; if (serializedString[serializedString.length - 1] === '=') { bufferLength--; if (serializedString[serializedString.length - 2] === '=') { bufferLength--; } } var buffer = new ArrayBuffer(bufferLength); var bytes = new Uint8Array(buffer); for (i = 0; i < len; i+=4) { encoded1 = BASE_CHARS.indexOf(serializedString[i]); encoded2 = BASE_CHARS.indexOf(serializedString[i+1]); encoded3 = BASE_CHARS.indexOf(serializedString[i+2]); encoded4 = BASE_CHARS.indexOf(serializedString[i+3]); /*jslint bitwise: true */ bytes[p++] = (encoded1 << 2) | (encoded2 >> 4); bytes[p++] = ((encoded2 & 15) << 4) | (encoded3 >> 2); bytes[p++] = ((encoded3 & 3) << 6) | (encoded4 & 63); } return buffer; } // Converts a buffer to a string to store, serialized, in the backend // storage library. function bufferToString(buffer) { // base64-arraybuffer var bytes = new Uint8Array(buffer); var base64String = ''; var i; for (i = 0; i < bytes.length; i += 3) { /*jslint bitwise: true */ base64String += BASE_CHARS[bytes[i] >> 2]; base64String += BASE_CHARS[((bytes[i] & 3) << 4) | (bytes[i + 1] >> 4)]; base64String += BASE_CHARS[((bytes[i + 1] & 15) << 2) | (bytes[i + 2] >> 6)]; base64String += BASE_CHARS[bytes[i + 2] & 63]; } if ((bytes.length % 3) === 2) { base64String = base64String.substring(0, base64String.length - 1) + '='; } else if (bytes.length % 3 === 1) { base64String = base64String.substring(0, base64String.length - 2) + '=='; } return base64String; } var localforageSerializer = { serialize: serialize, deserialize: deserialize, stringToBuffer: stringToBuffer, bufferToString: bufferToString }; if (typeof module !== 'undefined' && module.exports && typeof _dereq_ !== 'undefined') { module.exports = localforageSerializer; } else if (typeof define === 'function' && define.amd) { define('localforageSerializer', function() { return localforageSerializer; }); } else { this.localforageSerializer = localforageSerializer; } }).call(window); },{}],77:[function(_dereq_,module,exports){ // Top level file is just a mixin of submodules & constants 'use strict'; var assign = _dereq_('./lib/utils/common').assign; var deflate = _dereq_('./lib/deflate'); var inflate = _dereq_('./lib/inflate'); var constants = _dereq_('./lib/zlib/constants'); var pako = {}; assign(pako, deflate, inflate, constants); module.exports = pako; },{"./lib/deflate":78,"./lib/inflate":79,"./lib/utils/common":80,"./lib/zlib/constants":83}],78:[function(_dereq_,module,exports){ 'use strict'; var zlib_deflate = _dereq_('./zlib/deflate'); var utils = _dereq_('./utils/common'); var strings = _dereq_('./utils/strings'); var msg = _dereq_('./zlib/messages'); var ZStream = _dereq_('./zlib/zstream'); var toString = Object.prototype.toString; /* Public constants ==========================================================*/ /* ===========================================================================*/ var Z_NO_FLUSH = 0; var Z_FINISH = 4; var Z_OK = 0; var Z_STREAM_END = 1; var Z_SYNC_FLUSH = 2; var Z_DEFAULT_COMPRESSION = -1; var Z_DEFAULT_STRATEGY = 0; var Z_DEFLATED = 8; /* ===========================================================================*/ /** * class Deflate * * Generic JS-style wrapper for zlib calls. If you don't need * streaming behaviour - use more simple functions: [[deflate]], * [[deflateRaw]] and [[gzip]]. **/ /* internal * Deflate.chunks -> Array * * Chunks of output data, if [[Deflate#onData]] not overriden. **/ /** * Deflate.result -> Uint8Array|Array * * Compressed result, generated by default [[Deflate#onData]] * and [[Deflate#onEnd]] handlers. Filled after you push last chunk * (call [[Deflate#push]] with `Z_FINISH` / `true` param) or if you * push a chunk with explicit flush (call [[Deflate#push]] with * `Z_SYNC_FLUSH` param). **/ /** * Deflate.err -> Number * * Error code after deflate finished. 0 (Z_OK) on success. * You will not need it in real life, because deflate errors * are possible only on wrong options or bad `onData` / `onEnd` * custom handlers. **/ /** * Deflate.msg -> String * * Error message, if [[Deflate.err]] != 0 **/ /** * new Deflate(options) * - options (Object): zlib deflate options. * * Creates new deflator instance with specified params. Throws exception * on bad params. Supported options: * * - `level` * - `windowBits` * - `memLevel` * - `strategy` * * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced) * for more information on these. * * Additional options, for internal needs: * * - `chunkSize` - size of generated data chunks (16K by default) * - `raw` (Boolean) - do raw deflate * - `gzip` (Boolean) - create gzip wrapper * - `to` (String) - if equal to 'string', then result will be "binary string" * (each char code [0..255]) * - `header` (Object) - custom header for gzip * - `text` (Boolean) - true if compressed data believed to be text * - `time` (Number) - modification time, unix timestamp * - `os` (Number) - operation system code * - `extra` (Array) - array of bytes with extra data (max 65536) * - `name` (String) - file name (binary string) * - `comment` (String) - comment (binary string) * - `hcrc` (Boolean) - true if header crc should be added * * ##### Example: * * ```javascript * var pako = require('pako') * , chunk1 = Uint8Array([1,2,3,4,5,6,7,8,9]) * , chunk2 = Uint8Array([10,11,12,13,14,15,16,17,18,19]); * * var deflate = new pako.Deflate({ level: 3}); * * deflate.push(chunk1, false); * deflate.push(chunk2, true); // true -> last chunk * * if (deflate.err) { throw new Error(deflate.err); } * * console.log(deflate.result); * ``` **/ function Deflate(options) { if (!(this instanceof Deflate)) return new Deflate(options); this.options = utils.assign({ level: Z_DEFAULT_COMPRESSION, method: Z_DEFLATED, chunkSize: 16384, windowBits: 15, memLevel: 8, strategy: Z_DEFAULT_STRATEGY, to: '' }, options || {}); var opt = this.options; if (opt.raw && (opt.windowBits > 0)) { opt.windowBits = -opt.windowBits; } else if (opt.gzip && (opt.windowBits > 0) && (opt.windowBits < 16)) { opt.windowBits += 16; } this.err = 0; // error code, if happens (0 = Z_OK) this.msg = ''; // error message this.ended = false; // used to avoid multiple onEnd() calls this.chunks = []; // chunks of compressed data this.strm = new ZStream(); this.strm.avail_out = 0; var status = zlib_deflate.deflateInit2( this.strm, opt.level, opt.method, opt.windowBits, opt.memLevel, opt.strategy ); if (status !== Z_OK) { throw new Error(msg[status]); } if (opt.header) { zlib_deflate.deflateSetHeader(this.strm, opt.header); } } /** * Deflate#push(data[, mode]) -> Boolean * - data (Uint8Array|Array|ArrayBuffer|String): input data. Strings will be * converted to utf8 byte sequence. * - mode (Number|Boolean): 0..6 for corresponding Z_NO_FLUSH..Z_TREE modes. * See constants. Skipped or `false` means Z_NO_FLUSH, `true` meansh Z_FINISH. * * Sends input data to deflate pipe, generating [[Deflate#onData]] calls with * new compressed chunks. Returns `true` on success. The last data block must have * mode Z_FINISH (or `true`). That will flush internal pending buffers and call * [[Deflate#onEnd]]. For interim explicit flushes (without ending the stream) you * can use mode Z_SYNC_FLUSH, keeping the compression context. * * On fail call [[Deflate#onEnd]] with error code and return false. * * We strongly recommend to use `Uint8Array` on input for best speed (output * array format is detected automatically). Also, don't skip last param and always * use the same type in your code (boolean or number). That will improve JS speed. * * For regular `Array`-s make sure all elements are [0..255]. * * ##### Example * * ```javascript * push(chunk, false); // push one of data chunks * ... * push(chunk, true); // push last chunk * ``` **/ Deflate.prototype.push = function (data, mode) { var strm = this.strm; var chunkSize = this.options.chunkSize; var status, _mode; if (this.ended) { return false; } _mode = (mode === ~~mode) ? mode : ((mode === true) ? Z_FINISH : Z_NO_FLUSH); // Convert data if needed if (typeof data === 'string') { // If we need to compress text, change encoding to utf8. strm.input = strings.string2buf(data); } else if (toString.call(data) === '[object ArrayBuffer]') { strm.input = new Uint8Array(data); } else { strm.input = data; } strm.next_in = 0; strm.avail_in = strm.input.length; do { if (strm.avail_out === 0) { strm.output = new utils.Buf8(chunkSize); strm.next_out = 0; strm.avail_out = chunkSize; } status = zlib_deflate.deflate(strm, _mode); /* no bad return value */ if (status !== Z_STREAM_END && status !== Z_OK) { this.onEnd(status); this.ended = true; return false; } if (strm.avail_out === 0 || (strm.avail_in === 0 && (_mode === Z_FINISH || _mode === Z_SYNC_FLUSH))) { if (this.options.to === 'string') { this.onData(strings.buf2binstring(utils.shrinkBuf(strm.output, strm.next_out))); } else { this.onData(utils.shrinkBuf(strm.output, strm.next_out)); } } } while ((strm.avail_in > 0 || strm.avail_out === 0) && status !== Z_STREAM_END); // Finalize on the last chunk. if (_mode === Z_FINISH) { status = zlib_deflate.deflateEnd(this.strm); this.onEnd(status); this.ended = true; return status === Z_OK; } // callback interim results if Z_SYNC_FLUSH. if (_mode === Z_SYNC_FLUSH) { this.onEnd(Z_OK); strm.avail_out = 0; return true; } return true; }; /** * Deflate#onData(chunk) -> Void * - chunk (Uint8Array|Array|String): ouput data. Type of array depends * on js engine support. When string output requested, each chunk * will be string. * * By default, stores data blocks in `chunks[]` property and glue * those in `onEnd`. Override this handler, if you need another behaviour. **/ Deflate.prototype.onData = function (chunk) { this.chunks.push(chunk); }; /** * Deflate#onEnd(status) -> Void * - status (Number): deflate status. 0 (Z_OK) on success, * other if not. * * Called once after you tell deflate that the input stream is * complete (Z_FINISH) or should be flushed (Z_SYNC_FLUSH) * or if an error happened. By default - join collected chunks, * free memory and fill `results` / `err` properties. **/ Deflate.prototype.onEnd = function (status) { // On success - join if (status === Z_OK) { if (this.options.to === 'string') { this.result = this.chunks.join(''); } else { this.result = utils.flattenChunks(this.chunks); } } this.chunks = []; this.err = status; this.msg = this.strm.msg; }; /** * deflate(data[, options]) -> Uint8Array|Array|String * - data (Uint8Array|Array|String): input data to compress. * - options (Object): zlib deflate options. * * Compress `data` with deflate algorithm and `options`. * * Supported options are: * * - level * - windowBits * - memLevel * - strategy * * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced) * for more information on these. * * Sugar (options): * * - `raw` (Boolean) - say that we work with raw stream, if you don't wish to specify * negative windowBits implicitly. * - `to` (String) - if equal to 'string', then result will be "binary string" * (each char code [0..255]) * * ##### Example: * * ```javascript * var pako = require('pako') * , data = Uint8Array([1,2,3,4,5,6,7,8,9]); * * console.log(pako.deflate(data)); * ``` **/ function deflate(input, options) { var deflator = new Deflate(options); deflator.push(input, true); // That will never happens, if you don't cheat with options :) if (deflator.err) { throw deflator.msg; } return deflator.result; } /** * deflateRaw(data[, options]) -> Uint8Array|Array|String * - data (Uint8Array|Array|String): input data to compress. * - options (Object): zlib deflate options. * * The same as [[deflate]], but creates raw data, without wrapper * (header and adler32 crc). **/ function deflateRaw(input, options) { options = options || {}; options.raw = true; return deflate(input, options); } /** * gzip(data[, options]) -> Uint8Array|Array|String * - data (Uint8Array|Array|String): input data to compress. * - options (Object): zlib deflate options. * * The same as [[deflate]], but create gzip wrapper instead of * deflate one. **/ function gzip(input, options) { options = options || {}; options.gzip = true; return deflate(input, options); } exports.Deflate = Deflate; exports.deflate = deflate; exports.deflateRaw = deflateRaw; exports.gzip = gzip; },{"./utils/common":80,"./utils/strings":81,"./zlib/deflate":85,"./zlib/messages":90,"./zlib/zstream":92}],79:[function(_dereq_,module,exports){ 'use strict'; var zlib_inflate = _dereq_('./zlib/inflate'); var utils = _dereq_('./utils/common'); var strings = _dereq_('./utils/strings'); var c = _dereq_('./zlib/constants'); var msg = _dereq_('./zlib/messages'); var ZStream = _dereq_('./zlib/zstream'); var GZheader = _dereq_('./zlib/gzheader'); var toString = Object.prototype.toString; /** * class Inflate * * Generic JS-style wrapper for zlib calls. If you don't need * streaming behaviour - use more simple functions: [[inflate]] * and [[inflateRaw]]. **/ /* internal * inflate.chunks -> Array * * Chunks of output data, if [[Inflate#onData]] not overriden. **/ /** * Inflate.result -> Uint8Array|Array|String * * Uncompressed result, generated by default [[Inflate#onData]] * and [[Inflate#onEnd]] handlers. Filled after you push last chunk * (call [[Inflate#push]] with `Z_FINISH` / `true` param) or if you * push a chunk with explicit flush (call [[Inflate#push]] with * `Z_SYNC_FLUSH` param). **/ /** * Inflate.err -> Number * * Error code after inflate finished. 0 (Z_OK) on success. * Should be checked if broken data possible. **/ /** * Inflate.msg -> String * * Error message, if [[Inflate.err]] != 0 **/ /** * new Inflate(options) * - options (Object): zlib inflate options. * * Creates new inflator instance with specified params. Throws exception * on bad params. Supported options: * * - `windowBits` * * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced) * for more information on these. * * Additional options, for internal needs: * * - `chunkSize` - size of generated data chunks (16K by default) * - `raw` (Boolean) - do raw inflate * - `to` (String) - if equal to 'string', then result will be converted * from utf8 to utf16 (javascript) string. When string output requested, * chunk length can differ from `chunkSize`, depending on content. * * By default, when no options set, autodetect deflate/gzip data format via * wrapper header. * * ##### Example: * * ```javascript * var pako = require('pako') * , chunk1 = Uint8Array([1,2,3,4,5,6,7,8,9]) * , chunk2 = Uint8Array([10,11,12,13,14,15,16,17,18,19]); * * var inflate = new pako.Inflate({ level: 3}); * * inflate.push(chunk1, false); * inflate.push(chunk2, true); // true -> last chunk * * if (inflate.err) { throw new Error(inflate.err); } * * console.log(inflate.result); * ``` **/ function Inflate(options) { if (!(this instanceof Inflate)) return new Inflate(options); this.options = utils.assign({ chunkSize: 16384, windowBits: 0, to: '' }, options || {}); var opt = this.options; // Force window size for `raw` data, if not set directly, // because we have no header for autodetect. if (opt.raw && (opt.windowBits >= 0) && (opt.windowBits < 16)) { opt.windowBits = -opt.windowBits; if (opt.windowBits === 0) { opt.windowBits = -15; } } // If `windowBits` not defined (and mode not raw) - set autodetect flag for gzip/deflate if ((opt.windowBits >= 0) && (opt.windowBits < 16) && !(options && options.windowBits)) { opt.windowBits += 32; } // Gzip header has no info about windows size, we can do autodetect only // for deflate. So, if window size not set, force it to max when gzip possible if ((opt.windowBits > 15) && (opt.windowBits < 48)) { // bit 3 (16) -> gzipped data // bit 4 (32) -> autodetect gzip/deflate if ((opt.windowBits & 15) === 0) { opt.windowBits |= 15; } } this.err = 0; // error code, if happens (0 = Z_OK) this.msg = ''; // error message this.ended = false; // used to avoid multiple onEnd() calls this.chunks = []; // chunks of compressed data this.strm = new ZStream(); this.strm.avail_out = 0; var status = zlib_inflate.inflateInit2( this.strm, opt.windowBits ); if (status !== c.Z_OK) { throw new Error(msg[status]); } this.header = new GZheader(); zlib_inflate.inflateGetHeader(this.strm, this.header); } /** * Inflate#push(data[, mode]) -> Boolean * - data (Uint8Array|Array|ArrayBuffer|String): input data * - mode (Number|Boolean): 0..6 for corresponding Z_NO_FLUSH..Z_TREE modes. * See constants. Skipped or `false` means Z_NO_FLUSH, `true` meansh Z_FINISH. * * Sends input data to inflate pipe, generating [[Inflate#onData]] calls with * new output chunks. Returns `true` on success. The last data block must have * mode Z_FINISH (or `true`). That will flush internal pending buffers and call * [[Inflate#onEnd]]. For interim explicit flushes (without ending the stream) you * can use mode Z_SYNC_FLUSH, keeping the decompression context. * * On fail call [[Inflate#onEnd]] with error code and return false. * * We strongly recommend to use `Uint8Array` on input for best speed (output * format is detected automatically). Also, don't skip last param and always * use the same type in your code (boolean or number). That will improve JS speed. * * For regular `Array`-s make sure all elements are [0..255]. * * ##### Example * * ```javascript * push(chunk, false); // push one of data chunks * ... * push(chunk, true); // push last chunk * ``` **/ Inflate.prototype.push = function (data, mode) { var strm = this.strm; var chunkSize = this.options.chunkSize; var status, _mode; var next_out_utf8, tail, utf8str; // Flag to properly process Z_BUF_ERROR on testing inflate call // when we check that all output data was flushed. var allowBufError = false; if (this.ended) { return false; } _mode = (mode === ~~mode) ? mode : ((mode === true) ? c.Z_FINISH : c.Z_NO_FLUSH); // Convert data if needed if (typeof data === 'string') { // Only binary strings can be decompressed on practice strm.input = strings.binstring2buf(data); } else if (toString.call(data) === '[object ArrayBuffer]') { strm.input = new Uint8Array(data); } else { strm.input = data; } strm.next_in = 0; strm.avail_in = strm.input.length; do { if (strm.avail_out === 0) { strm.output = new utils.Buf8(chunkSize); strm.next_out = 0; strm.avail_out = chunkSize; } status = zlib_inflate.inflate(strm, c.Z_NO_FLUSH); /* no bad return value */ if (status === c.Z_BUF_ERROR && allowBufError === true) { status = c.Z_OK; allowBufError = false; } if (status !== c.Z_STREAM_END && status !== c.Z_OK) { this.onEnd(status); this.ended = true; return false; } if (strm.next_out) { if (strm.avail_out === 0 || status === c.Z_STREAM_END || (strm.avail_in === 0 && (_mode === c.Z_FINISH || _mode === c.Z_SYNC_FLUSH))) { if (this.options.to === 'string') { next_out_utf8 = strings.utf8border(strm.output, strm.next_out); tail = strm.next_out - next_out_utf8; utf8str = strings.buf2string(strm.output, next_out_utf8); // move tail strm.next_out = tail; strm.avail_out = chunkSize - tail; if (tail) { utils.arraySet(strm.output, strm.output, next_out_utf8, tail, 0); } this.onData(utf8str); } else { this.onData(utils.shrinkBuf(strm.output, strm.next_out)); } } } // When no more input data, we should check that internal inflate buffers // are flushed. The only way to do it when avail_out = 0 - run one more // inflate pass. But if output data not exists, inflate return Z_BUF_ERROR. // Here we set flag to process this error properly. // // NOTE. Deflate does not return error in this case and does not needs such // logic. if (strm.avail_in === 0 && strm.avail_out === 0) { allowBufError = true; } } while ((strm.avail_in > 0 || strm.avail_out === 0) && status !== c.Z_STREAM_END); if (status === c.Z_STREAM_END) { _mode = c.Z_FINISH; } // Finalize on the last chunk. if (_mode === c.Z_FINISH) { status = zlib_inflate.inflateEnd(this.strm); this.onEnd(status); this.ended = true; return status === c.Z_OK; } // callback interim results if Z_SYNC_FLUSH. if (_mode === c.Z_SYNC_FLUSH) { this.onEnd(c.Z_OK); strm.avail_out = 0; return true; } return true; }; /** * Inflate#onData(chunk) -> Void * - chunk (Uint8Array|Array|String): ouput data. Type of array depends * on js engine support. When string output requested, each chunk * will be string. * * By default, stores data blocks in `chunks[]` property and glue * those in `onEnd`. Override this handler, if you need another behaviour. **/ Inflate.prototype.onData = function (chunk) { this.chunks.push(chunk); }; /** * Inflate#onEnd(status) -> Void * - status (Number): inflate status. 0 (Z_OK) on success, * other if not. * * Called either after you tell inflate that the input stream is * complete (Z_FINISH) or should be flushed (Z_SYNC_FLUSH) * or if an error happened. By default - join collected chunks, * free memory and fill `results` / `err` properties. **/ Inflate.prototype.onEnd = function (status) { // On success - join if (status === c.Z_OK) { if (this.options.to === 'string') { // Glue & convert here, until we teach pako to send // utf8 alligned strings to onData this.result = this.chunks.join(''); } else { this.result = utils.flattenChunks(this.chunks); } } this.chunks = []; this.err = status; this.msg = this.strm.msg; }; /** * inflate(data[, options]) -> Uint8Array|Array|String * - data (Uint8Array|Array|String): input data to decompress. * - options (Object): zlib inflate options. * * Decompress `data` with inflate/ungzip and `options`. Autodetect * format via wrapper header by default. That's why we don't provide * separate `ungzip` method. * * Supported options are: * * - windowBits * * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced) * for more information. * * Sugar (options): * * - `raw` (Boolean) - say that we work with raw stream, if you don't wish to specify * negative windowBits implicitly. * - `to` (String) - if equal to 'string', then result will be converted * from utf8 to utf16 (javascript) string. When string output requested, * chunk length can differ from `chunkSize`, depending on content. * * * ##### Example: * * ```javascript * var pako = require('pako') * , input = pako.deflate([1,2,3,4,5,6,7,8,9]) * , output; * * try { * output = pako.inflate(input); * } catch (err) * console.log(err); * } * ``` **/ function inflate(input, options) { var inflator = new Inflate(options); inflator.push(input, true); // That will never happens, if you don't cheat with options :) if (inflator.err) { throw inflator.msg; } return inflator.result; } /** * inflateRaw(data[, options]) -> Uint8Array|Array|String * - data (Uint8Array|Array|String): input data to decompress. * - options (Object): zlib inflate options. * * The same as [[inflate]], but creates raw data, without wrapper * (header and adler32 crc). **/ function inflateRaw(input, options) { options = options || {}; options.raw = true; return inflate(input, options); } /** * ungzip(data[, options]) -> Uint8Array|Array|String * - data (Uint8Array|Array|String): input data to decompress. * - options (Object): zlib inflate options. * * Just shortcut to [[inflate]], because it autodetects format * by header.content. Done for convenience. **/ exports.Inflate = Inflate; exports.inflate = inflate; exports.inflateRaw = inflateRaw; exports.ungzip = inflate; },{"./utils/common":80,"./utils/strings":81,"./zlib/constants":83,"./zlib/gzheader":86,"./zlib/inflate":88,"./zlib/messages":90,"./zlib/zstream":92}],80:[function(_dereq_,module,exports){ 'use strict'; var TYPED_OK = (typeof Uint8Array !== 'undefined') && (typeof Uint16Array !== 'undefined') && (typeof Int32Array !== 'undefined'); exports.assign = function (obj /*from1, from2, from3, ...*/) { var sources = Array.prototype.slice.call(arguments, 1); while (sources.length) { var source = sources.shift(); if (!source) { continue; } if (typeof source !== 'object') { throw new TypeError(source + 'must be non-object'); } for (var p in source) { if (source.hasOwnProperty(p)) { obj[p] = source[p]; } } } return obj; }; // reduce buffer size, avoiding mem copy exports.shrinkBuf = function (buf, size) { if (buf.length === size) { return buf; } if (buf.subarray) { return buf.subarray(0, size); } buf.length = size; return buf; }; var fnTyped = { arraySet: function (dest, src, src_offs, len, dest_offs) { if (src.subarray && dest.subarray) { dest.set(src.subarray(src_offs, src_offs + len), dest_offs); return; } // Fallback to ordinary array for (var i = 0; i < len; i++) { dest[dest_offs + i] = src[src_offs + i]; } }, // Join array of chunks to single array. flattenChunks: function (chunks) { var i, l, len, pos, chunk, result; // calculate data length len = 0; for (i = 0, l = chunks.length; i < l; i++) { len += chunks[i].length; } // join chunks result = new Uint8Array(len); pos = 0; for (i = 0, l = chunks.length; i < l; i++) { chunk = chunks[i]; result.set(chunk, pos); pos += chunk.length; } return result; } }; var fnUntyped = { arraySet: function (dest, src, src_offs, len, dest_offs) { for (var i = 0; i < len; i++) { dest[dest_offs + i] = src[src_offs + i]; } }, // Join array of chunks to single array. flattenChunks: function (chunks) { return [].concat.apply([], chunks); } }; // Enable/Disable typed arrays use, for testing // exports.setTyped = function (on) { if (on) { exports.Buf8 = Uint8Array; exports.Buf16 = Uint16Array; exports.Buf32 = Int32Array; exports.assign(exports, fnTyped); } else { exports.Buf8 = Array; exports.Buf16 = Array; exports.Buf32 = Array; exports.assign(exports, fnUntyped); } }; exports.setTyped(TYPED_OK); },{}],81:[function(_dereq_,module,exports){ // String encode/decode helpers 'use strict'; var utils = _dereq_('./common'); // Quick check if we can use fast array to bin string conversion // // - apply(Array) can fail on Android 2.2 // - apply(Uint8Array) can fail on iOS 5.1 Safary // var STR_APPLY_OK = true; var STR_APPLY_UIA_OK = true; try { String.fromCharCode.apply(null, [ 0 ]); } catch (__) { STR_APPLY_OK = false; } try { String.fromCharCode.apply(null, new Uint8Array(1)); } catch (__) { STR_APPLY_UIA_OK = false; } // Table with utf8 lengths (calculated by first byte of sequence) // Note, that 5 & 6-byte values and some 4-byte values can not be represented in JS, // because max possible codepoint is 0x10ffff var _utf8len = new utils.Buf8(256); for (var q = 0; q < 256; q++) { _utf8len[q] = (q >= 252 ? 6 : q >= 248 ? 5 : q >= 240 ? 4 : q >= 224 ? 3 : q >= 192 ? 2 : 1); } _utf8len[254] = _utf8len[254] = 1; // Invalid sequence start // convert string to array (typed, when possible) exports.string2buf = function (str) { var buf, c, c2, m_pos, i, str_len = str.length, buf_len = 0; // count binary size for (m_pos = 0; m_pos < str_len; m_pos++) { c = str.charCodeAt(m_pos); if ((c & 0xfc00) === 0xd800 && (m_pos + 1 < str_len)) { c2 = str.charCodeAt(m_pos + 1); if ((c2 & 0xfc00) === 0xdc00) { c = 0x10000 + ((c - 0xd800) << 10) + (c2 - 0xdc00); m_pos++; } } buf_len += c < 0x80 ? 1 : c < 0x800 ? 2 : c < 0x10000 ? 3 : 4; } // allocate buffer buf = new utils.Buf8(buf_len); // convert for (i = 0, m_pos = 0; i < buf_len; m_pos++) { c = str.charCodeAt(m_pos); if ((c & 0xfc00) === 0xd800 && (m_pos + 1 < str_len)) { c2 = str.charCodeAt(m_pos + 1); if ((c2 & 0xfc00) === 0xdc00) { c = 0x10000 + ((c - 0xd800) << 10) + (c2 - 0xdc00); m_pos++; } } if (c < 0x80) { /* one byte */ buf[i++] = c; } else if (c < 0x800) { /* two bytes */ buf[i++] = 0xC0 | (c >>> 6); buf[i++] = 0x80 | (c & 0x3f); } else if (c < 0x10000) { /* three bytes */ buf[i++] = 0xE0 | (c >>> 12); buf[i++] = 0x80 | (c >>> 6 & 0x3f); buf[i++] = 0x80 | (c & 0x3f); } else { /* four bytes */ buf[i++] = 0xf0 | (c >>> 18); buf[i++] = 0x80 | (c >>> 12 & 0x3f); buf[i++] = 0x80 | (c >>> 6 & 0x3f); buf[i++] = 0x80 | (c & 0x3f); } } return buf; }; // Helper (used in 2 places) function buf2binstring(buf, len) { // use fallback for big arrays to avoid stack overflow if (len < 65537) { if ((buf.subarray && STR_APPLY_UIA_OK) || (!buf.subarray && STR_APPLY_OK)) { return String.fromCharCode.apply(null, utils.shrinkBuf(buf, len)); } } var result = ''; for (var i = 0; i < len; i++) { result += String.fromCharCode(buf[i]); } return result; } // Convert byte array to binary string exports.buf2binstring = function (buf) { return buf2binstring(buf, buf.length); }; // Convert binary string (typed, when possible) exports.binstring2buf = function (str) { var buf = new utils.Buf8(str.length); for (var i = 0, len = buf.length; i < len; i++) { buf[i] = str.charCodeAt(i); } return buf; }; // convert array to string exports.buf2string = function (buf, max) { var i, out, c, c_len; var len = max || buf.length; // Reserve max possible length (2 words per char) // NB: by unknown reasons, Array is significantly faster for // String.fromCharCode.apply than Uint16Array. var utf16buf = new Array(len * 2); for (out = 0, i = 0; i < len;) { c = buf[i++]; // quick process ascii if (c < 0x80) { utf16buf[out++] = c; continue; } c_len = _utf8len[c]; // skip 5 & 6 byte codes if (c_len > 4) { utf16buf[out++] = 0xfffd; i += c_len - 1; continue; } // apply mask on first byte c &= c_len === 2 ? 0x1f : c_len === 3 ? 0x0f : 0x07; // join the rest while (c_len > 1 && i < len) { c = (c << 6) | (buf[i++] & 0x3f); c_len--; } // terminated by end of string? if (c_len > 1) { utf16buf[out++] = 0xfffd; continue; } if (c < 0x10000) { utf16buf[out++] = c; } else { c -= 0x10000; utf16buf[out++] = 0xd800 | ((c >> 10) & 0x3ff); utf16buf[out++] = 0xdc00 | (c & 0x3ff); } } return buf2binstring(utf16buf, out); }; // Calculate max possible position in utf8 buffer, // that will not break sequence. If that's not possible // - (very small limits) return max size as is. // // buf[] - utf8 bytes array // max - length limit (mandatory); exports.utf8border = function (buf, max) { var pos; max = max || buf.length; if (max > buf.length) { max = buf.length; } // go back from last position, until start of sequence found pos = max - 1; while (pos >= 0 && (buf[pos] & 0xC0) === 0x80) { pos--; } // Fuckup - very small and broken sequence, // return max, because we should return something anyway. if (pos < 0) { return max; } // If we came to start of buffer - that means vuffer is too small, // return max too. if (pos === 0) { return max; } return (pos + _utf8len[buf[pos]] > max) ? pos : max; }; },{"./common":80}],82:[function(_dereq_,module,exports){ 'use strict'; // Note: adler32 takes 12% for level 0 and 2% for level 6. // It doesn't worth to make additional optimizationa as in original. // Small size is preferable. function adler32(adler, buf, len, pos) { var s1 = (adler & 0xffff) |0, s2 = ((adler >>> 16) & 0xffff) |0, n = 0; while (len !== 0) { // Set limit ~ twice less than 5552, to keep // s2 in 31-bits, because we force signed ints. // in other case %= will fail. n = len > 2000 ? 2000 : len; len -= n; do { s1 = (s1 + buf[pos++]) |0; s2 = (s2 + s1) |0; } while (--n); s1 %= 65521; s2 %= 65521; } return (s1 | (s2 << 16)) |0; } module.exports = adler32; },{}],83:[function(_dereq_,module,exports){ 'use strict'; module.exports = { /* Allowed flush values; see deflate() and inflate() below for details */ 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, /* Return codes for the compression/decompression functions. Negative values * are errors, positive values are used for special but normal events. */ Z_OK: 0, Z_STREAM_END: 1, Z_NEED_DICT: 2, Z_ERRNO: -1, Z_STREAM_ERROR: -2, Z_DATA_ERROR: -3, //Z_MEM_ERROR: -4, Z_BUF_ERROR: -5, //Z_VERSION_ERROR: -6, /* compression levels */ 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, /* Possible values of the data_type field (though see inflate()) */ Z_BINARY: 0, Z_TEXT: 1, //Z_ASCII: 1, // = Z_TEXT (deprecated) Z_UNKNOWN: 2, /* The deflate compression method */ Z_DEFLATED: 8 //Z_NULL: null // Use -1 or null inline, depending on var type }; },{}],84:[function(_dereq_,module,exports){ 'use strict'; // Note: we can't get significant speed boost here. // So write code to minimize size - no pregenerated tables // and array tools dependencies. // Use ordinary array, since untyped makes no boost here function makeTable() { var c, table = []; for (var n = 0; n < 256; n++) { c = n; for (var k = 0; k < 8; k++) { c = ((c & 1) ? (0xEDB88320 ^ (c >>> 1)) : (c >>> 1)); } table[n] = c; } return table; } // Create table on load. Just 255 signed longs. Not a problem. var crcTable = makeTable(); function crc32(crc, buf, len, pos) { var t = crcTable, end = pos + len; crc ^= -1; for (var i = pos; i < end; i++) { crc = (crc >>> 8) ^ t[(crc ^ buf[i]) & 0xFF]; } return (crc ^ (-1)); // >>> 0; } module.exports = crc32; },{}],85:[function(_dereq_,module,exports){ 'use strict'; var utils = _dereq_('../utils/common'); var trees = _dereq_('./trees'); var adler32 = _dereq_('./adler32'); var crc32 = _dereq_('./crc32'); var msg = _dereq_('./messages'); /* Public constants ==========================================================*/ /* ===========================================================================*/ /* Allowed flush values; see deflate() and inflate() below for details */ var Z_NO_FLUSH = 0; var Z_PARTIAL_FLUSH = 1; //var Z_SYNC_FLUSH = 2; var Z_FULL_FLUSH = 3; var Z_FINISH = 4; var Z_BLOCK = 5; //var Z_TREES = 6; /* Return codes for the compression/decompression functions. Negative values * are errors, positive values are used for special but normal events. */ var Z_OK = 0; var Z_STREAM_END = 1; //var Z_NEED_DICT = 2; //var Z_ERRNO = -1; var Z_STREAM_ERROR = -2; var Z_DATA_ERROR = -3; //var Z_MEM_ERROR = -4; var Z_BUF_ERROR = -5; //var Z_VERSION_ERROR = -6; /* compression levels */ //var Z_NO_COMPRESSION = 0; //var Z_BEST_SPEED = 1; //var Z_BEST_COMPRESSION = 9; var Z_DEFAULT_COMPRESSION = -1; var Z_FILTERED = 1; var Z_HUFFMAN_ONLY = 2; var Z_RLE = 3; var Z_FIXED = 4; var Z_DEFAULT_STRATEGY = 0; /* Possible values of the data_type field (though see inflate()) */ //var Z_BINARY = 0; //var Z_TEXT = 1; //var Z_ASCII = 1; // = Z_TEXT var Z_UNKNOWN = 2; /* The deflate compression method */ var Z_DEFLATED = 8; /*============================================================================*/ var MAX_MEM_LEVEL = 9; /* Maximum value for memLevel in deflateInit2 */ var MAX_WBITS = 15; /* 32K LZ77 window */ var DEF_MEM_LEVEL = 8; var LENGTH_CODES = 29; /* number of length codes, not counting the special END_BLOCK code */ var LITERALS = 256; /* number of literal bytes 0..255 */ var L_CODES = LITERALS + 1 + LENGTH_CODES; /* number of Literal or Length codes, including the END_BLOCK code */ var D_CODES = 30; /* number of distance codes */ var BL_CODES = 19; /* number of codes used to transfer the bit lengths */ var HEAP_SIZE = 2 * L_CODES + 1; /* maximum heap size */ var MAX_BITS = 15; /* All codes must not exceed MAX_BITS bits */ var MIN_MATCH = 3; var MAX_MATCH = 258; var MIN_LOOKAHEAD = (MAX_MATCH + MIN_MATCH + 1); var PRESET_DICT = 0x20; var INIT_STATE = 42; var EXTRA_STATE = 69; var NAME_STATE = 73; var COMMENT_STATE = 91; var HCRC_STATE = 103; var BUSY_STATE = 113; var FINISH_STATE = 666; var BS_NEED_MORE = 1; /* block not completed, need more input or more output */ var BS_BLOCK_DONE = 2; /* block flush performed */ var BS_FINISH_STARTED = 3; /* finish started, need only more output at next deflate */ var BS_FINISH_DONE = 4; /* finish done, accept no more input or output */ var OS_CODE = 0x03; // Unix :) . Don't detect, use this default. function err(strm, errorCode) { strm.msg = msg[errorCode]; return errorCode; } function rank(f) { return ((f) << 1) - ((f) > 4 ? 9 : 0); } function zero(buf) { var len = buf.length; while (--len >= 0) { buf[len] = 0; } } /* ========================================================================= * Flush as much pending output as possible. All deflate() output goes * through this function so some applications may wish to modify it * to avoid allocating a large strm->output buffer and copying into it. * (See also read_buf()). */ function flush_pending(strm) { var s = strm.state; //_tr_flush_bits(s); var len = s.pending; if (len > strm.avail_out) { len = strm.avail_out; } if (len === 0) { return; } utils.arraySet(strm.output, s.pending_buf, s.pending_out, len, strm.next_out); strm.next_out += len; s.pending_out += len; strm.total_out += len; strm.avail_out -= len; s.pending -= len; if (s.pending === 0) { s.pending_out = 0; } } function flush_block_only(s, last) { trees._tr_flush_block(s, (s.block_start >= 0 ? s.block_start : -1), s.strstart - s.block_start, last); s.block_start = s.strstart; flush_pending(s.strm); } function put_byte(s, b) { s.pending_buf[s.pending++] = b; } /* ========================================================================= * Put a short in the pending buffer. The 16-bit value is put in MSB order. * IN assertion: the stream state is correct and there is enough room in * pending_buf. */ function putShortMSB(s, b) { // put_byte(s, (Byte)(b >> 8)); // put_byte(s, (Byte)(b & 0xff)); s.pending_buf[s.pending++] = (b >>> 8) & 0xff; s.pending_buf[s.pending++] = b & 0xff; } /* =========================================================================== * Read a new buffer from the current input stream, update the adler32 * and total number of bytes read. All deflate() input goes through * this function so some applications may wish to modify it to avoid * allocating a large strm->input buffer and copying from it. * (See also flush_pending()). */ function read_buf(strm, buf, start, size) { var len = strm.avail_in; if (len > size) { len = size; } if (len === 0) { return 0; } strm.avail_in -= len; utils.arraySet(buf, strm.input, strm.next_in, len, start); if (strm.state.wrap === 1) { strm.adler = adler32(strm.adler, buf, len, start); } else if (strm.state.wrap === 2) { strm.adler = crc32(strm.adler, buf, len, start); } strm.next_in += len; strm.total_in += len; return len; } /* =========================================================================== * Set match_start to the longest match starting at the given string and * return its length. Matches shorter or equal to prev_length are discarded, * in which case the result is equal to prev_length and match_start is * garbage. * IN assertions: cur_match is the head of the hash chain for the current * string (strstart) and its distance is <= MAX_DIST, and prev_length >= 1 * OUT assertion: the match length is not greater than s->lookahead. */ function longest_match(s, cur_match) { var chain_length = s.max_chain_length; /* max hash chain length */ var scan = s.strstart; /* current string */ var match; /* matched string */ var len; /* length of current match */ var best_len = s.prev_length; /* best match length so far */ var nice_match = s.nice_match; /* stop if match long enough */ var limit = (s.strstart > (s.w_size - MIN_LOOKAHEAD)) ? s.strstart - (s.w_size - MIN_LOOKAHEAD) : 0/*NIL*/; var _win = s.window; // shortcut var wmask = s.w_mask; var prev = s.prev; /* Stop when cur_match becomes <= limit. To simplify the code, * we prevent matches with the string of window index 0. */ var strend = s.strstart + MAX_MATCH; var scan_end1 = _win[scan + best_len - 1]; var scan_end = _win[scan + best_len]; /* The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16. * It is easy to get rid of this optimization if necessary. */ // Assert(s->hash_bits >= 8 && MAX_MATCH == 258, "Code too clever"); /* Do not waste too much time if we already have a good match: */ if (s.prev_length >= s.good_match) { chain_length >>= 2; } /* Do not look for matches beyond the end of the input. This is necessary * to make deflate deterministic. */ if (nice_match > s.lookahead) { nice_match = s.lookahead; } // Assert((ulg)s->strstart <= s->window_size-MIN_LOOKAHEAD, "need lookahead"); do { // Assert(cur_match < s->strstart, "no future"); match = cur_match; /* Skip to next match if the match length cannot increase * or if the match length is less than 2. Note that the checks below * for insufficient lookahead only occur occasionally for performance * reasons. Therefore uninitialized memory will be accessed, and * conditional jumps will be made that depend on those values. * However the length of the match is limited to the lookahead, so * the output of deflate is not affected by the uninitialized values. */ if (_win[match + best_len] !== scan_end || _win[match + best_len - 1] !== scan_end1 || _win[match] !== _win[scan] || _win[++match] !== _win[scan + 1]) { continue; } /* The check at best_len-1 can be removed because it will be made * again later. (This heuristic is not always a win.) * It is not necessary to compare scan[2] and match[2] since they * are always equal when the other bytes match, given that * the hash keys are equal and that HASH_BITS >= 8. */ scan += 2; match++; // Assert(*scan == *match, "match[2]?"); /* We check for insufficient lookahead only every 8th comparison; * the 256th check will be made at strstart+258. */ do { /*jshint noempty:false*/ } while (_win[++scan] === _win[++match] && _win[++scan] === _win[++match] && _win[++scan] === _win[++match] && _win[++scan] === _win[++match] && _win[++scan] === _win[++match] && _win[++scan] === _win[++match] && _win[++scan] === _win[++match] && _win[++scan] === _win[++match] && scan < strend); // Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan"); len = MAX_MATCH - (strend - scan); scan = strend - MAX_MATCH; if (len > best_len) { s.match_start = cur_match; best_len = len; if (len >= nice_match) { break; } scan_end1 = _win[scan + best_len - 1]; scan_end = _win[scan + best_len]; } } while ((cur_match = prev[cur_match & wmask]) > limit && --chain_length !== 0); if (best_len <= s.lookahead) { return best_len; } return s.lookahead; } /* =========================================================================== * Fill the window when the lookahead becomes insufficient. * Updates strstart and lookahead. * * IN assertion: lookahead < MIN_LOOKAHEAD * OUT assertions: strstart <= window_size-MIN_LOOKAHEAD * At least one byte has been read, or avail_in == 0; reads are * performed for at least two bytes (required for the zip translate_eol * option -- not supported here). */ function fill_window(s) { var _w_size = s.w_size; var p, n, m, more, str; //Assert(s->lookahead < MIN_LOOKAHEAD, "already enough lookahead"); do { more = s.window_size - s.lookahead - s.strstart; // JS ints have 32 bit, block below not needed /* Deal with !@#$% 64K limit: */ //if (sizeof(int) <= 2) { // if (more == 0 && s->strstart == 0 && s->lookahead == 0) { // more = wsize; // // } else if (more == (unsigned)(-1)) { // /* Very unlikely, but possible on 16 bit machine if // * strstart == 0 && lookahead == 1 (input done a byte at time) // */ // more--; // } //} /* If the window is almost full and there is insufficient lookahead, * move the upper half to the lower one to make room in the upper half. */ if (s.strstart >= _w_size + (_w_size - MIN_LOOKAHEAD)) { utils.arraySet(s.window, s.window, _w_size, _w_size, 0); s.match_start -= _w_size; s.strstart -= _w_size; /* we now have strstart >= MAX_DIST */ s.block_start -= _w_size; /* Slide the hash table (could be avoided with 32 bit values at the expense of memory usage). We slide even when level == 0 to keep the hash table consistent if we switch back to level > 0 later. (Using level 0 permanently is not an optimal usage of zlib, so we don't care about this pathological case.) */ n = s.hash_size; p = n; do { m = s.head[--p]; s.head[p] = (m >= _w_size ? m - _w_size : 0); } while (--n); n = _w_size; p = n; do { m = s.prev[--p]; s.prev[p] = (m >= _w_size ? m - _w_size : 0); /* If n is not on any hash chain, prev[n] is garbage but * its value will never be used. */ } while (--n); more += _w_size; } if (s.strm.avail_in === 0) { break; } /* If there was no sliding: * strstart <= WSIZE+MAX_DIST-1 && lookahead <= MIN_LOOKAHEAD - 1 && * more == window_size - lookahead - strstart * => more >= window_size - (MIN_LOOKAHEAD-1 + WSIZE + MAX_DIST-1) * => more >= window_size - 2*WSIZE + 2 * In the BIG_MEM or MMAP case (not yet supported), * window_size == input_size + MIN_LOOKAHEAD && * strstart + s->lookahead <= input_size => more >= MIN_LOOKAHEAD. * Otherwise, window_size == 2*WSIZE so more >= 2. * If there was sliding, more >= WSIZE. So in all cases, more >= 2. */ //Assert(more >= 2, "more < 2"); n = read_buf(s.strm, s.window, s.strstart + s.lookahead, more); s.lookahead += n; /* Initialize the hash value now that we have some input: */ if (s.lookahead + s.insert >= MIN_MATCH) { str = s.strstart - s.insert; s.ins_h = s.window[str]; /* UPDATE_HASH(s, s->ins_h, s->window[str + 1]); */ s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[str + 1]) & s.hash_mask; //#if MIN_MATCH != 3 // Call update_hash() MIN_MATCH-3 more times //#endif while (s.insert) { /* UPDATE_HASH(s, s->ins_h, s->window[str + MIN_MATCH-1]); */ s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[str + MIN_MATCH - 1]) & s.hash_mask; s.prev[str & s.w_mask] = s.head[s.ins_h]; s.head[s.ins_h] = str; str++; s.insert--; if (s.lookahead + s.insert < MIN_MATCH) { break; } } } /* If the whole input has less than MIN_MATCH bytes, ins_h is garbage, * but this is not important since only literal bytes will be emitted. */ } while (s.lookahead < MIN_LOOKAHEAD && s.strm.avail_in !== 0); /* If the WIN_INIT bytes after the end of the current data have never been * written, then zero those bytes in order to avoid memory check reports of * the use of uninitialized (or uninitialised as Julian writes) bytes by * the longest match routines. Update the high water mark for the next * time through here. WIN_INIT is set to MAX_MATCH since the longest match * routines allow scanning to strstart + MAX_MATCH, ignoring lookahead. */ // if (s.high_water < s.window_size) { // var curr = s.strstart + s.lookahead; // var init = 0; // // if (s.high_water < curr) { // /* Previous high water mark below current data -- zero WIN_INIT // * bytes or up to end of window, whichever is less. // */ // init = s.window_size - curr; // if (init > WIN_INIT) // init = WIN_INIT; // zmemzero(s->window + curr, (unsigned)init); // s->high_water = curr + init; // } // else if (s->high_water < (ulg)curr + WIN_INIT) { // /* High water mark at or above current data, but below current data // * plus WIN_INIT -- zero out to current data plus WIN_INIT, or up // * to end of window, whichever is less. // */ // init = (ulg)curr + WIN_INIT - s->high_water; // if (init > s->window_size - s->high_water) // init = s->window_size - s->high_water; // zmemzero(s->window + s->high_water, (unsigned)init); // s->high_water += init; // } // } // // Assert((ulg)s->strstart <= s->window_size - MIN_LOOKAHEAD, // "not enough room for search"); } /* =========================================================================== * Copy without compression as much as possible from the input stream, return * the current block state. * This function does not insert new strings in the dictionary since * uncompressible data is probably not useful. This function is used * only for the level=0 compression option. * NOTE: this function should be optimized to avoid extra copying from * window to pending_buf. */ function deflate_stored(s, flush) { /* Stored blocks are limited to 0xffff bytes, pending_buf is limited * to pending_buf_size, and each stored block has a 5 byte header: */ var max_block_size = 0xffff; if (max_block_size > s.pending_buf_size - 5) { max_block_size = s.pending_buf_size - 5; } /* Copy as much as possible from input to output: */ for (;;) { /* Fill the window as much as possible: */ if (s.lookahead <= 1) { //Assert(s->strstart < s->w_size+MAX_DIST(s) || // s->block_start >= (long)s->w_size, "slide too late"); // if (!(s.strstart < s.w_size + (s.w_size - MIN_LOOKAHEAD) || // s.block_start >= s.w_size)) { // throw new Error("slide too late"); // } fill_window(s); if (s.lookahead === 0 && flush === Z_NO_FLUSH) { return BS_NEED_MORE; } if (s.lookahead === 0) { break; } /* flush the current block */ } //Assert(s->block_start >= 0L, "block gone"); // if (s.block_start < 0) throw new Error("block gone"); s.strstart += s.lookahead; s.lookahead = 0; /* Emit a stored block if pending_buf will be full: */ var max_start = s.block_start + max_block_size; if (s.strstart === 0 || s.strstart >= max_start) { /* strstart == 0 is possible when wraparound on 16-bit machine */ s.lookahead = s.strstart - max_start; s.strstart = max_start; /*** FLUSH_BLOCK(s, 0); ***/ flush_block_only(s, false); if (s.strm.avail_out === 0) { return BS_NEED_MORE; } /***/ } /* Flush if we may have to slide, otherwise block_start may become * negative and the data will be gone: */ if (s.strstart - s.block_start >= (s.w_size - MIN_LOOKAHEAD)) { /*** FLUSH_BLOCK(s, 0); ***/ flush_block_only(s, false); if (s.strm.avail_out === 0) { return BS_NEED_MORE; } /***/ } } s.insert = 0; if (flush === Z_FINISH) { /*** FLUSH_BLOCK(s, 1); ***/ flush_block_only(s, true); if (s.strm.avail_out === 0) { return BS_FINISH_STARTED; } /***/ return BS_FINISH_DONE; } if (s.strstart > s.block_start) { /*** FLUSH_BLOCK(s, 0); ***/ flush_block_only(s, false); if (s.strm.avail_out === 0) { return BS_NEED_MORE; } /***/ } return BS_NEED_MORE; } /* =========================================================================== * Compress as much as possible from the input stream, return the current * block state. * This function does not perform lazy evaluation of matches and inserts * new strings in the dictionary only for unmatched strings or for short * matches. It is used only for the fast compression options. */ function deflate_fast(s, flush) { var hash_head; /* head of the hash chain */ var bflush; /* set if current block must be flushed */ for (;;) { /* Make sure that we always have enough lookahead, except * at the end of the input file. We need MAX_MATCH bytes * for the next match, plus MIN_MATCH bytes to insert the * string following the next match. */ if (s.lookahead < MIN_LOOKAHEAD) { fill_window(s); if (s.lookahead < MIN_LOOKAHEAD && flush === Z_NO_FLUSH) { return BS_NEED_MORE; } if (s.lookahead === 0) { break; /* flush the current block */ } } /* Insert the string window[strstart .. strstart+2] in the * dictionary, and set hash_head to the head of the hash chain: */ hash_head = 0/*NIL*/; if (s.lookahead >= MIN_MATCH) { /*** INSERT_STRING(s, s.strstart, hash_head); ***/ s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask; hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h]; s.head[s.ins_h] = s.strstart; /***/ } /* Find the longest match, discarding those <= prev_length. * At this point we have always match_length < MIN_MATCH */ if (hash_head !== 0/*NIL*/ && ((s.strstart - hash_head) <= (s.w_size - MIN_LOOKAHEAD))) { /* To simplify the code, we prevent matches with the string * of window index 0 (in particular we have to avoid a match * of the string with itself at the start of the input file). */ s.match_length = longest_match(s, hash_head); /* longest_match() sets match_start */ } if (s.match_length >= MIN_MATCH) { // check_match(s, s.strstart, s.match_start, s.match_length); // for debug only /*** _tr_tally_dist(s, s.strstart - s.match_start, s.match_length - MIN_MATCH, bflush); ***/ bflush = trees._tr_tally(s, s.strstart - s.match_start, s.match_length - MIN_MATCH); s.lookahead -= s.match_length; /* Insert new strings in the hash table only if the match length * is not too large. This saves time but degrades compression. */ if (s.match_length <= s.max_lazy_match/*max_insert_length*/ && s.lookahead >= MIN_MATCH) { s.match_length--; /* string at strstart already in table */ do { s.strstart++; /*** INSERT_STRING(s, s.strstart, hash_head); ***/ s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask; hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h]; s.head[s.ins_h] = s.strstart; /***/ /* strstart never exceeds WSIZE-MAX_MATCH, so there are * always MIN_MATCH bytes ahead. */ } while (--s.match_length !== 0); s.strstart++; } else { s.strstart += s.match_length; s.match_length = 0; s.ins_h = s.window[s.strstart]; /* UPDATE_HASH(s, s.ins_h, s.window[s.strstart+1]); */ s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + 1]) & s.hash_mask; //#if MIN_MATCH != 3 // Call UPDATE_HASH() MIN_MATCH-3 more times //#endif /* If lookahead < MIN_MATCH, ins_h is garbage, but it does not * matter since it will be recomputed at next deflate call. */ } } else { /* No match, output a literal byte */ //Tracevv((stderr,"%c", s.window[s.strstart])); /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/ bflush = trees._tr_tally(s, 0, s.window[s.strstart]); s.lookahead--; s.strstart++; } if (bflush) { /*** FLUSH_BLOCK(s, 0); ***/ flush_block_only(s, false); if (s.strm.avail_out === 0) { return BS_NEED_MORE; } /***/ } } s.insert = ((s.strstart < (MIN_MATCH - 1)) ? s.strstart : MIN_MATCH - 1); if (flush === Z_FINISH) { /*** FLUSH_BLOCK(s, 1); ***/ flush_block_only(s, true); if (s.strm.avail_out === 0) { return BS_FINISH_STARTED; } /***/ return BS_FINISH_DONE; } if (s.last_lit) { /*** FLUSH_BLOCK(s, 0); ***/ flush_block_only(s, false); if (s.strm.avail_out === 0) { return BS_NEED_MORE; } /***/ } return BS_BLOCK_DONE; } /* =========================================================================== * Same as above, but achieves better compression. We use a lazy * evaluation for matches: a match is finally adopted only if there is * no better match at the next window position. */ function deflate_slow(s, flush) { var hash_head; /* head of hash chain */ var bflush; /* set if current block must be flushed */ var max_insert; /* Process the input block. */ for (;;) { /* Make sure that we always have enough lookahead, except * at the end of the input file. We need MAX_MATCH bytes * for the next match, plus MIN_MATCH bytes to insert the * string following the next match. */ if (s.lookahead < MIN_LOOKAHEAD) { fill_window(s); if (s.lookahead < MIN_LOOKAHEAD && flush === Z_NO_FLUSH) { return BS_NEED_MORE; } if (s.lookahead === 0) { break; } /* flush the current block */ } /* Insert the string window[strstart .. strstart+2] in the * dictionary, and set hash_head to the head of the hash chain: */ hash_head = 0/*NIL*/; if (s.lookahead >= MIN_MATCH) { /*** INSERT_STRING(s, s.strstart, hash_head); ***/ s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask; hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h]; s.head[s.ins_h] = s.strstart; /***/ } /* Find the longest match, discarding those <= prev_length. */ s.prev_length = s.match_length; s.prev_match = s.match_start; s.match_length = MIN_MATCH - 1; if (hash_head !== 0/*NIL*/ && s.prev_length < s.max_lazy_match && s.strstart - hash_head <= (s.w_size - MIN_LOOKAHEAD)/*MAX_DIST(s)*/) { /* To simplify the code, we prevent matches with the string * of window index 0 (in particular we have to avoid a match * of the string with itself at the start of the input file). */ s.match_length = longest_match(s, hash_head); /* longest_match() sets match_start */ if (s.match_length <= 5 && (s.strategy === Z_FILTERED || (s.match_length === MIN_MATCH && s.strstart - s.match_start > 4096/*TOO_FAR*/))) { /* If prev_match is also MIN_MATCH, match_start is garbage * but we will ignore the current match anyway. */ s.match_length = MIN_MATCH - 1; } } /* If there was a match at the previous step and the current * match is not better, output the previous match: */ if (s.prev_length >= MIN_MATCH && s.match_length <= s.prev_length) { max_insert = s.strstart + s.lookahead - MIN_MATCH; /* Do not insert strings in hash table beyond this. */ //check_match(s, s.strstart-1, s.prev_match, s.prev_length); /***_tr_tally_dist(s, s.strstart - 1 - s.prev_match, s.prev_length - MIN_MATCH, bflush);***/ bflush = trees._tr_tally(s, s.strstart - 1 - s.prev_match, s.prev_length - MIN_MATCH); /* Insert in hash table all strings up to the end of the match. * strstart-1 and strstart are already inserted. If there is not * enough lookahead, the last two strings are not inserted in * the hash table. */ s.lookahead -= s.prev_length - 1; s.prev_length -= 2; do { if (++s.strstart <= max_insert) { /*** INSERT_STRING(s, s.strstart, hash_head); ***/ s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask; hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h]; s.head[s.ins_h] = s.strstart; /***/ } } while (--s.prev_length !== 0); s.match_available = 0; s.match_length = MIN_MATCH - 1; s.strstart++; if (bflush) { /*** FLUSH_BLOCK(s, 0); ***/ flush_block_only(s, false); if (s.strm.avail_out === 0) { return BS_NEED_MORE; } /***/ } } else if (s.match_available) { /* If there was no match at the previous position, output a * single literal. If there was a match but the current match * is longer, truncate the previous match to a single literal. */ //Tracevv((stderr,"%c", s->window[s->strstart-1])); /*** _tr_tally_lit(s, s.window[s.strstart-1], bflush); ***/ bflush = trees._tr_tally(s, 0, s.window[s.strstart - 1]); if (bflush) { /*** FLUSH_BLOCK_ONLY(s, 0) ***/ flush_block_only(s, false); /***/ } s.strstart++; s.lookahead--; if (s.strm.avail_out === 0) { return BS_NEED_MORE; } } else { /* There is no previous match to compare with, wait for * the next step to decide. */ s.match_available = 1; s.strstart++; s.lookahead--; } } //Assert (flush != Z_NO_FLUSH, "no flush?"); if (s.match_available) { //Tracevv((stderr,"%c", s->window[s->strstart-1])); /*** _tr_tally_lit(s, s.window[s.strstart-1], bflush); ***/ bflush = trees._tr_tally(s, 0, s.window[s.strstart - 1]); s.match_available = 0; } s.insert = s.strstart < MIN_MATCH - 1 ? s.strstart : MIN_MATCH - 1; if (flush === Z_FINISH) { /*** FLUSH_BLOCK(s, 1); ***/ flush_block_only(s, true); if (s.strm.avail_out === 0) { return BS_FINISH_STARTED; } /***/ return BS_FINISH_DONE; } if (s.last_lit) { /*** FLUSH_BLOCK(s, 0); ***/ flush_block_only(s, false); if (s.strm.avail_out === 0) { return BS_NEED_MORE; } /***/ } return BS_BLOCK_DONE; } /* =========================================================================== * For Z_RLE, simply look for runs of bytes, generate matches only of distance * one. Do not maintain a hash table. (It will be regenerated if this run of * deflate switches away from Z_RLE.) */ function deflate_rle(s, flush) { var bflush; /* set if current block must be flushed */ var prev; /* byte at distance one to match */ var scan, strend; /* scan goes up to strend for length of run */ var _win = s.window; for (;;) { /* Make sure that we always have enough lookahead, except * at the end of the input file. We need MAX_MATCH bytes * for the longest run, plus one for the unrolled loop. */ if (s.lookahead <= MAX_MATCH) { fill_window(s); if (s.lookahead <= MAX_MATCH && flush === Z_NO_FLUSH) { return BS_NEED_MORE; } if (s.lookahead === 0) { break; } /* flush the current block */ } /* See how many times the previous byte repeats */ s.match_length = 0; if (s.lookahead >= MIN_MATCH && s.strstart > 0) { scan = s.strstart - 1; prev = _win[scan]; if (prev === _win[++scan] && prev === _win[++scan] && prev === _win[++scan]) { strend = s.strstart + MAX_MATCH; do { /*jshint noempty:false*/ } while (prev === _win[++scan] && prev === _win[++scan] && prev === _win[++scan] && prev === _win[++scan] && prev === _win[++scan] && prev === _win[++scan] && prev === _win[++scan] && prev === _win[++scan] && scan < strend); s.match_length = MAX_MATCH - (strend - scan); if (s.match_length > s.lookahead) { s.match_length = s.lookahead; } } //Assert(scan <= s->window+(uInt)(s->window_size-1), "wild scan"); } /* Emit match if have run of MIN_MATCH or longer, else emit literal */ if (s.match_length >= MIN_MATCH) { //check_match(s, s.strstart, s.strstart - 1, s.match_length); /*** _tr_tally_dist(s, 1, s.match_length - MIN_MATCH, bflush); ***/ bflush = trees._tr_tally(s, 1, s.match_length - MIN_MATCH); s.lookahead -= s.match_length; s.strstart += s.match_length; s.match_length = 0; } else { /* No match, output a literal byte */ //Tracevv((stderr,"%c", s->window[s->strstart])); /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/ bflush = trees._tr_tally(s, 0, s.window[s.strstart]); s.lookahead--; s.strstart++; } if (bflush) { /*** FLUSH_BLOCK(s, 0); ***/ flush_block_only(s, false); if (s.strm.avail_out === 0) { return BS_NEED_MORE; } /***/ } } s.insert = 0; if (flush === Z_FINISH) { /*** FLUSH_BLOCK(s, 1); ***/ flush_block_only(s, true); if (s.strm.avail_out === 0) { return BS_FINISH_STARTED; } /***/ return BS_FINISH_DONE; } if (s.last_lit) { /*** FLUSH_BLOCK(s, 0); ***/ flush_block_only(s, false); if (s.strm.avail_out === 0) { return BS_NEED_MORE; } /***/ } return BS_BLOCK_DONE; } /* =========================================================================== * For Z_HUFFMAN_ONLY, do not look for matches. Do not maintain a hash table. * (It will be regenerated if this run of deflate switches away from Huffman.) */ function deflate_huff(s, flush) { var bflush; /* set if current block must be flushed */ for (;;) { /* Make sure that we have a literal to write. */ if (s.lookahead === 0) { fill_window(s); if (s.lookahead === 0) { if (flush === Z_NO_FLUSH) { return BS_NEED_MORE; } break; /* flush the current block */ } } /* Output a literal byte */ s.match_length = 0; //Tracevv((stderr,"%c", s->window[s->strstart])); /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/ bflush = trees._tr_tally(s, 0, s.window[s.strstart]); s.lookahead--; s.strstart++; if (bflush) { /*** FLUSH_BLOCK(s, 0); ***/ flush_block_only(s, false); if (s.strm.avail_out === 0) { return BS_NEED_MORE; } /***/ } } s.insert = 0; if (flush === Z_FINISH) { /*** FLUSH_BLOCK(s, 1); ***/ flush_block_only(s, true); if (s.strm.avail_out === 0) { return BS_FINISH_STARTED; } /***/ return BS_FINISH_DONE; } if (s.last_lit) { /*** FLUSH_BLOCK(s, 0); ***/ flush_block_only(s, false); if (s.strm.avail_out === 0) { return BS_NEED_MORE; } /***/ } return BS_BLOCK_DONE; } /* Values for max_lazy_match, good_match and max_chain_length, depending on * the desired pack level (0..9). The values given below have been tuned to * exclude worst case performance for pathological files. Better values may be * found for specific files. */ function Config(good_length, max_lazy, nice_length, max_chain, func) { this.good_length = good_length; this.max_lazy = max_lazy; this.nice_length = nice_length; this.max_chain = max_chain; this.func = func; } var configuration_table; configuration_table = [ /* good lazy nice chain */ new Config(0, 0, 0, 0, deflate_stored), /* 0 store only */ new Config(4, 4, 8, 4, deflate_fast), /* 1 max speed, no lazy matches */ new Config(4, 5, 16, 8, deflate_fast), /* 2 */ new Config(4, 6, 32, 32, deflate_fast), /* 3 */ new Config(4, 4, 16, 16, deflate_slow), /* 4 lazy matches */ new Config(8, 16, 32, 32, deflate_slow), /* 5 */ new Config(8, 16, 128, 128, deflate_slow), /* 6 */ new Config(8, 32, 128, 256, deflate_slow), /* 7 */ new Config(32, 128, 258, 1024, deflate_slow), /* 8 */ new Config(32, 258, 258, 4096, deflate_slow) /* 9 max compression */ ]; /* =========================================================================== * Initialize the "longest match" routines for a new zlib stream */ function lm_init(s) { s.window_size = 2 * s.w_size; /*** CLEAR_HASH(s); ***/ zero(s.head); // Fill with NIL (= 0); /* Set the default configuration parameters: */ s.max_lazy_match = configuration_table[s.level].max_lazy; s.good_match = configuration_table[s.level].good_length; s.nice_match = configuration_table[s.level].nice_length; s.max_chain_length = configuration_table[s.level].max_chain; s.strstart = 0; s.block_start = 0; s.lookahead = 0; s.insert = 0; s.match_length = s.prev_length = MIN_MATCH - 1; s.match_available = 0; s.ins_h = 0; } function DeflateState() { this.strm = null; /* pointer back to this zlib stream */ this.status = 0; /* as the name implies */ this.pending_buf = null; /* output still pending */ this.pending_buf_size = 0; /* size of pending_buf */ this.pending_out = 0; /* next pending byte to output to the stream */ this.pending = 0; /* nb of bytes in the pending buffer */ this.wrap = 0; /* bit 0 true for zlib, bit 1 true for gzip */ this.gzhead = null; /* gzip header information to write */ this.gzindex = 0; /* where in extra, name, or comment */ this.method = Z_DEFLATED; /* can only be DEFLATED */ this.last_flush = -1; /* value of flush param for previous deflate call */ this.w_size = 0; /* LZ77 window size (32K by default) */ this.w_bits = 0; /* log2(w_size) (8..16) */ this.w_mask = 0; /* w_size - 1 */ this.window = null; /* Sliding window. Input bytes are read into the second half of the window, * and move to the first half later to keep a dictionary of at least wSize * bytes. With this organization, matches are limited to a distance of * wSize-MAX_MATCH bytes, but this ensures that IO is always * performed with a length multiple of the block size. */ this.window_size = 0; /* Actual size of window: 2*wSize, except when the user input buffer * is directly used as sliding window. */ this.prev = null; /* Link to older string with same hash index. To limit the size of this * array to 64K, this link is maintained only for the last 32K strings. * An index in this array is thus a window index modulo 32K. */ this.head = null; /* Heads of the hash chains or NIL. */ this.ins_h = 0; /* hash index of string to be inserted */ this.hash_size = 0; /* number of elements in hash table */ this.hash_bits = 0; /* log2(hash_size) */ this.hash_mask = 0; /* hash_size-1 */ this.hash_shift = 0; /* Number of bits by which ins_h must be shifted at each input * step. It must be such that after MIN_MATCH steps, the oldest * byte no longer takes part in the hash key, that is: * hash_shift * MIN_MATCH >= hash_bits */ this.block_start = 0; /* Window position at the beginning of the current output block. Gets * negative when the window is moved backwards. */ this.match_length = 0; /* length of best match */ this.prev_match = 0; /* previous match */ this.match_available = 0; /* set if previous match exists */ this.strstart = 0; /* start of string to insert */ this.match_start = 0; /* start of matching string */ this.lookahead = 0; /* number of valid bytes ahead in window */ this.prev_length = 0; /* Length of the best match at previous step. Matches not greater than this * are discarded. This is used in the lazy match evaluation. */ this.max_chain_length = 0; /* To speed up deflation, hash chains are never searched beyond this * length. A higher limit improves compression ratio but degrades the * speed. */ this.max_lazy_match = 0; /* Attempt to find a better match only when the current match is strictly * smaller than this value. This mechanism is used only for compression * levels >= 4. */ // That's alias to max_lazy_match, don't use directly //this.max_insert_length = 0; /* Insert new strings in the hash table only if the match length is not * greater than this length. This saves time but degrades compression. * max_insert_length is used only for compression levels <= 3. */ this.level = 0; /* compression level (1..9) */ this.strategy = 0; /* favor or force Huffman coding*/ this.good_match = 0; /* Use a faster search when the previous match is longer than this */ this.nice_match = 0; /* Stop searching when current match exceeds this */ /* used by trees.c: */ /* Didn't use ct_data typedef below to suppress compiler warning */ // struct ct_data_s dyn_ltree[HEAP_SIZE]; /* literal and length tree */ // struct ct_data_s dyn_dtree[2*D_CODES+1]; /* distance tree */ // struct ct_data_s bl_tree[2*BL_CODES+1]; /* Huffman tree for bit lengths */ // Use flat array of DOUBLE size, with interleaved fata, // because JS does not support effective this.dyn_ltree = new utils.Buf16(HEAP_SIZE * 2); this.dyn_dtree = new utils.Buf16((2 * D_CODES + 1) * 2); this.bl_tree = new utils.Buf16((2 * BL_CODES + 1) * 2); zero(this.dyn_ltree); zero(this.dyn_dtree); zero(this.bl_tree); this.l_desc = null; /* desc. for literal tree */ this.d_desc = null; /* desc. for distance tree */ this.bl_desc = null; /* desc. for bit length tree */ //ush bl_count[MAX_BITS+1]; this.bl_count = new utils.Buf16(MAX_BITS + 1); /* number of codes at each bit length for an optimal tree */ //int heap[2*L_CODES+1]; /* heap used to build the Huffman trees */ this.heap = new utils.Buf16(2 * L_CODES + 1); /* heap used to build the Huffman trees */ zero(this.heap); this.heap_len = 0; /* number of elements in the heap */ this.heap_max = 0; /* element of largest frequency */ /* The sons of heap[n] are heap[2*n] and heap[2*n+1]. heap[0] is not used. * The same heap array is used to build all trees. */ this.depth = new utils.Buf16(2 * L_CODES + 1); //uch depth[2*L_CODES+1]; zero(this.depth); /* Depth of each subtree used as tie breaker for trees of equal frequency */ this.l_buf = 0; /* buffer index for literals or lengths */ this.lit_bufsize = 0; /* Size of match buffer for literals/lengths. There are 4 reasons for * limiting lit_bufsize to 64K: * - frequencies can be kept in 16 bit counters * - if compression is not successful for the first block, all input * data is still in the window so we can still emit a stored block even * when input comes from standard input. (This can also be done for * all blocks if lit_bufsize is not greater than 32K.) * - if compression is not successful for a file smaller than 64K, we can * even emit a stored file instead of a stored block (saving 5 bytes). * This is applicable only for zip (not gzip or zlib). * - creating new Huffman trees less frequently may not provide fast * adaptation to changes in the input data statistics. (Take for * example a binary file with poorly compressible code followed by * a highly compressible string table.) Smaller buffer sizes give * fast adaptation but have of course the overhead of transmitting * trees more frequently. * - I can't count above 4 */ this.last_lit = 0; /* running index in l_buf */ this.d_buf = 0; /* Buffer index for distances. To simplify the code, d_buf and l_buf have * the same number of elements. To use different lengths, an extra flag * array would be necessary. */ this.opt_len = 0; /* bit length of current block with optimal trees */ this.static_len = 0; /* bit length of current block with static trees */ this.matches = 0; /* number of string matches in current block */ this.insert = 0; /* bytes at end of window left to insert */ this.bi_buf = 0; /* Output buffer. bits are inserted starting at the bottom (least * significant bits). */ this.bi_valid = 0; /* Number of valid bits in bi_buf. All bits above the last valid bit * are always zero. */ // Used for window memory init. We safely ignore it for JS. That makes // sense only for pointers and memory check tools. //this.high_water = 0; /* High water mark offset in window for initialized bytes -- bytes above * this are set to zero in order to avoid memory check warnings when * longest match routines access bytes past the input. This is then * updated to the new high water mark. */ } function deflateResetKeep(strm) { var s; if (!strm || !strm.state) { return err(strm, Z_STREAM_ERROR); } strm.total_in = strm.total_out = 0; strm.data_type = Z_UNKNOWN; s = strm.state; s.pending = 0; s.pending_out = 0; if (s.wrap < 0) { s.wrap = -s.wrap; /* was made negative by deflate(..., Z_FINISH); */ } s.status = (s.wrap ? INIT_STATE : BUSY_STATE); strm.adler = (s.wrap === 2) ? 0 // crc32(0, Z_NULL, 0) : 1; // adler32(0, Z_NULL, 0) s.last_flush = Z_NO_FLUSH; trees._tr_init(s); return Z_OK; } function deflateReset(strm) { var ret = deflateResetKeep(strm); if (ret === Z_OK) { lm_init(strm.state); } return ret; } function deflateSetHeader(strm, head) { if (!strm || !strm.state) { return Z_STREAM_ERROR; } if (strm.state.wrap !== 2) { return Z_STREAM_ERROR; } strm.state.gzhead = head; return Z_OK; } function deflateInit2(strm, level, method, windowBits, memLevel, strategy) { if (!strm) { // === Z_NULL return Z_STREAM_ERROR; } var wrap = 1; if (level === Z_DEFAULT_COMPRESSION) { level = 6; } if (windowBits < 0) { /* suppress zlib wrapper */ wrap = 0; windowBits = -windowBits; } else if (windowBits > 15) { wrap = 2; /* write gzip wrapper instead */ windowBits -= 16; } if (memLevel < 1 || memLevel > MAX_MEM_LEVEL || method !== Z_DEFLATED || windowBits < 8 || windowBits > 15 || level < 0 || level > 9 || strategy < 0 || strategy > Z_FIXED) { return err(strm, Z_STREAM_ERROR); } if (windowBits === 8) { windowBits = 9; } /* until 256-byte window bug fixed */ var s = new DeflateState(); strm.state = s; s.strm = strm; s.wrap = wrap; s.gzhead = null; s.w_bits = windowBits; s.w_size = 1 << s.w_bits; s.w_mask = s.w_size - 1; s.hash_bits = memLevel + 7; s.hash_size = 1 << s.hash_bits; s.hash_mask = s.hash_size - 1; s.hash_shift = ~~((s.hash_bits + MIN_MATCH - 1) / MIN_MATCH); s.window = new utils.Buf8(s.w_size * 2); s.head = new utils.Buf16(s.hash_size); s.prev = new utils.Buf16(s.w_size); // Don't need mem init magic for JS. //s.high_water = 0; /* nothing written to s->window yet */ s.lit_bufsize = 1 << (memLevel + 6); /* 16K elements by default */ s.pending_buf_size = s.lit_bufsize * 4; s.pending_buf = new utils.Buf8(s.pending_buf_size); s.d_buf = s.lit_bufsize >> 1; s.l_buf = (1 + 2) * s.lit_bufsize; s.level = level; s.strategy = strategy; s.method = method; return deflateReset(strm); } function deflateInit(strm, level) { return deflateInit2(strm, level, Z_DEFLATED, MAX_WBITS, DEF_MEM_LEVEL, Z_DEFAULT_STRATEGY); } function deflate(strm, flush) { var old_flush, s; var beg, val; // for gzip header write only if (!strm || !strm.state || flush > Z_BLOCK || flush < 0) { return strm ? err(strm, Z_STREAM_ERROR) : Z_STREAM_ERROR; } s = strm.state; if (!strm.output || (!strm.input && strm.avail_in !== 0) || (s.status === FINISH_STATE && flush !== Z_FINISH)) { return err(strm, (strm.avail_out === 0) ? Z_BUF_ERROR : Z_STREAM_ERROR); } s.strm = strm; /* just in case */ old_flush = s.last_flush; s.last_flush = flush; /* Write the header */ if (s.status === INIT_STATE) { if (s.wrap === 2) { // GZIP header strm.adler = 0; //crc32(0L, Z_NULL, 0); put_byte(s, 31); put_byte(s, 139); put_byte(s, 8); if (!s.gzhead) { // s->gzhead == Z_NULL put_byte(s, 0); put_byte(s, 0); put_byte(s, 0); put_byte(s, 0); put_byte(s, 0); put_byte(s, s.level === 9 ? 2 : (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2 ? 4 : 0)); put_byte(s, OS_CODE); s.status = BUSY_STATE; } else { put_byte(s, (s.gzhead.text ? 1 : 0) + (s.gzhead.hcrc ? 2 : 0) + (!s.gzhead.extra ? 0 : 4) + (!s.gzhead.name ? 0 : 8) + (!s.gzhead.comment ? 0 : 16) ); put_byte(s, s.gzhead.time & 0xff); put_byte(s, (s.gzhead.time >> 8) & 0xff); put_byte(s, (s.gzhead.time >> 16) & 0xff); put_byte(s, (s.gzhead.time >> 24) & 0xff); put_byte(s, s.level === 9 ? 2 : (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2 ? 4 : 0)); put_byte(s, s.gzhead.os & 0xff); if (s.gzhead.extra && s.gzhead.extra.length) { put_byte(s, s.gzhead.extra.length & 0xff); put_byte(s, (s.gzhead.extra.length >> 8) & 0xff); } if (s.gzhead.hcrc) { strm.adler = crc32(strm.adler, s.pending_buf, s.pending, 0); } s.gzindex = 0; s.status = EXTRA_STATE; } } else // DEFLATE header { var header = (Z_DEFLATED + ((s.w_bits - 8) << 4)) << 8; var level_flags = -1; if (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2) { level_flags = 0; } else if (s.level < 6) { level_flags = 1; } else if (s.level === 6) { level_flags = 2; } else { level_flags = 3; } header |= (level_flags << 6); if (s.strstart !== 0) { header |= PRESET_DICT; } header += 31 - (header % 31); s.status = BUSY_STATE; putShortMSB(s, header); /* Save the adler32 of the preset dictionary: */ if (s.strstart !== 0) { putShortMSB(s, strm.adler >>> 16); putShortMSB(s, strm.adler & 0xffff); } strm.adler = 1; // adler32(0L, Z_NULL, 0); } } //#ifdef GZIP if (s.status === EXTRA_STATE) { if (s.gzhead.extra/* != Z_NULL*/) { beg = s.pending; /* start of bytes to update crc */ while (s.gzindex < (s.gzhead.extra.length & 0xffff)) { if (s.pending === s.pending_buf_size) { if (s.gzhead.hcrc && s.pending > beg) { strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg); } flush_pending(strm); beg = s.pending; if (s.pending === s.pending_buf_size) { break; } } put_byte(s, s.gzhead.extra[s.gzindex] & 0xff); s.gzindex++; } if (s.gzhead.hcrc && s.pending > beg) { strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg); } if (s.gzindex === s.gzhead.extra.length) { s.gzindex = 0; s.status = NAME_STATE; } } else { s.status = NAME_STATE; } } if (s.status === NAME_STATE) { if (s.gzhead.name/* != Z_NULL*/) { beg = s.pending; /* start of bytes to update crc */ //int val; do { if (s.pending === s.pending_buf_size) { if (s.gzhead.hcrc && s.pending > beg) { strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg); } flush_pending(strm); beg = s.pending; if (s.pending === s.pending_buf_size) { val = 1; break; } } // JS specific: little magic to add zero terminator to end of string if (s.gzindex < s.gzhead.name.length) { val = s.gzhead.name.charCodeAt(s.gzindex++) & 0xff; } else { val = 0; } put_byte(s, val); } while (val !== 0); if (s.gzhead.hcrc && s.pending > beg) { strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg); } if (val === 0) { s.gzindex = 0; s.status = COMMENT_STATE; } } else { s.status = COMMENT_STATE; } } if (s.status === COMMENT_STATE) { if (s.gzhead.comment/* != Z_NULL*/) { beg = s.pending; /* start of bytes to update crc */ //int val; do { if (s.pending === s.pending_buf_size) { if (s.gzhead.hcrc && s.pending > beg) { strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg); } flush_pending(strm); beg = s.pending; if (s.pending === s.pending_buf_size) { val = 1; break; } } // JS specific: little magic to add zero terminator to end of string if (s.gzindex < s.gzhead.comment.length) { val = s.gzhead.comment.charCodeAt(s.gzindex++) & 0xff; } else { val = 0; } put_byte(s, val); } while (val !== 0); if (s.gzhead.hcrc && s.pending > beg) { strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg); } if (val === 0) { s.status = HCRC_STATE; } } else { s.status = HCRC_STATE; } } if (s.status === HCRC_STATE) { if (s.gzhead.hcrc) { if (s.pending + 2 > s.pending_buf_size) { flush_pending(strm); } if (s.pending + 2 <= s.pending_buf_size) { put_byte(s, strm.adler & 0xff); put_byte(s, (strm.adler >> 8) & 0xff); strm.adler = 0; //crc32(0L, Z_NULL, 0); s.status = BUSY_STATE; } } else { s.status = BUSY_STATE; } } //#endif /* Flush as much pending output as possible */ if (s.pending !== 0) { flush_pending(strm); if (strm.avail_out === 0) { /* Since avail_out is 0, deflate will be called again with * more output space, but possibly with both pending and * avail_in equal to zero. There won't be anything to do, * but this is not an error situation so make sure we * return OK instead of BUF_ERROR at next call of deflate: */ s.last_flush = -1; return Z_OK; } /* Make sure there is something to do and avoid duplicate consecutive * flushes. For repeated and useless calls with Z_FINISH, we keep * returning Z_STREAM_END instead of Z_BUF_ERROR. */ } else if (strm.avail_in === 0 && rank(flush) <= rank(old_flush) && flush !== Z_FINISH) { return err(strm, Z_BUF_ERROR); } /* User must not provide more input after the first FINISH: */ if (s.status === FINISH_STATE && strm.avail_in !== 0) { return err(strm, Z_BUF_ERROR); } /* Start a new block or continue the current one. */ if (strm.avail_in !== 0 || s.lookahead !== 0 || (flush !== Z_NO_FLUSH && s.status !== FINISH_STATE)) { var bstate = (s.strategy === Z_HUFFMAN_ONLY) ? deflate_huff(s, flush) : (s.strategy === Z_RLE ? deflate_rle(s, flush) : configuration_table[s.level].func(s, flush)); if (bstate === BS_FINISH_STARTED || bstate === BS_FINISH_DONE) { s.status = FINISH_STATE; } if (bstate === BS_NEED_MORE || bstate === BS_FINISH_STARTED) { if (strm.avail_out === 0) { s.last_flush = -1; /* avoid BUF_ERROR next call, see above */ } return Z_OK; /* If flush != Z_NO_FLUSH && avail_out == 0, the next call * of deflate should use the same flush parameter to make sure * that the flush is complete. So we don't have to output an * empty block here, this will be done at next call. This also * ensures that for a very small output buffer, we emit at most * one empty block. */ } if (bstate === BS_BLOCK_DONE) { if (flush === Z_PARTIAL_FLUSH) { trees._tr_align(s); } else if (flush !== Z_BLOCK) { /* FULL_FLUSH or SYNC_FLUSH */ trees._tr_stored_block(s, 0, 0, false); /* For a full flush, this empty block will be recognized * as a special marker by inflate_sync(). */ if (flush === Z_FULL_FLUSH) { /*** CLEAR_HASH(s); ***/ /* forget history */ zero(s.head); // Fill with NIL (= 0); if (s.lookahead === 0) { s.strstart = 0; s.block_start = 0; s.insert = 0; } } } flush_pending(strm); if (strm.avail_out === 0) { s.last_flush = -1; /* avoid BUF_ERROR at next call, see above */ return Z_OK; } } } //Assert(strm->avail_out > 0, "bug2"); //if (strm.avail_out <= 0) { throw new Error("bug2");} if (flush !== Z_FINISH) { return Z_OK; } if (s.wrap <= 0) { return Z_STREAM_END; } /* Write the trailer */ if (s.wrap === 2) { put_byte(s, strm.adler & 0xff); put_byte(s, (strm.adler >> 8) & 0xff); put_byte(s, (strm.adler >> 16) & 0xff); put_byte(s, (strm.adler >> 24) & 0xff); put_byte(s, strm.total_in & 0xff); put_byte(s, (strm.total_in >> 8) & 0xff); put_byte(s, (strm.total_in >> 16) & 0xff); put_byte(s, (strm.total_in >> 24) & 0xff); } else { putShortMSB(s, strm.adler >>> 16); putShortMSB(s, strm.adler & 0xffff); } flush_pending(strm); /* If avail_out is zero, the application will call deflate again * to flush the rest. */ if (s.wrap > 0) { s.wrap = -s.wrap; } /* write the trailer only once! */ return s.pending !== 0 ? Z_OK : Z_STREAM_END; } function deflateEnd(strm) { var status; if (!strm/*== Z_NULL*/ || !strm.state/*== Z_NULL*/) { return Z_STREAM_ERROR; } status = strm.state.status; if (status !== INIT_STATE && status !== EXTRA_STATE && status !== NAME_STATE && status !== COMMENT_STATE && status !== HCRC_STATE && status !== BUSY_STATE && status !== FINISH_STATE ) { return err(strm, Z_STREAM_ERROR); } strm.state = null; return status === BUSY_STATE ? err(strm, Z_DATA_ERROR) : Z_OK; } /* ========================================================================= * Copy the source state to the destination state */ //function deflateCopy(dest, source) { // //} exports.deflateInit = deflateInit; exports.deflateInit2 = deflateInit2; exports.deflateReset = deflateReset; exports.deflateResetKeep = deflateResetKeep; exports.deflateSetHeader = deflateSetHeader; exports.deflate = deflate; exports.deflateEnd = deflateEnd; exports.deflateInfo = 'pako deflate (from Nodeca project)'; /* Not implemented exports.deflateBound = deflateBound; exports.deflateCopy = deflateCopy; exports.deflateSetDictionary = deflateSetDictionary; exports.deflateParams = deflateParams; exports.deflatePending = deflatePending; exports.deflatePrime = deflatePrime; exports.deflateTune = deflateTune; */ },{"../utils/common":80,"./adler32":82,"./crc32":84,"./messages":90,"./trees":91}],86:[function(_dereq_,module,exports){ 'use strict'; function GZheader() { /* true if compressed data believed to be text */ this.text = 0; /* modification time */ this.time = 0; /* extra flags (not used when writing a gzip file) */ this.xflags = 0; /* operating system */ this.os = 0; /* pointer to extra field or Z_NULL if none */ this.extra = null; /* extra field length (valid if extra != Z_NULL) */ this.extra_len = 0; // Actually, we don't need it in JS, // but leave for few code modifications // // Setup limits is not necessary because in js we should not preallocate memory // for inflate use constant limit in 65536 bytes // /* space at extra (only when reading header) */ // this.extra_max = 0; /* pointer to zero-terminated file name or Z_NULL */ this.name = ''; /* space at name (only when reading header) */ // this.name_max = 0; /* pointer to zero-terminated comment or Z_NULL */ this.comment = ''; /* space at comment (only when reading header) */ // this.comm_max = 0; /* true if there was or will be a header crc */ this.hcrc = 0; /* true when done reading gzip header (not used when writing a gzip file) */ this.done = false; } module.exports = GZheader; },{}],87:[function(_dereq_,module,exports){ 'use strict'; // See state defs from inflate.js var BAD = 30; /* got a data error -- remain here until reset */ var TYPE = 12; /* i: waiting for type bits, including last-flag bit */ /* Decode literal, length, and distance codes and write out the resulting literal and match bytes until either not enough input or output is available, an end-of-block is encountered, or a data error is encountered. When large enough input and output buffers are supplied to inflate(), for example, a 16K input buffer and a 64K output buffer, more than 95% of the inflate execution time is spent in this routine. Entry assumptions: state.mode === LEN strm.avail_in >= 6 strm.avail_out >= 258 start >= strm.avail_out state.bits < 8 On return, state.mode is one of: LEN -- ran out of enough output space or enough available input TYPE -- reached end of block code, inflate() to interpret next block BAD -- error in block data Notes: - The maximum input bits used by a length/distance pair is 15 bits for the length code, 5 bits for the length extra, 15 bits for the distance code, and 13 bits for the distance extra. This totals 48 bits, or six bytes. Therefore if strm.avail_in >= 6, then there is enough input to avoid checking for available input while decoding. - The maximum bytes that a single length/distance pair can output is 258 bytes, which is the maximum length that can be coded. inflate_fast() requires strm.avail_out >= 258 for each loop to avoid checking for output space. */ module.exports = function inflate_fast(strm, start) { var state; var _in; /* local strm.input */ var last; /* have enough input while in < last */ var _out; /* local strm.output */ var beg; /* inflate()'s initial strm.output */ var end; /* while out < end, enough space available */ //#ifdef INFLATE_STRICT var dmax; /* maximum distance from zlib header */ //#endif var wsize; /* window size or zero if not using window */ var whave; /* valid bytes in the window */ var wnext; /* window write index */ // Use `s_window` instead `window`, avoid conflict with instrumentation tools var s_window; /* allocated sliding window, if wsize != 0 */ var hold; /* local strm.hold */ var bits; /* local strm.bits */ var lcode; /* local strm.lencode */ var dcode; /* local strm.distcode */ var lmask; /* mask for first level of length codes */ var dmask; /* mask for first level of distance codes */ var here; /* retrieved table entry */ var op; /* code bits, operation, extra bits, or */ /* window position, window bytes to copy */ var len; /* match length, unused bytes */ var dist; /* match distance */ var from; /* where to copy match from */ var from_source; var input, output; // JS specific, because we have no pointers /* copy state to local variables */ state = strm.state; //here = state.here; _in = strm.next_in; input = strm.input; last = _in + (strm.avail_in - 5); _out = strm.next_out; output = strm.output; beg = _out - (start - strm.avail_out); end = _out + (strm.avail_out - 257); //#ifdef INFLATE_STRICT dmax = state.dmax; //#endif wsize = state.wsize; whave = state.whave; wnext = state.wnext; s_window = state.window; hold = state.hold; bits = state.bits; lcode = state.lencode; dcode = state.distcode; lmask = (1 << state.lenbits) - 1; dmask = (1 << state.distbits) - 1; /* decode literals and length/distances until end-of-block or not enough input data or output space */ top: do { if (bits < 15) { hold += input[_in++] << bits; bits += 8; hold += input[_in++] << bits; bits += 8; } here = lcode[hold & lmask]; dolen: for (;;) { // Goto emulation op = here >>> 24/*here.bits*/; hold >>>= op; bits -= op; op = (here >>> 16) & 0xff/*here.op*/; if (op === 0) { /* literal */ //Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ? // "inflate: literal '%c'\n" : // "inflate: literal 0x%02x\n", here.val)); output[_out++] = here & 0xffff/*here.val*/; } else if (op & 16) { /* length base */ len = here & 0xffff/*here.val*/; op &= 15; /* number of extra bits */ if (op) { if (bits < op) { hold += input[_in++] << bits; bits += 8; } len += hold & ((1 << op) - 1); hold >>>= op; bits -= op; } //Tracevv((stderr, "inflate: length %u\n", len)); if (bits < 15) { hold += input[_in++] << bits; bits += 8; hold += input[_in++] << bits; bits += 8; } here = dcode[hold & dmask]; dodist: for (;;) { // goto emulation op = here >>> 24/*here.bits*/; hold >>>= op; bits -= op; op = (here >>> 16) & 0xff/*here.op*/; if (op & 16) { /* distance base */ dist = here & 0xffff/*here.val*/; op &= 15; /* number of extra bits */ if (bits < op) { hold += input[_in++] << bits; bits += 8; if (bits < op) { hold += input[_in++] << bits; bits += 8; } } dist += hold & ((1 << op) - 1); //#ifdef INFLATE_STRICT if (dist > dmax) { strm.msg = 'invalid distance too far back'; state.mode = BAD; break top; } //#endif hold >>>= op; bits -= op; //Tracevv((stderr, "inflate: distance %u\n", dist)); op = _out - beg; /* max distance in output */ if (dist > op) { /* see if copy from window */ op = dist - op; /* distance back in window */ if (op > whave) { if (state.sane) { strm.msg = 'invalid distance too far back'; state.mode = BAD; break top; } // (!) This block is disabled in zlib defailts, // don't enable it for binary compatibility //#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR // if (len <= op - whave) { // do { // output[_out++] = 0; // } while (--len); // continue top; // } // len -= op - whave; // do { // output[_out++] = 0; // } while (--op > whave); // if (op === 0) { // from = _out - dist; // do { // output[_out++] = output[from++]; // } while (--len); // continue top; // } //#endif } from = 0; // window index from_source = s_window; if (wnext === 0) { /* very common case */ from += wsize - op; if (op < len) { /* some from window */ len -= op; do { output[_out++] = s_window[from++]; } while (--op); from = _out - dist; /* rest from output */ from_source = output; } } else if (wnext < op) { /* wrap around window */ from += wsize + wnext - op; op -= wnext; if (op < len) { /* some from end of window */ len -= op; do { output[_out++] = s_window[from++]; } while (--op); from = 0; if (wnext < len) { /* some from start of window */ op = wnext; len -= op; do { output[_out++] = s_window[from++]; } while (--op); from = _out - dist; /* rest from output */ from_source = output; } } } else { /* contiguous in window */ from += wnext - op; if (op < len) { /* some from window */ len -= op; do { output[_out++] = s_window[from++]; } while (--op); from = _out - dist; /* rest from output */ from_source = output; } } while (len > 2) { output[_out++] = from_source[from++]; output[_out++] = from_source[from++]; output[_out++] = from_source[from++]; len -= 3; } if (len) { output[_out++] = from_source[from++]; if (len > 1) { output[_out++] = from_source[from++]; } } } else { from = _out - dist; /* copy direct from output */ do { /* minimum length is three */ output[_out++] = output[from++]; output[_out++] = output[from++]; output[_out++] = output[from++]; len -= 3; } while (len > 2); if (len) { output[_out++] = output[from++]; if (len > 1) { output[_out++] = output[from++]; } } } } else if ((op & 64) === 0) { /* 2nd level distance code */ here = dcode[(here & 0xffff)/*here.val*/ + (hold & ((1 << op) - 1))]; continue dodist; } else { strm.msg = 'invalid distance code'; state.mode = BAD; break top; } break; // need to emulate goto via "continue" } } else if ((op & 64) === 0) { /* 2nd level length code */ here = lcode[(here & 0xffff)/*here.val*/ + (hold & ((1 << op) - 1))]; continue dolen; } else if (op & 32) { /* end-of-block */ //Tracevv((stderr, "inflate: end of block\n")); state.mode = TYPE; break top; } else { strm.msg = 'invalid literal/length code'; state.mode = BAD; break top; } break; // need to emulate goto via "continue" } } while (_in < last && _out < end); /* return unused bytes (on entry, bits < 8, so in won't go too far back) */ len = bits >> 3; _in -= len; bits -= len << 3; hold &= (1 << bits) - 1; /* update state and return */ strm.next_in = _in; strm.next_out = _out; strm.avail_in = (_in < last ? 5 + (last - _in) : 5 - (_in - last)); strm.avail_out = (_out < end ? 257 + (end - _out) : 257 - (_out - end)); state.hold = hold; state.bits = bits; return; }; },{}],88:[function(_dereq_,module,exports){ 'use strict'; var utils = _dereq_('../utils/common'); var adler32 = _dereq_('./adler32'); var crc32 = _dereq_('./crc32'); var inflate_fast = _dereq_('./inffast'); var inflate_table = _dereq_('./inftrees'); var CODES = 0; var LENS = 1; var DISTS = 2; /* Public constants ==========================================================*/ /* ===========================================================================*/ /* Allowed flush values; see deflate() and inflate() below for details */ //var Z_NO_FLUSH = 0; //var Z_PARTIAL_FLUSH = 1; //var Z_SYNC_FLUSH = 2; //var Z_FULL_FLUSH = 3; var Z_FINISH = 4; var Z_BLOCK = 5; var Z_TREES = 6; /* Return codes for the compression/decompression functions. Negative values * are errors, positive values are used for special but normal events. */ var Z_OK = 0; var Z_STREAM_END = 1; var Z_NEED_DICT = 2; //var Z_ERRNO = -1; var Z_STREAM_ERROR = -2; var Z_DATA_ERROR = -3; var Z_MEM_ERROR = -4; var Z_BUF_ERROR = -5; //var Z_VERSION_ERROR = -6; /* The deflate compression method */ var Z_DEFLATED = 8; /* STATES ====================================================================*/ /* ===========================================================================*/ var HEAD = 1; /* i: waiting for magic header */ var FLAGS = 2; /* i: waiting for method and flags (gzip) */ var TIME = 3; /* i: waiting for modification time (gzip) */ var OS = 4; /* i: waiting for extra flags and operating system (gzip) */ var EXLEN = 5; /* i: waiting for extra length (gzip) */ var EXTRA = 6; /* i: waiting for extra bytes (gzip) */ var NAME = 7; /* i: waiting for end of file name (gzip) */ var COMMENT = 8; /* i: waiting for end of comment (gzip) */ var HCRC = 9; /* i: waiting for header crc (gzip) */ var DICTID = 10; /* i: waiting for dictionary check value */ var DICT = 11; /* waiting for inflateSetDictionary() call */ var TYPE = 12; /* i: waiting for type bits, including last-flag bit */ var TYPEDO = 13; /* i: same, but skip check to exit inflate on new block */ var STORED = 14; /* i: waiting for stored size (length and complement) */ var COPY_ = 15; /* i/o: same as COPY below, but only first time in */ var COPY = 16; /* i/o: waiting for input or output to copy stored block */ var TABLE = 17; /* i: waiting for dynamic block table lengths */ var LENLENS = 18; /* i: waiting for code length code lengths */ var CODELENS = 19; /* i: waiting for length/lit and distance code lengths */ var LEN_ = 20; /* i: same as LEN below, but only first time in */ var LEN = 21; /* i: waiting for length/lit/eob code */ var LENEXT = 22; /* i: waiting for length extra bits */ var DIST = 23; /* i: waiting for distance code */ var DISTEXT = 24; /* i: waiting for distance extra bits */ var MATCH = 25; /* o: waiting for output space to copy string */ var LIT = 26; /* o: waiting for output space to write literal */ var CHECK = 27; /* i: waiting for 32-bit check value */ var LENGTH = 28; /* i: waiting for 32-bit length (gzip) */ var DONE = 29; /* finished check, done -- remain here until reset */ var BAD = 30; /* got a data error -- remain here until reset */ var MEM = 31; /* got an inflate() memory error -- remain here until reset */ var SYNC = 32; /* looking for synchronization bytes to restart inflate() */ /* ===========================================================================*/ var ENOUGH_LENS = 852; var ENOUGH_DISTS = 592; //var ENOUGH = (ENOUGH_LENS+ENOUGH_DISTS); var MAX_WBITS = 15; /* 32K LZ77 window */ var DEF_WBITS = MAX_WBITS; function zswap32(q) { return (((q >>> 24) & 0xff) + ((q >>> 8) & 0xff00) + ((q & 0xff00) << 8) + ((q & 0xff) << 24)); } function InflateState() { this.mode = 0; /* current inflate mode */ this.last = false; /* true if processing last block */ this.wrap = 0; /* bit 0 true for zlib, bit 1 true for gzip */ this.havedict = false; /* true if dictionary provided */ this.flags = 0; /* gzip header method and flags (0 if zlib) */ this.dmax = 0; /* zlib header max distance (INFLATE_STRICT) */ this.check = 0; /* protected copy of check value */ this.total = 0; /* protected copy of output count */ // TODO: may be {} this.head = null; /* where to save gzip header information */ /* sliding window */ this.wbits = 0; /* log base 2 of requested window size */ this.wsize = 0; /* window size or zero if not using window */ this.whave = 0; /* valid bytes in the window */ this.wnext = 0; /* window write index */ this.window = null; /* allocated sliding window, if needed */ /* bit accumulator */ this.hold = 0; /* input bit accumulator */ this.bits = 0; /* number of bits in "in" */ /* for string and stored block copying */ this.length = 0; /* literal or length of data to copy */ this.offset = 0; /* distance back to copy string from */ /* for table and code decoding */ this.extra = 0; /* extra bits needed */ /* fixed and dynamic code tables */ this.lencode = null; /* starting table for length/literal codes */ this.distcode = null; /* starting table for distance codes */ this.lenbits = 0; /* index bits for lencode */ this.distbits = 0; /* index bits for distcode */ /* dynamic table building */ this.ncode = 0; /* number of code length code lengths */ this.nlen = 0; /* number of length code lengths */ this.ndist = 0; /* number of distance code lengths */ this.have = 0; /* number of code lengths in lens[] */ this.next = null; /* next available space in codes[] */ this.lens = new utils.Buf16(320); /* temporary storage for code lengths */ this.work = new utils.Buf16(288); /* work area for code table building */ /* because we don't have pointers in js, we use lencode and distcode directly as buffers so we don't need codes */ //this.codes = new utils.Buf32(ENOUGH); /* space for code tables */ this.lendyn = null; /* dynamic table for length/literal codes (JS specific) */ this.distdyn = null; /* dynamic table for distance codes (JS specific) */ this.sane = 0; /* if false, allow invalid distance too far */ this.back = 0; /* bits back of last unprocessed length/lit */ this.was = 0; /* initial length of match */ } function inflateResetKeep(strm) { var state; if (!strm || !strm.state) { return Z_STREAM_ERROR; } state = strm.state; strm.total_in = strm.total_out = state.total = 0; strm.msg = ''; /*Z_NULL*/ if (state.wrap) { /* to support ill-conceived Java test suite */ strm.adler = state.wrap & 1; } state.mode = HEAD; state.last = 0; state.havedict = 0; state.dmax = 32768; state.head = null/*Z_NULL*/; state.hold = 0; state.bits = 0; //state.lencode = state.distcode = state.next = state.codes; state.lencode = state.lendyn = new utils.Buf32(ENOUGH_LENS); state.distcode = state.distdyn = new utils.Buf32(ENOUGH_DISTS); state.sane = 1; state.back = -1; //Tracev((stderr, "inflate: reset\n")); return Z_OK; } function inflateReset(strm) { var state; if (!strm || !strm.state) { return Z_STREAM_ERROR; } state = strm.state; state.wsize = 0; state.whave = 0; state.wnext = 0; return inflateResetKeep(strm); } function inflateReset2(strm, windowBits) { var wrap; var state; /* get the state */ if (!strm || !strm.state) { return Z_STREAM_ERROR; } state = strm.state; /* extract wrap request from windowBits parameter */ if (windowBits < 0) { wrap = 0; windowBits = -windowBits; } else { wrap = (windowBits >> 4) + 1; if (windowBits < 48) { windowBits &= 15; } } /* set number of window bits, free window if different */ if (windowBits && (windowBits < 8 || windowBits > 15)) { return Z_STREAM_ERROR; } if (state.window !== null && state.wbits !== windowBits) { state.window = null; } /* update state and reset the rest of it */ state.wrap = wrap; state.wbits = windowBits; return inflateReset(strm); } function inflateInit2(strm, windowBits) { var ret; var state; if (!strm) { return Z_STREAM_ERROR; } //strm.msg = Z_NULL; /* in case we return an error */ state = new InflateState(); //if (state === Z_NULL) return Z_MEM_ERROR; //Tracev((stderr, "inflate: allocated\n")); strm.state = state; state.window = null/*Z_NULL*/; ret = inflateReset2(strm, windowBits); if (ret !== Z_OK) { strm.state = null/*Z_NULL*/; } return ret; } function inflateInit(strm) { return inflateInit2(strm, DEF_WBITS); } /* Return state with length and distance decoding tables and index sizes set to fixed code decoding. Normally this returns fixed tables from inffixed.h. If BUILDFIXED is defined, then instead this routine builds the tables the first time it's called, and returns those tables the first time and thereafter. This reduces the size of the code by about 2K bytes, in exchange for a little execution time. However, BUILDFIXED should not be used for threaded applications, since the rewriting of the tables and virgin may not be thread-safe. */ var virgin = true; var lenfix, distfix; // We have no pointers in JS, so keep tables separate function fixedtables(state) { /* build fixed huffman tables if first call (may not be thread safe) */ if (virgin) { var sym; lenfix = new utils.Buf32(512); distfix = new utils.Buf32(32); /* literal/length table */ sym = 0; while (sym < 144) { state.lens[sym++] = 8; } while (sym < 256) { state.lens[sym++] = 9; } while (sym < 280) { state.lens[sym++] = 7; } while (sym < 288) { state.lens[sym++] = 8; } inflate_table(LENS, state.lens, 0, 288, lenfix, 0, state.work, { bits: 9 }); /* distance table */ sym = 0; while (sym < 32) { state.lens[sym++] = 5; } inflate_table(DISTS, state.lens, 0, 32, distfix, 0, state.work, { bits: 5 }); /* do this just once */ virgin = false; } state.lencode = lenfix; state.lenbits = 9; state.distcode = distfix; state.distbits = 5; } /* Update the window with the last wsize (normally 32K) bytes written before returning. If window does not exist yet, create it. This is only called when a window is already in use, or when output has been written during this inflate call, but the end of the deflate stream has not been reached yet. It is also called to create a window for dictionary data when a dictionary is loaded. Providing output buffers larger than 32K to inflate() should provide a speed advantage, since only the last 32K of output is copied to the sliding window upon return from inflate(), and since all distances after the first 32K of output will fall in the output data, making match copies simpler and faster. The advantage may be dependent on the size of the processor's data caches. */ function updatewindow(strm, src, end, copy) { var dist; var state = strm.state; /* if it hasn't been done already, allocate space for the window */ if (state.window === null) { state.wsize = 1 << state.wbits; state.wnext = 0; state.whave = 0; state.window = new utils.Buf8(state.wsize); } /* copy state->wsize or less output bytes into the circular window */ if (copy >= state.wsize) { utils.arraySet(state.window, src, end - state.wsize, state.wsize, 0); state.wnext = 0; state.whave = state.wsize; } else { dist = state.wsize - state.wnext; if (dist > copy) { dist = copy; } //zmemcpy(state->window + state->wnext, end - copy, dist); utils.arraySet(state.window, src, end - copy, dist, state.wnext); copy -= dist; if (copy) { //zmemcpy(state->window, end - copy, copy); utils.arraySet(state.window, src, end - copy, copy, 0); state.wnext = copy; state.whave = state.wsize; } else { state.wnext += dist; if (state.wnext === state.wsize) { state.wnext = 0; } if (state.whave < state.wsize) { state.whave += dist; } } } return 0; } function inflate(strm, flush) { var state; var input, output; // input/output buffers var next; /* next input INDEX */ var put; /* next output INDEX */ var have, left; /* available input and output */ var hold; /* bit buffer */ var bits; /* bits in bit buffer */ var _in, _out; /* save starting available input and output */ var copy; /* number of stored or match bytes to copy */ var from; /* where to copy match bytes from */ var from_source; var here = 0; /* current decoding table entry */ var here_bits, here_op, here_val; // paked "here" denormalized (JS specific) //var last; /* parent table entry */ var last_bits, last_op, last_val; // paked "last" denormalized (JS specific) var len; /* length to copy for repeats, bits to drop */ var ret; /* return code */ var hbuf = new utils.Buf8(4); /* buffer for gzip header crc calculation */ var opts; var n; // temporary var for NEED_BITS var order = /* permutation of code lengths */ [ 16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15 ]; if (!strm || !strm.state || !strm.output || (!strm.input && strm.avail_in !== 0)) { return Z_STREAM_ERROR; } state = strm.state; if (state.mode === TYPE) { state.mode = TYPEDO; } /* skip check */ //--- LOAD() --- put = strm.next_out; output = strm.output; left = strm.avail_out; next = strm.next_in; input = strm.input; have = strm.avail_in; hold = state.hold; bits = state.bits; //--- _in = have; _out = left; ret = Z_OK; inf_leave: // goto emulation for (;;) { switch (state.mode) { case HEAD: if (state.wrap === 0) { state.mode = TYPEDO; break; } //=== NEEDBITS(16); while (bits < 16) { if (have === 0) { break inf_leave; } have--; hold += input[next++] << bits; bits += 8; } //===// if ((state.wrap & 2) && hold === 0x8b1f) { /* gzip header */ state.check = 0/*crc32(0L, Z_NULL, 0)*/; //=== CRC2(state.check, hold); hbuf[0] = hold & 0xff; hbuf[1] = (hold >>> 8) & 0xff; state.check = crc32(state.check, hbuf, 2, 0); //===// //=== INITBITS(); hold = 0; bits = 0; //===// state.mode = FLAGS; break; } state.flags = 0; /* expect zlib header */ if (state.head) { state.head.done = false; } if (!(state.wrap & 1) || /* check if zlib header allowed */ (((hold & 0xff)/*BITS(8)*/ << 8) + (hold >> 8)) % 31) { strm.msg = 'incorrect header check'; state.mode = BAD; break; } if ((hold & 0x0f)/*BITS(4)*/ !== Z_DEFLATED) { strm.msg = 'unknown compression method'; state.mode = BAD; break; } //--- DROPBITS(4) ---// hold >>>= 4; bits -= 4; //---// len = (hold & 0x0f)/*BITS(4)*/ + 8; if (state.wbits === 0) { state.wbits = len; } else if (len > state.wbits) { strm.msg = 'invalid window size'; state.mode = BAD; break; } state.dmax = 1 << len; //Tracev((stderr, "inflate: zlib header ok\n")); strm.adler = state.check = 1/*adler32(0L, Z_NULL, 0)*/; state.mode = hold & 0x200 ? DICTID : TYPE; //=== INITBITS(); hold = 0; bits = 0; //===// break; case FLAGS: //=== NEEDBITS(16); */ while (bits < 16) { if (have === 0) { break inf_leave; } have--; hold += input[next++] << bits; bits += 8; } //===// state.flags = hold; if ((state.flags & 0xff) !== Z_DEFLATED) { strm.msg = 'unknown compression method'; state.mode = BAD; break; } if (state.flags & 0xe000) { strm.msg = 'unknown header flags set'; state.mode = BAD; break; } if (state.head) { state.head.text = ((hold >> 8) & 1); } if (state.flags & 0x0200) { //=== CRC2(state.check, hold); hbuf[0] = hold & 0xff; hbuf[1] = (hold >>> 8) & 0xff; state.check = crc32(state.check, hbuf, 2, 0); //===// } //=== INITBITS(); hold = 0; bits = 0; //===// state.mode = TIME; /* falls through */ case TIME: //=== NEEDBITS(32); */ while (bits < 32) { if (have === 0) { break inf_leave; } have--; hold += input[next++] << bits; bits += 8; } //===// if (state.head) { state.head.time = hold; } if (state.flags & 0x0200) { //=== CRC4(state.check, hold) hbuf[0] = hold & 0xff; hbuf[1] = (hold >>> 8) & 0xff; hbuf[2] = (hold >>> 16) & 0xff; hbuf[3] = (hold >>> 24) & 0xff; state.check = crc32(state.check, hbuf, 4, 0); //=== } //=== INITBITS(); hold = 0; bits = 0; //===// state.mode = OS; /* falls through */ case OS: //=== NEEDBITS(16); */ while (bits < 16) { if (have === 0) { break inf_leave; } have--; hold += input[next++] << bits; bits += 8; } //===// if (state.head) { state.head.xflags = (hold & 0xff); state.head.os = (hold >> 8); } if (state.flags & 0x0200) { //=== CRC2(state.check, hold); hbuf[0] = hold & 0xff; hbuf[1] = (hold >>> 8) & 0xff; state.check = crc32(state.check, hbuf, 2, 0); //===// } //=== INITBITS(); hold = 0; bits = 0; //===// state.mode = EXLEN; /* falls through */ case EXLEN: if (state.flags & 0x0400) { //=== NEEDBITS(16); */ while (bits < 16) { if (have === 0) { break inf_leave; } have--; hold += input[next++] << bits; bits += 8; } //===// state.length = hold; if (state.head) { state.head.extra_len = hold; } if (state.flags & 0x0200) { //=== CRC2(state.check, hold); hbuf[0] = hold & 0xff; hbuf[1] = (hold >>> 8) & 0xff; state.check = crc32(state.check, hbuf, 2, 0); //===// } //=== INITBITS(); hold = 0; bits = 0; //===// } else if (state.head) { state.head.extra = null/*Z_NULL*/; } state.mode = EXTRA; /* falls through */ case EXTRA: if (state.flags & 0x0400) { copy = state.length; if (copy > have) { copy = have; } if (copy) { if (state.head) { len = state.head.extra_len - state.length; if (!state.head.extra) { // Use untyped array for more conveniend processing later state.head.extra = new Array(state.head.extra_len); } utils.arraySet( state.head.extra, input, next, // extra field is limited to 65536 bytes // - no need for additional size check copy, /*len + copy > state.head.extra_max - len ? state.head.extra_max : copy,*/ len ); //zmemcpy(state.head.extra + len, next, // len + copy > state.head.extra_max ? // state.head.extra_max - len : copy); } if (state.flags & 0x0200) { state.check = crc32(state.check, input, copy, next); } have -= copy; next += copy; state.length -= copy; } if (state.length) { break inf_leave; } } state.length = 0; state.mode = NAME; /* falls through */ case NAME: if (state.flags & 0x0800) { if (have === 0) { break inf_leave; } copy = 0; do { // TODO: 2 or 1 bytes? len = input[next + copy++]; /* use constant limit because in js we should not preallocate memory */ if (state.head && len && (state.length < 65536 /*state.head.name_max*/)) { state.head.name += String.fromCharCode(len); } } while (len && copy < have); if (state.flags & 0x0200) { state.check = crc32(state.check, input, copy, next); } have -= copy; next += copy; if (len) { break inf_leave; } } else if (state.head) { state.head.name = null; } state.length = 0; state.mode = COMMENT; /* falls through */ case COMMENT: if (state.flags & 0x1000) { if (have === 0) { break inf_leave; } copy = 0; do { len = input[next + copy++]; /* use constant limit because in js we should not preallocate memory */ if (state.head && len && (state.length < 65536 /*state.head.comm_max*/)) { state.head.comment += String.fromCharCode(len); } } while (len && copy < have); if (state.flags & 0x0200) { state.check = crc32(state.check, input, copy, next); } have -= copy; next += copy; if (len) { break inf_leave; } } else if (state.head) { state.head.comment = null; } state.mode = HCRC; /* falls through */ case HCRC: if (state.flags & 0x0200) { //=== NEEDBITS(16); */ while (bits < 16) { if (have === 0) { break inf_leave; } have--; hold += input[next++] << bits; bits += 8; } //===// if (hold !== (state.check & 0xffff)) { strm.msg = 'header crc mismatch'; state.mode = BAD; break; } //=== INITBITS(); hold = 0; bits = 0; //===// } if (state.head) { state.head.hcrc = ((state.flags >> 9) & 1); state.head.done = true; } strm.adler = state.check = 0; state.mode = TYPE; break; case DICTID: //=== NEEDBITS(32); */ while (bits < 32) { if (have === 0) { break inf_leave; } have--; hold += input[next++] << bits; bits += 8; } //===// strm.adler = state.check = zswap32(hold); //=== INITBITS(); hold = 0; bits = 0; //===// state.mode = DICT; /* falls through */ case DICT: if (state.havedict === 0) { //--- RESTORE() --- strm.next_out = put; strm.avail_out = left; strm.next_in = next; strm.avail_in = have; state.hold = hold; state.bits = bits; //--- return Z_NEED_DICT; } strm.adler = state.check = 1/*adler32(0L, Z_NULL, 0)*/; state.mode = TYPE; /* falls through */ case TYPE: if (flush === Z_BLOCK || flush === Z_TREES) { break inf_leave; } /* falls through */ case TYPEDO: if (state.last) { //--- BYTEBITS() ---// hold >>>= bits & 7; bits -= bits & 7; //---// state.mode = CHECK; break; } //=== NEEDBITS(3); */ while (bits < 3) { if (have === 0) { break inf_leave; } have--; hold += input[next++] << bits; bits += 8; } //===// state.last = (hold & 0x01)/*BITS(1)*/; //--- DROPBITS(1) ---// hold >>>= 1; bits -= 1; //---// switch ((hold & 0x03)/*BITS(2)*/) { case 0: /* stored block */ //Tracev((stderr, "inflate: stored block%s\n", // state.last ? " (last)" : "")); state.mode = STORED; break; case 1: /* fixed block */ fixedtables(state); //Tracev((stderr, "inflate: fixed codes block%s\n", // state.last ? " (last)" : "")); state.mode = LEN_; /* decode codes */ if (flush === Z_TREES) { //--- DROPBITS(2) ---// hold >>>= 2; bits -= 2; //---// break inf_leave; } break; case 2: /* dynamic block */ //Tracev((stderr, "inflate: dynamic codes block%s\n", // state.last ? " (last)" : "")); state.mode = TABLE; break; case 3: strm.msg = 'invalid block type'; state.mode = BAD; } //--- DROPBITS(2) ---// hold >>>= 2; bits -= 2; //---// break; case STORED: //--- BYTEBITS() ---// /* go to byte boundary */ hold >>>= bits & 7; bits -= bits & 7; //---// //=== NEEDBITS(32); */ while (bits < 32) { if (have === 0) { break inf_leave; } have--; hold += input[next++] << bits; bits += 8; } //===// if ((hold & 0xffff) !== ((hold >>> 16) ^ 0xffff)) { strm.msg = 'invalid stored block lengths'; state.mode = BAD; break; } state.length = hold & 0xffff; //Tracev((stderr, "inflate: stored length %u\n", // state.length)); //=== INITBITS(); hold = 0; bits = 0; //===// state.mode = COPY_; if (flush === Z_TREES) { break inf_leave; } /* falls through */ case COPY_: state.mode = COPY; /* falls through */ case COPY: copy = state.length; if (copy) { if (copy > have) { copy = have; } if (copy > left) { copy = left; } if (copy === 0) { break inf_leave; } //--- zmemcpy(put, next, copy); --- utils.arraySet(output, input, next, copy, put); //---// have -= copy; next += copy; left -= copy; put += copy; state.length -= copy; break; } //Tracev((stderr, "inflate: stored end\n")); state.mode = TYPE; break; case TABLE: //=== NEEDBITS(14); */ while (bits < 14) { if (have === 0) { break inf_leave; } have--; hold += input[next++] << bits; bits += 8; } //===// state.nlen = (hold & 0x1f)/*BITS(5)*/ + 257; //--- DROPBITS(5) ---// hold >>>= 5; bits -= 5; //---// state.ndist = (hold & 0x1f)/*BITS(5)*/ + 1; //--- DROPBITS(5) ---// hold >>>= 5; bits -= 5; //---// state.ncode = (hold & 0x0f)/*BITS(4)*/ + 4; //--- DROPBITS(4) ---// hold >>>= 4; bits -= 4; //---// //#ifndef PKZIP_BUG_WORKAROUND if (state.nlen > 286 || state.ndist > 30) { strm.msg = 'too many length or distance symbols'; state.mode = BAD; break; } //#endif //Tracev((stderr, "inflate: table sizes ok\n")); state.have = 0; state.mode = LENLENS; /* falls through */ case LENLENS: while (state.have < state.ncode) { //=== NEEDBITS(3); while (bits < 3) { if (have === 0) { break inf_leave; } have--; hold += input[next++] << bits; bits += 8; } //===// state.lens[order[state.have++]] = (hold & 0x07);//BITS(3); //--- DROPBITS(3) ---// hold >>>= 3; bits -= 3; //---// } while (state.have < 19) { state.lens[order[state.have++]] = 0; } // We have separate tables & no pointers. 2 commented lines below not needed. //state.next = state.codes; //state.lencode = state.next; // Switch to use dynamic table state.lencode = state.lendyn; state.lenbits = 7; opts = { bits: state.lenbits }; ret = inflate_table(CODES, state.lens, 0, 19, state.lencode, 0, state.work, opts); state.lenbits = opts.bits; if (ret) { strm.msg = 'invalid code lengths set'; state.mode = BAD; break; } //Tracev((stderr, "inflate: code lengths ok\n")); state.have = 0; state.mode = CODELENS; /* falls through */ case CODELENS: while (state.have < state.nlen + state.ndist) { for (;;) { here = state.lencode[hold & ((1 << state.lenbits) - 1)];/*BITS(state.lenbits)*/ here_bits = here >>> 24; here_op = (here >>> 16) & 0xff; here_val = here & 0xffff; if ((here_bits) <= bits) { break; } //--- PULLBYTE() ---// if (have === 0) { break inf_leave; } have--; hold += input[next++] << bits; bits += 8; //---// } if (here_val < 16) { //--- DROPBITS(here.bits) ---// hold >>>= here_bits; bits -= here_bits; //---// state.lens[state.have++] = here_val; } else { if (here_val === 16) { //=== NEEDBITS(here.bits + 2); n = here_bits + 2; while (bits < n) { if (have === 0) { break inf_leave; } have--; hold += input[next++] << bits; bits += 8; } //===// //--- DROPBITS(here.bits) ---// hold >>>= here_bits; bits -= here_bits; //---// if (state.have === 0) { strm.msg = 'invalid bit length repeat'; state.mode = BAD; break; } len = state.lens[state.have - 1]; copy = 3 + (hold & 0x03);//BITS(2); //--- DROPBITS(2) ---// hold >>>= 2; bits -= 2; //---// } else if (here_val === 17) { //=== NEEDBITS(here.bits + 3); n = here_bits + 3; while (bits < n) { if (have === 0) { break inf_leave; } have--; hold += input[next++] << bits; bits += 8; } //===// //--- DROPBITS(here.bits) ---// hold >>>= here_bits; bits -= here_bits; //---// len = 0; copy = 3 + (hold & 0x07);//BITS(3); //--- DROPBITS(3) ---// hold >>>= 3; bits -= 3; //---// } else { //=== NEEDBITS(here.bits + 7); n = here_bits + 7; while (bits < n) { if (have === 0) { break inf_leave; } have--; hold += input[next++] << bits; bits += 8; } //===// //--- DROPBITS(here.bits) ---// hold >>>= here_bits; bits -= here_bits; //---// len = 0; copy = 11 + (hold & 0x7f);//BITS(7); //--- DROPBITS(7) ---// hold >>>= 7; bits -= 7; //---// } if (state.have + copy > state.nlen + state.ndist) { strm.msg = 'invalid bit length repeat'; state.mode = BAD; break; } while (copy--) { state.lens[state.have++] = len; } } } /* handle error breaks in while */ if (state.mode === BAD) { break; } /* check for end-of-block code (better have one) */ if (state.lens[256] === 0) { strm.msg = 'invalid code -- missing end-of-block'; state.mode = BAD; break; } /* build code tables -- note: do not change the lenbits or distbits values here (9 and 6) without reading the comments in inftrees.h concerning the ENOUGH constants, which depend on those values */ state.lenbits = 9; opts = { bits: state.lenbits }; ret = inflate_table(LENS, state.lens, 0, state.nlen, state.lencode, 0, state.work, opts); // We have separate tables & no pointers. 2 commented lines below not needed. // state.next_index = opts.table_index; state.lenbits = opts.bits; // state.lencode = state.next; if (ret) { strm.msg = 'invalid literal/lengths set'; state.mode = BAD; break; } state.distbits = 6; //state.distcode.copy(state.codes); // Switch to use dynamic table state.distcode = state.distdyn; opts = { bits: state.distbits }; ret = inflate_table(DISTS, state.lens, state.nlen, state.ndist, state.distcode, 0, state.work, opts); // We have separate tables & no pointers. 2 commented lines below not needed. // state.next_index = opts.table_index; state.distbits = opts.bits; // state.distcode = state.next; if (ret) { strm.msg = 'invalid distances set'; state.mode = BAD; break; } //Tracev((stderr, 'inflate: codes ok\n')); state.mode = LEN_; if (flush === Z_TREES) { break inf_leave; } /* falls through */ case LEN_: state.mode = LEN; /* falls through */ case LEN: if (have >= 6 && left >= 258) { //--- RESTORE() --- strm.next_out = put; strm.avail_out = left; strm.next_in = next; strm.avail_in = have; state.hold = hold; state.bits = bits; //--- inflate_fast(strm, _out); //--- LOAD() --- put = strm.next_out; output = strm.output; left = strm.avail_out; next = strm.next_in; input = strm.input; have = strm.avail_in; hold = state.hold; bits = state.bits; //--- if (state.mode === TYPE) { state.back = -1; } break; } state.back = 0; for (;;) { here = state.lencode[hold & ((1 << state.lenbits) - 1)]; /*BITS(state.lenbits)*/ here_bits = here >>> 24; here_op = (here >>> 16) & 0xff; here_val = here & 0xffff; if (here_bits <= bits) { break; } //--- PULLBYTE() ---// if (have === 0) { break inf_leave; } have--; hold += input[next++] << bits; bits += 8; //---// } if (here_op && (here_op & 0xf0) === 0) { last_bits = here_bits; last_op = here_op; last_val = here_val; for (;;) { here = state.lencode[last_val + ((hold & ((1 << (last_bits + last_op)) - 1))/*BITS(last.bits + last.op)*/ >> last_bits)]; here_bits = here >>> 24; here_op = (here >>> 16) & 0xff; here_val = here & 0xffff; if ((last_bits + here_bits) <= bits) { break; } //--- PULLBYTE() ---// if (have === 0) { break inf_leave; } have--; hold += input[next++] << bits; bits += 8; //---// } //--- DROPBITS(last.bits) ---// hold >>>= last_bits; bits -= last_bits; //---// state.back += last_bits; } //--- DROPBITS(here.bits) ---// hold >>>= here_bits; bits -= here_bits; //---// state.back += here_bits; state.length = here_val; if (here_op === 0) { //Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ? // "inflate: literal '%c'\n" : // "inflate: literal 0x%02x\n", here.val)); state.mode = LIT; break; } if (here_op & 32) { //Tracevv((stderr, "inflate: end of block\n")); state.back = -1; state.mode = TYPE; break; } if (here_op & 64) { strm.msg = 'invalid literal/length code'; state.mode = BAD; break; } state.extra = here_op & 15; state.mode = LENEXT; /* falls through */ case LENEXT: if (state.extra) { //=== NEEDBITS(state.extra); n = state.extra; while (bits < n) { if (have === 0) { break inf_leave; } have--; hold += input[next++] << bits; bits += 8; } //===// state.length += hold & ((1 << state.extra) - 1)/*BITS(state.extra)*/; //--- DROPBITS(state.extra) ---// hold >>>= state.extra; bits -= state.extra; //---// state.back += state.extra; } //Tracevv((stderr, "inflate: length %u\n", state.length)); state.was = state.length; state.mode = DIST; /* falls through */ case DIST: for (;;) { here = state.distcode[hold & ((1 << state.distbits) - 1)];/*BITS(state.distbits)*/ here_bits = here >>> 24; here_op = (here >>> 16) & 0xff; here_val = here & 0xffff; if ((here_bits) <= bits) { break; } //--- PULLBYTE() ---// if (have === 0) { break inf_leave; } have--; hold += input[next++] << bits; bits += 8; //---// } if ((here_op & 0xf0) === 0) { last_bits = here_bits; last_op = here_op; last_val = here_val; for (;;) { here = state.distcode[last_val + ((hold & ((1 << (last_bits + last_op)) - 1))/*BITS(last.bits + last.op)*/ >> last_bits)]; here_bits = here >>> 24; here_op = (here >>> 16) & 0xff; here_val = here & 0xffff; if ((last_bits + here_bits) <= bits) { break; } //--- PULLBYTE() ---// if (have === 0) { break inf_leave; } have--; hold += input[next++] << bits; bits += 8; //---// } //--- DROPBITS(last.bits) ---// hold >>>= last_bits; bits -= last_bits; //---// state.back += last_bits; } //--- DROPBITS(here.bits) ---// hold >>>= here_bits; bits -= here_bits; //---// state.back += here_bits; if (here_op & 64) { strm.msg = 'invalid distance code'; state.mode = BAD; break; } state.offset = here_val; state.extra = (here_op) & 15; state.mode = DISTEXT; /* falls through */ case DISTEXT: if (state.extra) { //=== NEEDBITS(state.extra); n = state.extra; while (bits < n) { if (have === 0) { break inf_leave; } have--; hold += input[next++] << bits; bits += 8; } //===// state.offset += hold & ((1 << state.extra) - 1)/*BITS(state.extra)*/; //--- DROPBITS(state.extra) ---// hold >>>= state.extra; bits -= state.extra; //---// state.back += state.extra; } //#ifdef INFLATE_STRICT if (state.offset > state.dmax) { strm.msg = 'invalid distance too far back'; state.mode = BAD; break; } //#endif //Tracevv((stderr, "inflate: distance %u\n", state.offset)); state.mode = MATCH; /* falls through */ case MATCH: if (left === 0) { break inf_leave; } copy = _out - left; if (state.offset > copy) { /* copy from window */ copy = state.offset - copy; if (copy > state.whave) { if (state.sane) { strm.msg = 'invalid distance too far back'; state.mode = BAD; break; } // (!) This block is disabled in zlib defailts, // don't enable it for binary compatibility //#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR // Trace((stderr, "inflate.c too far\n")); // copy -= state.whave; // if (copy > state.length) { copy = state.length; } // if (copy > left) { copy = left; } // left -= copy; // state.length -= copy; // do { // output[put++] = 0; // } while (--copy); // if (state.length === 0) { state.mode = LEN; } // break; //#endif } if (copy > state.wnext) { copy -= state.wnext; from = state.wsize - copy; } else { from = state.wnext - copy; } if (copy > state.length) { copy = state.length; } from_source = state.window; } else { /* copy from output */ from_source = output; from = put - state.offset; copy = state.length; } if (copy > left) { copy = left; } left -= copy; state.length -= copy; do { output[put++] = from_source[from++]; } while (--copy); if (state.length === 0) { state.mode = LEN; } break; case LIT: if (left === 0) { break inf_leave; } output[put++] = state.length; left--; state.mode = LEN; break; case CHECK: if (state.wrap) { //=== NEEDBITS(32); while (bits < 32) { if (have === 0) { break inf_leave; } have--; // Use '|' insdead of '+' to make sure that result is signed hold |= input[next++] << bits; bits += 8; } //===// _out -= left; strm.total_out += _out; state.total += _out; if (_out) { strm.adler = state.check = /*UPDATE(state.check, put - _out, _out);*/ (state.flags ? crc32(state.check, output, _out, put - _out) : adler32(state.check, output, _out, put - _out)); } _out = left; // NB: crc32 stored as signed 32-bit int, zswap32 returns signed too if ((state.flags ? hold : zswap32(hold)) !== state.check) { strm.msg = 'incorrect data check'; state.mode = BAD; break; } //=== INITBITS(); hold = 0; bits = 0; //===// //Tracev((stderr, "inflate: check matches trailer\n")); } state.mode = LENGTH; /* falls through */ case LENGTH: if (state.wrap && state.flags) { //=== NEEDBITS(32); while (bits < 32) { if (have === 0) { break inf_leave; } have--; hold += input[next++] << bits; bits += 8; } //===// if (hold !== (state.total & 0xffffffff)) { strm.msg = 'incorrect length check'; state.mode = BAD; break; } //=== INITBITS(); hold = 0; bits = 0; //===// //Tracev((stderr, "inflate: length matches trailer\n")); } state.mode = DONE; /* falls through */ case DONE: ret = Z_STREAM_END; break inf_leave; case BAD: ret = Z_DATA_ERROR; break inf_leave; case MEM: return Z_MEM_ERROR; case SYNC: /* falls through */ default: return Z_STREAM_ERROR; } } // inf_leave <- here is real place for "goto inf_leave", emulated via "break inf_leave" /* Return from inflate(), updating the total counts and the check value. If there was no progress during the inflate() call, return a buffer error. Call updatewindow() to create and/or update the window state. Note: a memory error from inflate() is non-recoverable. */ //--- RESTORE() --- strm.next_out = put; strm.avail_out = left; strm.next_in = next; strm.avail_in = have; state.hold = hold; state.bits = bits; //--- if (state.wsize || (_out !== strm.avail_out && state.mode < BAD && (state.mode < CHECK || flush !== Z_FINISH))) { if (updatewindow(strm, strm.output, strm.next_out, _out - strm.avail_out)) { state.mode = MEM; return Z_MEM_ERROR; } } _in -= strm.avail_in; _out -= strm.avail_out; strm.total_in += _in; strm.total_out += _out; state.total += _out; if (state.wrap && _out) { strm.adler = state.check = /*UPDATE(state.check, strm.next_out - _out, _out);*/ (state.flags ? crc32(state.check, output, _out, strm.next_out - _out) : adler32(state.check, output, _out, strm.next_out - _out)); } strm.data_type = state.bits + (state.last ? 64 : 0) + (state.mode === TYPE ? 128 : 0) + (state.mode === LEN_ || state.mode === COPY_ ? 256 : 0); if (((_in === 0 && _out === 0) || flush === Z_FINISH) && ret === Z_OK) { ret = Z_BUF_ERROR; } return ret; } function inflateEnd(strm) { if (!strm || !strm.state /*|| strm->zfree == (free_func)0*/) { return Z_STREAM_ERROR; } var state = strm.state; if (state.window) { state.window = null; } strm.state = null; return Z_OK; } function inflateGetHeader(strm, head) { var state; /* check state */ if (!strm || !strm.state) { return Z_STREAM_ERROR; } state = strm.state; if ((state.wrap & 2) === 0) { return Z_STREAM_ERROR; } /* save header structure */ state.head = head; head.done = false; return Z_OK; } exports.inflateReset = inflateReset; exports.inflateReset2 = inflateReset2; exports.inflateResetKeep = inflateResetKeep; exports.inflateInit = inflateInit; exports.inflateInit2 = inflateInit2; exports.inflate = inflate; exports.inflateEnd = inflateEnd; exports.inflateGetHeader = inflateGetHeader; exports.inflateInfo = 'pako inflate (from Nodeca project)'; /* Not implemented exports.inflateCopy = inflateCopy; exports.inflateGetDictionary = inflateGetDictionary; exports.inflateMark = inflateMark; exports.inflatePrime = inflatePrime; exports.inflateSetDictionary = inflateSetDictionary; exports.inflateSync = inflateSync; exports.inflateSyncPoint = inflateSyncPoint; exports.inflateUndermine = inflateUndermine; */ },{"../utils/common":80,"./adler32":82,"./crc32":84,"./inffast":87,"./inftrees":89}],89:[function(_dereq_,module,exports){ 'use strict'; var utils = _dereq_('../utils/common'); var MAXBITS = 15; var ENOUGH_LENS = 852; var ENOUGH_DISTS = 592; //var ENOUGH = (ENOUGH_LENS+ENOUGH_DISTS); var CODES = 0; var LENS = 1; var DISTS = 2; var lbase = [ /* Length codes 257..285 base */ 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 ]; var lext = [ /* Length codes 257..285 extra */ 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 ]; var dbase = [ /* Distance codes 0..29 base */ 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 ]; var dext = [ /* Distance codes 0..29 extra */ 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 ]; module.exports = function inflate_table(type, lens, lens_index, codes, table, table_index, work, opts) { var bits = opts.bits; //here = opts.here; /* table entry for duplication */ var len = 0; /* a code's length in bits */ var sym = 0; /* index of code symbols */ var min = 0, max = 0; /* minimum and maximum code lengths */ var root = 0; /* number of index bits for root table */ var curr = 0; /* number of index bits for current table */ var drop = 0; /* code bits to drop for sub-table */ var left = 0; /* number of prefix codes available */ var used = 0; /* code entries in table used */ var huff = 0; /* Huffman code */ var incr; /* for incrementing code, index */ var fill; /* index for replicating entries */ var low; /* low bits for current root entry */ var mask; /* mask for low root bits */ var next; /* next available space in table */ var base = null; /* base value table to use */ var base_index = 0; // var shoextra; /* extra bits table to use */ var end; /* use base and extra for symbol > end */ var count = new utils.Buf16(MAXBITS + 1); //[MAXBITS+1]; /* number of codes of each length */ var offs = new utils.Buf16(MAXBITS + 1); //[MAXBITS+1]; /* offsets in table for each length */ var extra = null; var extra_index = 0; var here_bits, here_op, here_val; /* Process a set of code lengths to create a canonical Huffman code. The code lengths are lens[0..codes-1]. Each length corresponds to the symbols 0..codes-1. The Huffman code is generated by first sorting the symbols by length from short to long, and retaining the symbol order for codes with equal lengths. Then the code starts with all zero bits for the first code of the shortest length, and the codes are integer increments for the same length, and zeros are appended as the length increases. For the deflate format, these bits are stored backwards from their more natural integer increment ordering, and so when the decoding tables are built in the large loop below, the integer codes are incremented backwards. This routine assumes, but does not check, that all of the entries in lens[] are in the range 0..MAXBITS. The caller must assure this. 1..MAXBITS is interpreted as that code length. zero means that that symbol does not occur in this code. The codes are sorted by computing a count of codes for each length, creating from that a table of starting indices for each length in the sorted table, and then entering the symbols in order in the sorted table. The sorted table is work[], with that space being provided by the caller. The length counts are used for other purposes as well, i.e. finding the minimum and maximum length codes, determining if there are any codes at all, checking for a valid set of lengths, and looking ahead at length counts to determine sub-table sizes when building the decoding tables. */ /* accumulate lengths for codes (assumes lens[] all in 0..MAXBITS) */ for (len = 0; len <= MAXBITS; len++) { count[len] = 0; } for (sym = 0; sym < codes; sym++) { count[lens[lens_index + sym]]++; } /* bound code lengths, force root to be within code lengths */ root = bits; for (max = MAXBITS; max >= 1; max--) { if (count[max] !== 0) { break; } } if (root > max) { root = max; } if (max === 0) { /* no symbols to code at all */ //table.op[opts.table_index] = 64; //here.op = (var char)64; /* invalid code marker */ //table.bits[opts.table_index] = 1; //here.bits = (var char)1; //table.val[opts.table_index++] = 0; //here.val = (var short)0; table[table_index++] = (1 << 24) | (64 << 16) | 0; //table.op[opts.table_index] = 64; //table.bits[opts.table_index] = 1; //table.val[opts.table_index++] = 0; table[table_index++] = (1 << 24) | (64 << 16) | 0; opts.bits = 1; return 0; /* no symbols, but wait for decoding to report error */ } for (min = 1; min < max; min++) { if (count[min] !== 0) { break; } } if (root < min) { root = min; } /* check for an over-subscribed or incomplete set of lengths */ left = 1; for (len = 1; len <= MAXBITS; len++) { left <<= 1; left -= count[len]; if (left < 0) { return -1; } /* over-subscribed */ } if (left > 0 && (type === CODES || max !== 1)) { return -1; /* incomplete set */ } /* generate offsets into symbol table for each length for sorting */ offs[1] = 0; for (len = 1; len < MAXBITS; len++) { offs[len + 1] = offs[len] + count[len]; } /* sort symbols by length, by symbol order within each length */ for (sym = 0; sym < codes; sym++) { if (lens[lens_index + sym] !== 0) { work[offs[lens[lens_index + sym]]++] = sym; } } /* Create and fill in decoding tables. In this loop, the table being filled is at next and has curr index bits. The code being used is huff with length len. That code is converted to an index by dropping drop bits off of the bottom. For codes where len is less than drop + curr, those top drop + curr - len bits are incremented through all values to fill the table with replicated entries. root is the number of index bits for the root table. When len exceeds root, sub-tables are created pointed to by the root entry with an index of the low root bits of huff. This is saved in low to check for when a new sub-table should be started. drop is zero when the root table is being filled, and drop is root when sub-tables are being filled. When a new sub-table is needed, it is necessary to look ahead in the code lengths to determine what size sub-table is needed. The length counts are used for this, and so count[] is decremented as codes are entered in the tables. used keeps track of how many table entries have been allocated from the provided *table space. It is checked for LENS and DIST tables against the constants ENOUGH_LENS and ENOUGH_DISTS to guard against changes in the initial root table size constants. See the comments in inftrees.h for more information. sym increments through all symbols, and the loop terminates when all codes of length max, i.e. all codes, have been processed. This routine permits incomplete codes, so another loop after this one fills in the rest of the decoding tables with invalid code markers. */ /* set up for code type */ // poor man optimization - use if-else instead of switch, // to avoid deopts in old v8 if (type === CODES) { base = extra = work; /* dummy value--not used */ end = 19; } else if (type === LENS) { base = lbase; base_index -= 257; extra = lext; extra_index -= 257; end = 256; } else { /* DISTS */ base = dbase; extra = dext; end = -1; } /* initialize opts for loop */ huff = 0; /* starting code */ sym = 0; /* starting code symbol */ len = min; /* starting code length */ next = table_index; /* current table to fill in */ curr = root; /* current table index bits */ drop = 0; /* current bits to drop from code for index */ low = -1; /* trigger new sub-table when len > root */ used = 1 << root; /* use root table entries */ mask = used - 1; /* mask for comparing low */ /* check available table space */ if ((type === LENS && used > ENOUGH_LENS) || (type === DISTS && used > ENOUGH_DISTS)) { return 1; } var i = 0; /* process all codes and make table entries */ for (;;) { i++; /* create table entry */ here_bits = len - drop; if (work[sym] < end) { here_op = 0; here_val = work[sym]; } else if (work[sym] > end) { here_op = extra[extra_index + work[sym]]; here_val = base[base_index + work[sym]]; } else { here_op = 32 + 64; /* end of block */ here_val = 0; } /* replicate for those indices with low len bits equal to huff */ incr = 1 << (len - drop); fill = 1 << curr; min = fill; /* save offset to next table */ do { fill -= incr; table[next + (huff >> drop) + fill] = (here_bits << 24) | (here_op << 16) | here_val |0; } while (fill !== 0); /* backwards increment the len-bit code huff */ incr = 1 << (len - 1); while (huff & incr) { incr >>= 1; } if (incr !== 0) { huff &= incr - 1; huff += incr; } else { huff = 0; } /* go to next symbol, update count, len */ sym++; if (--count[len] === 0) { if (len === max) { break; } len = lens[lens_index + work[sym]]; } /* create new sub-table if needed */ if (len > root && (huff & mask) !== low) { /* if first time, transition to sub-tables */ if (drop === 0) { drop = root; } /* increment past last table */ next += min; /* here min is 1 << curr */ /* determine length of next table */ curr = len - drop; left = 1 << curr; while (curr + drop < max) { left -= count[curr + drop]; if (left <= 0) { break; } curr++; left <<= 1; } /* check for enough space */ used += 1 << curr; if ((type === LENS && used > ENOUGH_LENS) || (type === DISTS && used > ENOUGH_DISTS)) { return 1; } /* point entry in root table to sub-table */ low = huff & mask; /*table.op[low] = curr; table.bits[low] = root; table.val[low] = next - opts.table_index;*/ table[low] = (root << 24) | (curr << 16) | (next - table_index) |0; } } /* fill in remaining table entry if code is incomplete (guaranteed to have at most one remaining entry, since if the code is incomplete, the maximum code length that was allowed to get this far is one bit) */ if (huff !== 0) { //table.op[next + huff] = 64; /* invalid code marker */ //table.bits[next + huff] = len - drop; //table.val[next + huff] = 0; table[next + huff] = ((len - drop) << 24) | (64 << 16) |0; } /* set return parameters */ //opts.table_index += used; opts.bits = root; return 0; }; },{"../utils/common":80}],90:[function(_dereq_,module,exports){ 'use strict'; module.exports = { 2: 'need dictionary', /* Z_NEED_DICT 2 */ 1: 'stream end', /* Z_STREAM_END 1 */ 0: '', /* Z_OK 0 */ '-1': 'file error', /* Z_ERRNO (-1) */ '-2': 'stream error', /* Z_STREAM_ERROR (-2) */ '-3': 'data error', /* Z_DATA_ERROR (-3) */ '-4': 'insufficient memory', /* Z_MEM_ERROR (-4) */ '-5': 'buffer error', /* Z_BUF_ERROR (-5) */ '-6': 'incompatible version' /* Z_VERSION_ERROR (-6) */ }; },{}],91:[function(_dereq_,module,exports){ 'use strict'; var utils = _dereq_('../utils/common'); /* Public constants ==========================================================*/ /* ===========================================================================*/ //var Z_FILTERED = 1; //var Z_HUFFMAN_ONLY = 2; //var Z_RLE = 3; var Z_FIXED = 4; //var Z_DEFAULT_STRATEGY = 0; /* Possible values of the data_type field (though see inflate()) */ var Z_BINARY = 0; var Z_TEXT = 1; //var Z_ASCII = 1; // = Z_TEXT var Z_UNKNOWN = 2; /*============================================================================*/ function zero(buf) { var len = buf.length; while (--len >= 0) { buf[len] = 0; } } // From zutil.h var STORED_BLOCK = 0; var STATIC_TREES = 1; var DYN_TREES = 2; /* The three kinds of block type */ var MIN_MATCH = 3; var MAX_MATCH = 258; /* The minimum and maximum match lengths */ // From deflate.h /* =========================================================================== * Internal compression state. */ var LENGTH_CODES = 29; /* number of length codes, not counting the special END_BLOCK code */ var LITERALS = 256; /* number of literal bytes 0..255 */ var L_CODES = LITERALS + 1 + LENGTH_CODES; /* number of Literal or Length codes, including the END_BLOCK code */ var D_CODES = 30; /* number of distance codes */ var BL_CODES = 19; /* number of codes used to transfer the bit lengths */ var HEAP_SIZE = 2 * L_CODES + 1; /* maximum heap size */ var MAX_BITS = 15; /* All codes must not exceed MAX_BITS bits */ var Buf_size = 16; /* size of bit buffer in bi_buf */ /* =========================================================================== * Constants */ var MAX_BL_BITS = 7; /* Bit length codes must not exceed MAX_BL_BITS bits */ var END_BLOCK = 256; /* end of block literal code */ var REP_3_6 = 16; /* repeat previous bit length 3-6 times (2 bits of repeat count) */ var REPZ_3_10 = 17; /* repeat a zero length 3-10 times (3 bits of repeat count) */ var REPZ_11_138 = 18; /* repeat a zero length 11-138 times (7 bits of repeat count) */ /* eslint-disable comma-spacing,array-bracket-spacing */ var extra_lbits = /* extra bits for each length code */ [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]; var extra_dbits = /* extra bits for each distance code */ [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]; var extra_blbits = /* extra bits for each bit length code */ [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7]; var bl_order = [16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]; /* eslint-enable comma-spacing,array-bracket-spacing */ /* The lengths of the bit length codes are sent in order of decreasing * probability, to avoid transmitting the lengths for unused bit length codes. */ /* =========================================================================== * Local data. These are initialized only once. */ // We pre-fill arrays with 0 to avoid uninitialized gaps var DIST_CODE_LEN = 512; /* see definition of array dist_code below */ // !!!! Use flat array insdead of structure, Freq = i*2, Len = i*2+1 var static_ltree = new Array((L_CODES + 2) * 2); zero(static_ltree); /* The static literal tree. Since the bit lengths are imposed, there is no * need for the L_CODES extra codes used during heap construction. However * The codes 286 and 287 are needed to build a canonical tree (see _tr_init * below). */ var static_dtree = new Array(D_CODES * 2); zero(static_dtree); /* The static distance tree. (Actually a trivial tree since all codes use * 5 bits.) */ var _dist_code = new Array(DIST_CODE_LEN); zero(_dist_code); /* Distance codes. The first 256 values correspond to the distances * 3 .. 258, the last 256 values correspond to the top 8 bits of * the 15 bit distances. */ var _length_code = new Array(MAX_MATCH - MIN_MATCH + 1); zero(_length_code); /* length code for each normalized match length (0 == MIN_MATCH) */ var base_length = new Array(LENGTH_CODES); zero(base_length); /* First normalized length for each code (0 = MIN_MATCH) */ var base_dist = new Array(D_CODES); zero(base_dist); /* First normalized distance for each code (0 = distance of 1) */ function StaticTreeDesc(static_tree, extra_bits, extra_base, elems, max_length) { this.static_tree = static_tree; /* static tree or NULL */ this.extra_bits = extra_bits; /* extra bits for each code or NULL */ this.extra_base = extra_base; /* base index for extra_bits */ this.elems = elems; /* max number of elements in the tree */ this.max_length = max_length; /* max bit length for the codes */ // show if `static_tree` has data or dummy - needed for monomorphic objects this.has_stree = static_tree && static_tree.length; } var static_l_desc; var static_d_desc; var static_bl_desc; function TreeDesc(dyn_tree, stat_desc) { this.dyn_tree = dyn_tree; /* the dynamic tree */ this.max_code = 0; /* largest code with non zero frequency */ this.stat_desc = stat_desc; /* the corresponding static tree */ } function d_code(dist) { return dist < 256 ? _dist_code[dist] : _dist_code[256 + (dist >>> 7)]; } /* =========================================================================== * Output a short LSB first on the stream. * IN assertion: there is enough room in pendingBuf. */ function put_short(s, w) { // put_byte(s, (uch)((w) & 0xff)); // put_byte(s, (uch)((ush)(w) >> 8)); s.pending_buf[s.pending++] = (w) & 0xff; s.pending_buf[s.pending++] = (w >>> 8) & 0xff; } /* =========================================================================== * Send a value on a given number of bits. * IN assertion: length <= 16 and value fits in length bits. */ function send_bits(s, value, length) { if (s.bi_valid > (Buf_size - length)) { s.bi_buf |= (value << s.bi_valid) & 0xffff; put_short(s, s.bi_buf); s.bi_buf = value >> (Buf_size - s.bi_valid); s.bi_valid += length - Buf_size; } else { s.bi_buf |= (value << s.bi_valid) & 0xffff; s.bi_valid += length; } } function send_code(s, c, tree) { send_bits(s, tree[c * 2]/*.Code*/, tree[c * 2 + 1]/*.Len*/); } /* =========================================================================== * Reverse the first len bits of a code, using straightforward code (a faster * method would use a table) * IN assertion: 1 <= len <= 15 */ function bi_reverse(code, len) { var res = 0; do { res |= code & 1; code >>>= 1; res <<= 1; } while (--len > 0); return res >>> 1; } /* =========================================================================== * Flush the bit buffer, keeping at most 7 bits in it. */ function bi_flush(s) { if (s.bi_valid === 16) { put_short(s, s.bi_buf); s.bi_buf = 0; s.bi_valid = 0; } else if (s.bi_valid >= 8) { s.pending_buf[s.pending++] = s.bi_buf & 0xff; s.bi_buf >>= 8; s.bi_valid -= 8; } } /* =========================================================================== * Compute the optimal bit lengths for a tree and update the total bit length * for the current block. * IN assertion: the fields freq and dad are set, heap[heap_max] and * above are the tree nodes sorted by increasing frequency. * OUT assertions: the field len is set to the optimal bit length, the * array bl_count contains the frequencies for each bit length. * The length opt_len is updated; static_len is also updated if stree is * not null. */ function gen_bitlen(s, desc) // deflate_state *s; // tree_desc *desc; /* the tree descriptor */ { var tree = desc.dyn_tree; var max_code = desc.max_code; var stree = desc.stat_desc.static_tree; var has_stree = desc.stat_desc.has_stree; var extra = desc.stat_desc.extra_bits; var base = desc.stat_desc.extra_base; var max_length = desc.stat_desc.max_length; var h; /* heap index */ var n, m; /* iterate over the tree elements */ var bits; /* bit length */ var xbits; /* extra bits */ var f; /* frequency */ var overflow = 0; /* number of elements with bit length too large */ for (bits = 0; bits <= MAX_BITS; bits++) { s.bl_count[bits] = 0; } /* In a first pass, compute the optimal bit lengths (which may * overflow in the case of the bit length tree). */ tree[s.heap[s.heap_max] * 2 + 1]/*.Len*/ = 0; /* root of the heap */ for (h = s.heap_max + 1; h < HEAP_SIZE; h++) { n = s.heap[h]; bits = tree[tree[n * 2 + 1]/*.Dad*/ * 2 + 1]/*.Len*/ + 1; if (bits > max_length) { bits = max_length; overflow++; } tree[n * 2 + 1]/*.Len*/ = bits; /* We overwrite tree[n].Dad which is no longer needed */ if (n > max_code) { continue; } /* not a leaf node */ s.bl_count[bits]++; xbits = 0; if (n >= base) { xbits = extra[n - base]; } f = tree[n * 2]/*.Freq*/; s.opt_len += f * (bits + xbits); if (has_stree) { s.static_len += f * (stree[n * 2 + 1]/*.Len*/ + xbits); } } if (overflow === 0) { return; } // Trace((stderr,"\nbit length overflow\n")); /* This happens for example on obj2 and pic of the Calgary corpus */ /* Find the first bit length which could increase: */ do { bits = max_length - 1; while (s.bl_count[bits] === 0) { bits--; } s.bl_count[bits]--; /* move one leaf down the tree */ s.bl_count[bits + 1] += 2; /* move one overflow item as its brother */ s.bl_count[max_length]--; /* The brother of the overflow item also moves one step up, * but this does not affect bl_count[max_length] */ overflow -= 2; } while (overflow > 0); /* Now recompute all bit lengths, scanning in increasing frequency. * h is still equal to HEAP_SIZE. (It is simpler to reconstruct all * lengths instead of fixing only the wrong ones. This idea is taken * from 'ar' written by Haruhiko Okumura.) */ for (bits = max_length; bits !== 0; bits--) { n = s.bl_count[bits]; while (n !== 0) { m = s.heap[--h]; if (m > max_code) { continue; } if (tree[m * 2 + 1]/*.Len*/ !== bits) { // Trace((stderr,"code %d bits %d->%d\n", m, tree[m].Len, bits)); s.opt_len += (bits - tree[m * 2 + 1]/*.Len*/) * tree[m * 2]/*.Freq*/; tree[m * 2 + 1]/*.Len*/ = bits; } n--; } } } /* =========================================================================== * Generate the codes for a given tree and bit counts (which need not be * optimal). * IN assertion: the array bl_count contains the bit length statistics for * the given tree and the field len is set for all tree elements. * OUT assertion: the field code is set for all tree elements of non * zero code length. */ function gen_codes(tree, max_code, bl_count) // ct_data *tree; /* the tree to decorate */ // int max_code; /* largest code with non zero frequency */ // ushf *bl_count; /* number of codes at each bit length */ { var next_code = new Array(MAX_BITS + 1); /* next code value for each bit length */ var code = 0; /* running code value */ var bits; /* bit index */ var n; /* code index */ /* The distribution counts are first used to generate the code values * without bit reversal. */ for (bits = 1; bits <= MAX_BITS; bits++) { next_code[bits] = code = (code + bl_count[bits - 1]) << 1; } /* Check that the bit counts in bl_count are consistent. The last code * must be all ones. */ //Assert (code + bl_count[MAX_BITS]-1 == (1<<MAX_BITS)-1, // "inconsistent bit counts"); //Tracev((stderr,"\ngen_codes: max_code %d ", max_code)); for (n = 0; n <= max_code; n++) { var len = tree[n * 2 + 1]/*.Len*/; if (len === 0) { continue; } /* Now reverse the bits */ tree[n * 2]/*.Code*/ = bi_reverse(next_code[len]++, len); //Tracecv(tree != static_ltree, (stderr,"\nn %3d %c l %2d c %4x (%x) ", // n, (isgraph(n) ? n : ' '), len, tree[n].Code, next_code[len]-1)); } } /* =========================================================================== * Initialize the various 'constant' tables. */ function tr_static_init() { var n; /* iterates over tree elements */ var bits; /* bit counter */ var length; /* length value */ var code; /* code value */ var dist; /* distance index */ var bl_count = new Array(MAX_BITS + 1); /* number of codes at each bit length for an optimal tree */ // do check in _tr_init() //if (static_init_done) return; /* For some embedded targets, global variables are not initialized: */ /*#ifdef NO_INIT_GLOBAL_POINTERS static_l_desc.static_tree = static_ltree; static_l_desc.extra_bits = extra_lbits; static_d_desc.static_tree = static_dtree; static_d_desc.extra_bits = extra_dbits; static_bl_desc.extra_bits = extra_blbits; #endif*/ /* Initialize the mapping length (0..255) -> length code (0..28) */ length = 0; for (code = 0; code < LENGTH_CODES - 1; code++) { base_length[code] = length; for (n = 0; n < (1 << extra_lbits[code]); n++) { _length_code[length++] = code; } } //Assert (length == 256, "tr_static_init: length != 256"); /* Note that the length 255 (match length 258) can be represented * in two different ways: code 284 + 5 bits or code 285, so we * overwrite length_code[255] to use the best encoding: */ _length_code[length - 1] = code; /* Initialize the mapping dist (0..32K) -> dist code (0..29) */ dist = 0; for (code = 0; code < 16; code++) { base_dist[code] = dist; for (n = 0; n < (1 << extra_dbits[code]); n++) { _dist_code[dist++] = code; } } //Assert (dist == 256, "tr_static_init: dist != 256"); dist >>= 7; /* from now on, all distances are divided by 128 */ for (; code < D_CODES; code++) { base_dist[code] = dist << 7; for (n = 0; n < (1 << (extra_dbits[code] - 7)); n++) { _dist_code[256 + dist++] = code; } } //Assert (dist == 256, "tr_static_init: 256+dist != 512"); /* Construct the codes of the static literal tree */ for (bits = 0; bits <= MAX_BITS; bits++) { bl_count[bits] = 0; } n = 0; while (n <= 143) { static_ltree[n * 2 + 1]/*.Len*/ = 8; n++; bl_count[8]++; } while (n <= 255) { static_ltree[n * 2 + 1]/*.Len*/ = 9; n++; bl_count[9]++; } while (n <= 279) { static_ltree[n * 2 + 1]/*.Len*/ = 7; n++; bl_count[7]++; } while (n <= 287) { static_ltree[n * 2 + 1]/*.Len*/ = 8; n++; bl_count[8]++; } /* Codes 286 and 287 do not exist, but we must include them in the * tree construction to get a canonical Huffman tree (longest code * all ones) */ gen_codes(static_ltree, L_CODES + 1, bl_count); /* The static distance tree is trivial: */ for (n = 0; n < D_CODES; n++) { static_dtree[n * 2 + 1]/*.Len*/ = 5; static_dtree[n * 2]/*.Code*/ = bi_reverse(n, 5); } // Now data ready and we can init static trees static_l_desc = new StaticTreeDesc(static_ltree, extra_lbits, LITERALS + 1, L_CODES, MAX_BITS); static_d_desc = new StaticTreeDesc(static_dtree, extra_dbits, 0, D_CODES, MAX_BITS); static_bl_desc = new StaticTreeDesc(new Array(0), extra_blbits, 0, BL_CODES, MAX_BL_BITS); //static_init_done = true; } /* =========================================================================== * Initialize a new block. */ function init_block(s) { var n; /* iterates over tree elements */ /* Initialize the trees. */ for (n = 0; n < L_CODES; n++) { s.dyn_ltree[n * 2]/*.Freq*/ = 0; } for (n = 0; n < D_CODES; n++) { s.dyn_dtree[n * 2]/*.Freq*/ = 0; } for (n = 0; n < BL_CODES; n++) { s.bl_tree[n * 2]/*.Freq*/ = 0; } s.dyn_ltree[END_BLOCK * 2]/*.Freq*/ = 1; s.opt_len = s.static_len = 0; s.last_lit = s.matches = 0; } /* =========================================================================== * Flush the bit buffer and align the output on a byte boundary */ function bi_windup(s) { if (s.bi_valid > 8) { put_short(s, s.bi_buf); } else if (s.bi_valid > 0) { //put_byte(s, (Byte)s->bi_buf); s.pending_buf[s.pending++] = s.bi_buf; } s.bi_buf = 0; s.bi_valid = 0; } /* =========================================================================== * Copy a stored block, storing first the length and its * one's complement if requested. */ function copy_block(s, buf, len, header) //DeflateState *s; //charf *buf; /* the input data */ //unsigned len; /* its length */ //int header; /* true if block header must be written */ { bi_windup(s); /* align on byte boundary */ if (header) { put_short(s, len); put_short(s, ~len); } // while (len--) { // put_byte(s, *buf++); // } utils.arraySet(s.pending_buf, s.window, buf, len, s.pending); s.pending += len; } /* =========================================================================== * Compares to subtrees, using the tree depth as tie breaker when * the subtrees have equal frequency. This minimizes the worst case length. */ function smaller(tree, n, m, depth) { var _n2 = n * 2; var _m2 = m * 2; return (tree[_n2]/*.Freq*/ < tree[_m2]/*.Freq*/ || (tree[_n2]/*.Freq*/ === tree[_m2]/*.Freq*/ && depth[n] <= depth[m])); } /* =========================================================================== * Restore the heap property by moving down the tree starting at node k, * exchanging a node with the smallest of its two sons if necessary, stopping * when the heap property is re-established (each father smaller than its * two sons). */ function pqdownheap(s, tree, k) // deflate_state *s; // ct_data *tree; /* the tree to restore */ // int k; /* node to move down */ { var v = s.heap[k]; var j = k << 1; /* left son of k */ while (j <= s.heap_len) { /* Set j to the smallest of the two sons: */ if (j < s.heap_len && smaller(tree, s.heap[j + 1], s.heap[j], s.depth)) { j++; } /* Exit if v is smaller than both sons */ if (smaller(tree, v, s.heap[j], s.depth)) { break; } /* Exchange v with the smallest son */ s.heap[k] = s.heap[j]; k = j; /* And continue down the tree, setting j to the left son of k */ j <<= 1; } s.heap[k] = v; } // inlined manually // var SMALLEST = 1; /* =========================================================================== * Send the block data compressed using the given Huffman trees */ function compress_block(s, ltree, dtree) // deflate_state *s; // const ct_data *ltree; /* literal tree */ // const ct_data *dtree; /* distance tree */ { var dist; /* distance of matched string */ var lc; /* match length or unmatched char (if dist == 0) */ var lx = 0; /* running index in l_buf */ var code; /* the code to send */ var extra; /* number of extra bits to send */ if (s.last_lit !== 0) { do { dist = (s.pending_buf[s.d_buf + lx * 2] << 8) | (s.pending_buf[s.d_buf + lx * 2 + 1]); lc = s.pending_buf[s.l_buf + lx]; lx++; if (dist === 0) { send_code(s, lc, ltree); /* send a literal byte */ //Tracecv(isgraph(lc), (stderr," '%c' ", lc)); } else { /* Here, lc is the match length - MIN_MATCH */ code = _length_code[lc]; send_code(s, code + LITERALS + 1, ltree); /* send the length code */ extra = extra_lbits[code]; if (extra !== 0) { lc -= base_length[code]; send_bits(s, lc, extra); /* send the extra length bits */ } dist--; /* dist is now the match distance - 1 */ code = d_code(dist); //Assert (code < D_CODES, "bad d_code"); send_code(s, code, dtree); /* send the distance code */ extra = extra_dbits[code]; if (extra !== 0) { dist -= base_dist[code]; send_bits(s, dist, extra); /* send the extra distance bits */ } } /* literal or match pair ? */ /* Check that the overlay between pending_buf and d_buf+l_buf is ok: */ //Assert((uInt)(s->pending) < s->lit_bufsize + 2*lx, // "pendingBuf overflow"); } while (lx < s.last_lit); } send_code(s, END_BLOCK, ltree); } /* =========================================================================== * Construct one Huffman tree and assigns the code bit strings and lengths. * Update the total bit length for the current block. * IN assertion: the field freq is set for all tree elements. * OUT assertions: the fields len and code are set to the optimal bit length * and corresponding code. The length opt_len is updated; static_len is * also updated if stree is not null. The field max_code is set. */ function build_tree(s, desc) // deflate_state *s; // tree_desc *desc; /* the tree descriptor */ { var tree = desc.dyn_tree; var stree = desc.stat_desc.static_tree; var has_stree = desc.stat_desc.has_stree; var elems = desc.stat_desc.elems; var n, m; /* iterate over heap elements */ var max_code = -1; /* largest code with non zero frequency */ var node; /* new node being created */ /* Construct the initial heap, with least frequent element in * heap[SMALLEST]. The sons of heap[n] are heap[2*n] and heap[2*n+1]. * heap[0] is not used. */ s.heap_len = 0; s.heap_max = HEAP_SIZE; for (n = 0; n < elems; n++) { if (tree[n * 2]/*.Freq*/ !== 0) { s.heap[++s.heap_len] = max_code = n; s.depth[n] = 0; } else { tree[n * 2 + 1]/*.Len*/ = 0; } } /* The pkzip format requires that at least one distance code exists, * and that at least one bit should be sent even if there is only one * possible code. So to avoid special checks later on we force at least * two codes of non zero frequency. */ while (s.heap_len < 2) { node = s.heap[++s.heap_len] = (max_code < 2 ? ++max_code : 0); tree[node * 2]/*.Freq*/ = 1; s.depth[node] = 0; s.opt_len--; if (has_stree) { s.static_len -= stree[node * 2 + 1]/*.Len*/; } /* node is 0 or 1 so it does not have extra bits */ } desc.max_code = max_code; /* The elements heap[heap_len/2+1 .. heap_len] are leaves of the tree, * establish sub-heaps of increasing lengths: */ for (n = (s.heap_len >> 1/*int /2*/); n >= 1; n--) { pqdownheap(s, tree, n); } /* Construct the Huffman tree by repeatedly combining the least two * frequent nodes. */ node = elems; /* next internal node of the tree */ do { //pqremove(s, tree, n); /* n = node of least frequency */ /*** pqremove ***/ n = s.heap[1/*SMALLEST*/]; s.heap[1/*SMALLEST*/] = s.heap[s.heap_len--]; pqdownheap(s, tree, 1/*SMALLEST*/); /***/ m = s.heap[1/*SMALLEST*/]; /* m = node of next least frequency */ s.heap[--s.heap_max] = n; /* keep the nodes sorted by frequency */ s.heap[--s.heap_max] = m; /* Create a new node father of n and m */ tree[node * 2]/*.Freq*/ = tree[n * 2]/*.Freq*/ + tree[m * 2]/*.Freq*/; s.depth[node] = (s.depth[n] >= s.depth[m] ? s.depth[n] : s.depth[m]) + 1; tree[n * 2 + 1]/*.Dad*/ = tree[m * 2 + 1]/*.Dad*/ = node; /* and insert the new node in the heap */ s.heap[1/*SMALLEST*/] = node++; pqdownheap(s, tree, 1/*SMALLEST*/); } while (s.heap_len >= 2); s.heap[--s.heap_max] = s.heap[1/*SMALLEST*/]; /* At this point, the fields freq and dad are set. We can now * generate the bit lengths. */ gen_bitlen(s, desc); /* The field len is now set, we can generate the bit codes */ gen_codes(tree, max_code, s.bl_count); } /* =========================================================================== * Scan a literal or distance tree to determine the frequencies of the codes * in the bit length tree. */ function scan_tree(s, tree, max_code) // deflate_state *s; // ct_data *tree; /* the tree to be scanned */ // int max_code; /* and its largest code of non zero frequency */ { var n; /* iterates over all tree elements */ var prevlen = -1; /* last emitted length */ var curlen; /* length of current code */ var nextlen = tree[0 * 2 + 1]/*.Len*/; /* length of next code */ var count = 0; /* repeat count of the current code */ var max_count = 7; /* max repeat count */ var min_count = 4; /* min repeat count */ if (nextlen === 0) { max_count = 138; min_count = 3; } tree[(max_code + 1) * 2 + 1]/*.Len*/ = 0xffff; /* guard */ for (n = 0; n <= max_code; n++) { curlen = nextlen; nextlen = tree[(n + 1) * 2 + 1]/*.Len*/; if (++count < max_count && curlen === nextlen) { continue; } else if (count < min_count) { s.bl_tree[curlen * 2]/*.Freq*/ += count; } else if (curlen !== 0) { if (curlen !== prevlen) { s.bl_tree[curlen * 2]/*.Freq*/++; } s.bl_tree[REP_3_6 * 2]/*.Freq*/++; } else if (count <= 10) { s.bl_tree[REPZ_3_10 * 2]/*.Freq*/++; } else { s.bl_tree[REPZ_11_138 * 2]/*.Freq*/++; } count = 0; prevlen = curlen; if (nextlen === 0) { max_count = 138; min_count = 3; } else if (curlen === nextlen) { max_count = 6; min_count = 3; } else { max_count = 7; min_count = 4; } } } /* =========================================================================== * Send a literal or distance tree in compressed form, using the codes in * bl_tree. */ function send_tree(s, tree, max_code) // deflate_state *s; // ct_data *tree; /* the tree to be scanned */ // int max_code; /* and its largest code of non zero frequency */ { var n; /* iterates over all tree elements */ var prevlen = -1; /* last emitted length */ var curlen; /* length of current code */ var nextlen = tree[0 * 2 + 1]/*.Len*/; /* length of next code */ var count = 0; /* repeat count of the current code */ var max_count = 7; /* max repeat count */ var min_count = 4; /* min repeat count */ /* tree[max_code+1].Len = -1; */ /* guard already set */ if (nextlen === 0) { max_count = 138; min_count = 3; } for (n = 0; n <= max_code; n++) { curlen = nextlen; nextlen = tree[(n + 1) * 2 + 1]/*.Len*/; if (++count < max_count && curlen === nextlen) { continue; } else if (count < min_count) { do { send_code(s, curlen, s.bl_tree); } while (--count !== 0); } else if (curlen !== 0) { if (curlen !== prevlen) { send_code(s, curlen, s.bl_tree); count--; } //Assert(count >= 3 && count <= 6, " 3_6?"); send_code(s, REP_3_6, s.bl_tree); send_bits(s, count - 3, 2); } else if (count <= 10) { send_code(s, REPZ_3_10, s.bl_tree); send_bits(s, count - 3, 3); } else { send_code(s, REPZ_11_138, s.bl_tree); send_bits(s, count - 11, 7); } count = 0; prevlen = curlen; if (nextlen === 0) { max_count = 138; min_count = 3; } else if (curlen === nextlen) { max_count = 6; min_count = 3; } else { max_count = 7; min_count = 4; } } } /* =========================================================================== * Construct the Huffman tree for the bit lengths and return the index in * bl_order of the last bit length code to send. */ function build_bl_tree(s) { var max_blindex; /* index of last bit length code of non zero freq */ /* Determine the bit length frequencies for literal and distance trees */ scan_tree(s, s.dyn_ltree, s.l_desc.max_code); scan_tree(s, s.dyn_dtree, s.d_desc.max_code); /* Build the bit length tree: */ build_tree(s, s.bl_desc); /* opt_len now includes the length of the tree representations, except * the lengths of the bit lengths codes and the 5+5+4 bits for the counts. */ /* Determine the number of bit length codes to send. The pkzip format * requires that at least 4 bit length codes be sent. (appnote.txt says * 3 but the actual value used is 4.) */ for (max_blindex = BL_CODES - 1; max_blindex >= 3; max_blindex--) { if (s.bl_tree[bl_order[max_blindex] * 2 + 1]/*.Len*/ !== 0) { break; } } /* Update opt_len to include the bit length tree and counts */ s.opt_len += 3 * (max_blindex + 1) + 5 + 5 + 4; //Tracev((stderr, "\ndyn trees: dyn %ld, stat %ld", // s->opt_len, s->static_len)); return max_blindex; } /* =========================================================================== * Send the header for a block using dynamic Huffman trees: the counts, the * lengths of the bit length codes, the literal tree and the distance tree. * IN assertion: lcodes >= 257, dcodes >= 1, blcodes >= 4. */ function send_all_trees(s, lcodes, dcodes, blcodes) // deflate_state *s; // int lcodes, dcodes, blcodes; /* number of codes for each tree */ { var rank; /* index in bl_order */ //Assert (lcodes >= 257 && dcodes >= 1 && blcodes >= 4, "not enough codes"); //Assert (lcodes <= L_CODES && dcodes <= D_CODES && blcodes <= BL_CODES, // "too many codes"); //Tracev((stderr, "\nbl counts: ")); send_bits(s, lcodes - 257, 5); /* not +255 as stated in appnote.txt */ send_bits(s, dcodes - 1, 5); send_bits(s, blcodes - 4, 4); /* not -3 as stated in appnote.txt */ for (rank = 0; rank < blcodes; rank++) { //Tracev((stderr, "\nbl code %2d ", bl_order[rank])); send_bits(s, s.bl_tree[bl_order[rank] * 2 + 1]/*.Len*/, 3); } //Tracev((stderr, "\nbl tree: sent %ld", s->bits_sent)); send_tree(s, s.dyn_ltree, lcodes - 1); /* literal tree */ //Tracev((stderr, "\nlit tree: sent %ld", s->bits_sent)); send_tree(s, s.dyn_dtree, dcodes - 1); /* distance tree */ //Tracev((stderr, "\ndist tree: sent %ld", s->bits_sent)); } /* =========================================================================== * Check if the data type is TEXT or BINARY, using the following algorithm: * - TEXT if the two conditions below are satisfied: * a) There are no non-portable control characters belonging to the * "black list" (0..6, 14..25, 28..31). * b) There is at least one printable character belonging to the * "white list" (9 {TAB}, 10 {LF}, 13 {CR}, 32..255). * - BINARY otherwise. * - The following partially-portable control characters form a * "gray list" that is ignored in this detection algorithm: * (7 {BEL}, 8 {BS}, 11 {VT}, 12 {FF}, 26 {SUB}, 27 {ESC}). * IN assertion: the fields Freq of dyn_ltree are set. */ function detect_data_type(s) { /* black_mask is the bit mask of black-listed bytes * set bits 0..6, 14..25, and 28..31 * 0xf3ffc07f = binary 11110011111111111100000001111111 */ var black_mask = 0xf3ffc07f; var n; /* Check for non-textual ("black-listed") bytes. */ for (n = 0; n <= 31; n++, black_mask >>>= 1) { if ((black_mask & 1) && (s.dyn_ltree[n * 2]/*.Freq*/ !== 0)) { return Z_BINARY; } } /* Check for textual ("white-listed") bytes. */ if (s.dyn_ltree[9 * 2]/*.Freq*/ !== 0 || s.dyn_ltree[10 * 2]/*.Freq*/ !== 0 || s.dyn_ltree[13 * 2]/*.Freq*/ !== 0) { return Z_TEXT; } for (n = 32; n < LITERALS; n++) { if (s.dyn_ltree[n * 2]/*.Freq*/ !== 0) { return Z_TEXT; } } /* There are no "black-listed" or "white-listed" bytes: * this stream either is empty or has tolerated ("gray-listed") bytes only. */ return Z_BINARY; } var static_init_done = false; /* =========================================================================== * Initialize the tree data structures for a new zlib stream. */ function _tr_init(s) { if (!static_init_done) { tr_static_init(); static_init_done = true; } s.l_desc = new TreeDesc(s.dyn_ltree, static_l_desc); s.d_desc = new TreeDesc(s.dyn_dtree, static_d_desc); s.bl_desc = new TreeDesc(s.bl_tree, static_bl_desc); s.bi_buf = 0; s.bi_valid = 0; /* Initialize the first block of the first file: */ init_block(s); } /* =========================================================================== * Send a stored block */ function _tr_stored_block(s, buf, stored_len, last) //DeflateState *s; //charf *buf; /* input block */ //ulg stored_len; /* length of input block */ //int last; /* one if this is the last block for a file */ { send_bits(s, (STORED_BLOCK << 1) + (last ? 1 : 0), 3); /* send block type */ copy_block(s, buf, stored_len, true); /* with header */ } /* =========================================================================== * Send one empty static block to give enough lookahead for inflate. * This takes 10 bits, of which 7 may remain in the bit buffer. */ function _tr_align(s) { send_bits(s, STATIC_TREES << 1, 3); send_code(s, END_BLOCK, static_ltree); bi_flush(s); } /* =========================================================================== * Determine the best encoding for the current block: dynamic trees, static * trees or store, and output the encoded block to the zip file. */ function _tr_flush_block(s, buf, stored_len, last) //DeflateState *s; //charf *buf; /* input block, or NULL if too old */ //ulg stored_len; /* length of input block */ //int last; /* one if this is the last block for a file */ { var opt_lenb, static_lenb; /* opt_len and static_len in bytes */ var max_blindex = 0; /* index of last bit length code of non zero freq */ /* Build the Huffman trees unless a stored block is forced */ if (s.level > 0) { /* Check if the file is binary or text */ if (s.strm.data_type === Z_UNKNOWN) { s.strm.data_type = detect_data_type(s); } /* Construct the literal and distance trees */ build_tree(s, s.l_desc); // Tracev((stderr, "\nlit data: dyn %ld, stat %ld", s->opt_len, // s->static_len)); build_tree(s, s.d_desc); // Tracev((stderr, "\ndist data: dyn %ld, stat %ld", s->opt_len, // s->static_len)); /* At this point, opt_len and static_len are the total bit lengths of * the compressed block data, excluding the tree representations. */ /* Build the bit length tree for the above two trees, and get the index * in bl_order of the last bit length code to send. */ max_blindex = build_bl_tree(s); /* Determine the best encoding. Compute the block lengths in bytes. */ opt_lenb = (s.opt_len + 3 + 7) >>> 3; static_lenb = (s.static_len + 3 + 7) >>> 3; // Tracev((stderr, "\nopt %lu(%lu) stat %lu(%lu) stored %lu lit %u ", // opt_lenb, s->opt_len, static_lenb, s->static_len, stored_len, // s->last_lit)); if (static_lenb <= opt_lenb) { opt_lenb = static_lenb; } } else { // Assert(buf != (char*)0, "lost buf"); opt_lenb = static_lenb = stored_len + 5; /* force a stored block */ } if ((stored_len + 4 <= opt_lenb) && (buf !== -1)) { /* 4: two words for the lengths */ /* The test buf != NULL is only necessary if LIT_BUFSIZE > WSIZE. * Otherwise we can't have processed more than WSIZE input bytes since * the last block flush, because compression would have been * successful. If LIT_BUFSIZE <= WSIZE, it is never too late to * transform a block into a stored block. */ _tr_stored_block(s, buf, stored_len, last); } else if (s.strategy === Z_FIXED || static_lenb === opt_lenb) { send_bits(s, (STATIC_TREES << 1) + (last ? 1 : 0), 3); compress_block(s, static_ltree, static_dtree); } else { send_bits(s, (DYN_TREES << 1) + (last ? 1 : 0), 3); send_all_trees(s, s.l_desc.max_code + 1, s.d_desc.max_code + 1, max_blindex + 1); compress_block(s, s.dyn_ltree, s.dyn_dtree); } // Assert (s->compressed_len == s->bits_sent, "bad compressed size"); /* The above check is made mod 2^32, for files larger than 512 MB * and uLong implemented on 32 bits. */ init_block(s); if (last) { bi_windup(s); } // Tracev((stderr,"\ncomprlen %lu(%lu) ", s->compressed_len>>3, // s->compressed_len-7*last)); } /* =========================================================================== * Save the match info and tally the frequency counts. Return true if * the current block must be flushed. */ function _tr_tally(s, dist, lc) // deflate_state *s; // unsigned dist; /* distance of matched string */ // unsigned lc; /* match length-MIN_MATCH or unmatched char (if dist==0) */ { //var out_length, in_length, dcode; s.pending_buf[s.d_buf + s.last_lit * 2] = (dist >>> 8) & 0xff; s.pending_buf[s.d_buf + s.last_lit * 2 + 1] = dist & 0xff; s.pending_buf[s.l_buf + s.last_lit] = lc & 0xff; s.last_lit++; if (dist === 0) { /* lc is the unmatched char */ s.dyn_ltree[lc * 2]/*.Freq*/++; } else { s.matches++; /* Here, lc is the match length - MIN_MATCH */ dist--; /* dist = match distance - 1 */ //Assert((ush)dist < (ush)MAX_DIST(s) && // (ush)lc <= (ush)(MAX_MATCH-MIN_MATCH) && // (ush)d_code(dist) < (ush)D_CODES, "_tr_tally: bad match"); s.dyn_ltree[(_length_code[lc] + LITERALS + 1) * 2]/*.Freq*/++; s.dyn_dtree[d_code(dist) * 2]/*.Freq*/++; } // (!) This block is disabled in zlib defailts, // don't enable it for binary compatibility //#ifdef TRUNCATE_BLOCK // /* Try to guess if it is profitable to stop the current block here */ // if ((s.last_lit & 0x1fff) === 0 && s.level > 2) { // /* Compute an upper bound for the compressed length */ // out_length = s.last_lit*8; // in_length = s.strstart - s.block_start; // // for (dcode = 0; dcode < D_CODES; dcode++) { // out_length += s.dyn_dtree[dcode*2]/*.Freq*/ * (5 + extra_dbits[dcode]); // } // out_length >>>= 3; // //Tracev((stderr,"\nlast_lit %u, in %ld, out ~%ld(%ld%%) ", // // s->last_lit, in_length, out_length, // // 100L - out_length*100L/in_length)); // if (s.matches < (s.last_lit>>1)/*int /2*/ && out_length < (in_length>>1)/*int /2*/) { // return true; // } // } //#endif return (s.last_lit === s.lit_bufsize - 1); /* We avoid equality with lit_bufsize because of wraparound at 64K * on 16 bit machines and because stored blocks are restricted to * 64K-1 bytes. */ } exports._tr_init = _tr_init; exports._tr_stored_block = _tr_stored_block; exports._tr_flush_block = _tr_flush_block; exports._tr_tally = _tr_tally; exports._tr_align = _tr_align; },{"../utils/common":80}],92:[function(_dereq_,module,exports){ 'use strict'; function ZStream() { /* next input byte */ this.input = null; // JS specific, because we have no pointers this.next_in = 0; /* number of bytes available at input */ this.avail_in = 0; /* total number of input bytes read so far */ this.total_in = 0; /* next output byte should be put there */ this.output = null; // JS specific, because we have no pointers this.next_out = 0; /* remaining free space at output */ this.avail_out = 0; /* total number of bytes output so far */ this.total_out = 0; /* last error message, NULL if no error */ this.msg = ''/*Z_NULL*/; /* not visible by applications */ this.state = null; /* best guess about the data type: binary or text */ this.data_type = 2/*Z_UNKNOWN*/; /* adler32 value of the uncompressed data */ this.adler = 0; } module.exports = ZStream; },{}],93:[function(_dereq_,module,exports){ // shim for using process in browser var process = module.exports = {}; var queue = []; var draining = false; var currentQueue; var queueIndex = -1; function cleanUpNextTick() { draining = false; if (currentQueue.length) { queue = currentQueue.concat(queue); } else { queueIndex = -1; } if (queue.length) { drainQueue(); } } function drainQueue() { if (draining) { return; } var timeout = setTimeout(cleanUpNextTick); draining = true; var len = queue.length; while(len) { currentQueue = queue; queue = []; while (++queueIndex < len) { if (currentQueue) { currentQueue[queueIndex].run(); } } queueIndex = -1; len = queue.length; } currentQueue = null; draining = false; clearTimeout(timeout); } process.nextTick = function (fun) { var args = new Array(arguments.length - 1); if (arguments.length > 1) { for (var i = 1; i < arguments.length; i++) { args[i - 1] = arguments[i]; } } queue.push(new Item(fun, args)); if (queue.length === 1 && !draining) { setTimeout(drainQueue, 0); } }; // v8 likes predictible objects function Item(fun, array) { this.fun = fun; this.array = array; } Item.prototype.run = function () { this.fun.apply(null, this.array); }; process.title = 'browser'; process.browser = true; process.env = {}; process.argv = []; process.version = ''; // empty string to avoid regexp issues process.versions = {}; function noop() {} process.on = noop; process.addListener = noop; process.once = noop; process.off = noop; process.removeListener = noop; process.removeAllListeners = noop; process.emit = noop; process.binding = function (name) { throw new Error('process.binding is not supported'); }; process.cwd = function () { return '/' }; process.chdir = function (dir) { throw new Error('process.chdir is not supported'); }; process.umask = function() { return 0; }; },{}],94:[function(_dereq_,module,exports){ 'use strict'; var asap = _dereq_('asap') module.exports = Promise function Promise(fn) { if (typeof this !== 'object') throw new TypeError('Promises must be constructed via new') if (typeof fn !== 'function') throw new TypeError('not a function') var state = null var value = null var deferreds = [] var self = this this.then = function(onFulfilled, onRejected) { return new Promise(function(resolve, reject) { handle(new Handler(onFulfilled, onRejected, resolve, reject)) }) } function handle(deferred) { if (state === null) { deferreds.push(deferred) return } asap(function() { var cb = state ? deferred.onFulfilled : deferred.onRejected if (cb === null) { (state ? deferred.resolve : deferred.reject)(value) return } var ret try { ret = cb(value) } catch (e) { deferred.reject(e) return } deferred.resolve(ret) }) } function resolve(newValue) { try { //Promise Resolution Procedure: https://github.com/promises-aplus/promises-spec#the-promise-resolution-procedure if (newValue === self) throw new TypeError('A promise cannot be resolved with itself.') if (newValue && (typeof newValue === 'object' || typeof newValue === 'function')) { var then = newValue.then if (typeof then === 'function') { doResolve(then.bind(newValue), resolve, reject) return } } state = true value = newValue finale() } catch (e) { reject(e) } } function reject(newValue) { state = false value = newValue finale() } function finale() { for (var i = 0, len = deferreds.length; i < len; i++) handle(deferreds[i]) deferreds = null } doResolve(fn, resolve, reject) } function Handler(onFulfilled, onRejected, resolve, reject){ this.onFulfilled = typeof onFulfilled === 'function' ? onFulfilled : null this.onRejected = typeof onRejected === 'function' ? onRejected : null this.resolve = resolve this.reject = reject } /** * Take a potentially misbehaving resolver function and make sure * onFulfilled and onRejected are only called once. * * Makes no guarantees about asynchrony. */ function doResolve(fn, onFulfilled, onRejected) { var done = false; try { fn(function (value) { if (done) return done = true onFulfilled(value) }, function (reason) { if (done) return done = true onRejected(reason) }) } catch (ex) { if (done) return done = true onRejected(ex) } } },{"asap":36}],95:[function(_dereq_,module,exports){ 'use strict'; //This file contains then/promise specific extensions to the core promise API var Promise = _dereq_('./core.js') var asap = _dereq_('asap') module.exports = Promise /* Static Functions */ function ValuePromise(value) { this.then = function (onFulfilled) { if (typeof onFulfilled !== 'function') return this return new Promise(function (resolve, reject) { asap(function () { try { resolve(onFulfilled(value)) } catch (ex) { reject(ex); } }) }) } } ValuePromise.prototype = Object.create(Promise.prototype) var TRUE = new ValuePromise(true) var FALSE = new ValuePromise(false) var NULL = new ValuePromise(null) var UNDEFINED = new ValuePromise(undefined) var ZERO = new ValuePromise(0) var EMPTYSTRING = new ValuePromise('') Promise.resolve = function (value) { if (value instanceof Promise) return value if (value === null) return NULL if (value === undefined) return UNDEFINED if (value === true) return TRUE if (value === false) return FALSE if (value === 0) return ZERO if (value === '') return EMPTYSTRING if (typeof value === 'object' || typeof value === 'function') { try { var then = value.then if (typeof then === 'function') { return new Promise(then.bind(value)) } } catch (ex) { return new Promise(function (resolve, reject) { reject(ex) }) } } return new ValuePromise(value) } Promise.from = Promise.cast = function (value) { var err = new Error('Promise.from and Promise.cast are deprecated, use Promise.resolve instead') err.name = 'Warning' console.warn(err.stack) return Promise.resolve(value) } Promise.denodeify = function (fn, argumentCount) { argumentCount = argumentCount || Infinity return function () { var self = this var args = Array.prototype.slice.call(arguments) return new Promise(function (resolve, reject) { while (args.length && args.length > argumentCount) { args.pop() } args.push(function (err, res) { if (err) reject(err) else resolve(res) }) fn.apply(self, args) }) } } Promise.nodeify = function (fn) { return function () { var args = Array.prototype.slice.call(arguments) var callback = typeof args[args.length - 1] === 'function' ? args.pop() : null try { return fn.apply(this, arguments).nodeify(callback) } catch (ex) { if (callback === null || typeof callback == 'undefined') { return new Promise(function (resolve, reject) { reject(ex) }) } else { asap(function () { callback(ex) }) } } } } Promise.all = function () { var calledWithArray = arguments.length === 1 && Array.isArray(arguments[0]) var args = Array.prototype.slice.call(calledWithArray ? arguments[0] : arguments) if (!calledWithArray) { var err = new Error('Promise.all should be called with a single array, calling it with multiple arguments is deprecated') err.name = 'Warning' console.warn(err.stack) } return new Promise(function (resolve, reject) { if (args.length === 0) return resolve([]) var remaining = args.length function res(i, val) { try { if (val && (typeof val === 'object' || typeof val === 'function')) { var then = val.then if (typeof then === 'function') { then.call(val, function (val) { res(i, val) }, reject) return } } args[i] = val if (--remaining === 0) { resolve(args); } } catch (ex) { reject(ex) } } for (var i = 0; i < args.length; i++) { res(i, args[i]) } }) } Promise.reject = function (value) { return new Promise(function (resolve, reject) { reject(value); }); } Promise.race = function (values) { return new Promise(function (resolve, reject) { values.forEach(function(value){ Promise.resolve(value).then(resolve, reject); }) }); } /* Prototype Methods */ Promise.prototype.done = function (onFulfilled, onRejected) { var self = arguments.length ? this.then.apply(this, arguments) : this self.then(null, function (err) { asap(function () { throw err }) }) } Promise.prototype.nodeify = function (callback) { if (typeof callback != 'function') return this this.then(function (value) { asap(function () { callback(null, value) }) }, function (err) { asap(function () { callback(err) }) }) } Promise.prototype['catch'] = function (onRejected) { return this.then(null, onRejected); } },{"./core.js":94,"asap":36}]},{},[1]);
socket/src/socket.js
pixelgrade/starter_content_exporter
import React from 'react' import ReactDOM from 'react-dom' import SocketDashboard from './components/dashboard.js' ReactDOM.render(<SocketDashboard/>, document.getElementById('socket_dashboard'))
ajax/libs/yui/3.7.0pr1/datatable-body/datatable-body-debug.js
bspaulding/cdnjs
YUI.add('datatable-body', function(Y) { /** View class responsible for rendering the `<tbody>` section of a table. Used as the default `bodyView` for `Y.DataTable.Base` and `Y.DataTable` classes. @module datatable @submodule datatable-body @since 3.5.0 **/ var Lang = Y.Lang, isArray = Lang.isArray, isNumber = Lang.isNumber, isString = Lang.isString, fromTemplate = Lang.sub, htmlEscape = Y.Escape.html, toArray = Y.Array, bind = Y.bind, YObject = Y.Object; /** View class responsible for rendering the `<tbody>` section of a table. Used as the default `bodyView` for `Y.DataTable.Base` and `Y.DataTable` classes. Translates the provided `modelList` into a rendered `<tbody>` based on the data in the constituent Models, altered or ammended by any special column configurations. The `columns` configuration, passed to the constructor, determines which columns will be rendered. The rendering process involves constructing an HTML template for a complete row of data, built by concatenating a customized copy of the instance's `CELL_TEMPLATE` into the `ROW_TEMPLATE` once for each column. This template is then populated with values from each Model in the `modelList`, aggregating a complete HTML string of all row and column data. A `<tbody>` Node is then created from the markup and any column `nodeFormatter`s are applied. Supported properties of the column objects include: * `key` - Used to link a column to an attribute in a Model. * `name` - Used for columns that don't relate to an attribute in the Model (`formatter` or `nodeFormatter` only) if the implementer wants a predictable name to refer to in their CSS. * `cellTemplate` - Overrides the instance's `CELL_TEMPLATE` for cells in this column only. * `formatter` - Used to customize or override the content value from the Model. These do not have access to the cell or row Nodes and should return string (HTML) content. * `nodeFormatter` - Used to provide content for a cell as well as perform any custom modifications on the cell or row Node that could not be performed by `formatter`s. Should be used sparingly for better performance. * `emptyCellValue` - String (HTML) value to use if the Model data for a column, or the content generated by a `formatter`, is the empty string, `null`, or `undefined`. * `allowHTML` - Set to `true` if a column value, `formatter`, or `emptyCellValue` can contain HTML. This defaults to `false` to protect against XSS. * `className` - Space delimited CSS classes to add to all `<td>`s in a column. Column `formatter`s are passed an object (`o`) with the following properties: * `value` - The current value of the column's associated attribute, if any. * `data` - An object map of Model keys to their current values. * `record` - The Model instance. * `column` - The column configuration object for the current column. * `className` - Initially empty string to allow `formatter`s to add CSS classes to the cell's `<td>`. * `rowIndex` - The zero-based row number. * `rowClass` - Initially empty string to allow `formatter`s to add CSS classes to the cell's containing row `<tr>`. They may return a value or update `o.value` to assign specific HTML content. A returned value has higher precedence. Column `nodeFormatter`s are passed an object (`o`) with the following properties: * `value` - The current value of the column's associated attribute, if any. * `td` - The `<td>` Node instance. * `cell` - The `<div>` liner Node instance if present, otherwise, the `<td>`. When adding content to the cell, prefer appending into this property. * `data` - An object map of Model keys to their current values. * `record` - The Model instance. * `column` - The column configuration object for the current column. * `rowIndex` - The zero-based row number. They are expected to inject content into the cell's Node directly, including any "empty" cell content. Each `nodeFormatter` will have access through the Node API to all cells and rows in the `<tbody>`, but not to the `<table>`, as it will not be attached yet. If a `nodeFormatter` returns `false`, the `o.td` and `o.cell` Nodes will be `destroy()`ed to remove them from the Node cache and free up memory. The DOM elements will remain as will any content added to them. _It is highly advisable to always return `false` from your `nodeFormatter`s_. @class BodyView @namespace DataTable @extends View @since 3.5.0 **/ Y.namespace('DataTable').BodyView = Y.Base.create('tableBody', Y.View, [], { // -- Instance properties ------------------------------------------------- /** HTML template used to create table cells. @property CELL_TEMPLATE @type {HTML} @default '<td {headers} class="{className}">{content}</td>' @since 3.5.0 **/ CELL_TEMPLATE: '<td {headers} class="{className}">{content}</td>', /** CSS class applied to even rows. This is assigned at instantiation. For DataTable, this will be `yui3-datatable-even`. @property CLASS_EVEN @type {String} @default 'yui3-table-even' @since 3.5.0 **/ //CLASS_EVEN: null /** CSS class applied to odd rows. This is assigned at instantiation. When used by DataTable instances, this will be `yui3-datatable-odd`. @property CLASS_ODD @type {String} @default 'yui3-table-odd' @since 3.5.0 **/ //CLASS_ODD: null /** HTML template used to create table rows. @property ROW_TEMPLATE @type {HTML} @default '<tr id="{rowId}" data-yui3-record="{clientId}" class="{rowClass}">{content}</tr>' @since 3.5.0 **/ ROW_TEMPLATE : '<tr id="{rowId}" data-yui3-record="{clientId}" class="{rowClass}">{content}</tr>', /** The object that serves as the source of truth for column and row data. This property is assigned at instantiation from the `host` property of the configuration object passed to the constructor. @property host @type {Object} @default (initially unset) @since 3.5.0 **/ //TODO: should this be protected? //host: null, /** HTML templates used to create the `<tbody>` containing the table rows. @property TBODY_TEMPLATE @type {HTML} @default '<tbody class="{className}">{content}</tbody>' @since 3.6.0 **/ TBODY_TEMPLATE: '<tbody class="{className}"></tbody>', // -- Public methods ------------------------------------------------------ /** Returns the `<td>` Node from the given row and column index. Alternately, the `seed` can be a Node. If so, the nearest ancestor cell is returned. If the `seed` is a cell, it is returned. If there is no cell at the given coordinates, `null` is returned. Optionally, include an offset array or string to return a cell near the cell identified by the `seed`. The offset can be an array containing the number of rows to shift followed by the number of columns to shift, or one of "above", "below", "next", or "previous". <pre><code>// Previous cell in the previous row var cell = table.getCell(e.target, [-1, -1]); // Next cell var cell = table.getCell(e.target, 'next'); var cell = table.getCell(e.taregt, [0, 1];</pre></code> @method getCell @param {Number[]|Node} seed Array of row and column indexes, or a Node that is either the cell itself or a descendant of one. @param {Number[]|String} [shift] Offset by which to identify the returned cell Node @return {Node} @since 3.5.0 **/ getCell: function (seed, shift) { var tbody = this.tbodyNode, row, cell, index, rowIndexOffset; if (seed && tbody) { if (isArray(seed)) { row = tbody.get('children').item(seed[0]); cell = row && row.get('children').item(seed[1]); } else if (Y.instanceOf(seed, Y.Node)) { cell = seed.ancestor('.' + this.getClassName('cell'), true); } if (cell && shift) { rowIndexOffset = tbody.get('firstChild.rowIndex'); if (isString(shift)) { // TODO this should be a static object map switch (shift) { case 'above' : shift = [-1, 0]; break; case 'below' : shift = [1, 0]; break; case 'next' : shift = [0, 1]; break; case 'previous': shift = [0, -1]; break; } } if (isArray(shift)) { index = cell.get('parentNode.rowIndex') + shift[0] - rowIndexOffset; row = tbody.get('children').item(index); index = cell.get('cellIndex') + shift[1]; cell = row && row.get('children').item(index); } } } return cell || null; }, /** Returns the generated CSS classname based on the input. If the `host` attribute is configured, it will attempt to relay to its `getClassName` or use its static `NAME` property as a string base. If `host` is absent or has neither method nor `NAME`, a CSS classname will be generated using this class's `NAME`. @method getClassName @param {String} token* Any number of token strings to assemble the classname from. @return {String} @protected @since 3.5.0 **/ getClassName: function () { var host = this.host, args; if (host && host.getClassName) { return host.getClassName.apply(host, arguments); } else { args = toArray(arguments); args.unshift(this.constructor.NAME); return Y.ClassNameManager.getClassName .apply(Y.ClassNameManager, args); } }, /** Returns the Model associated to the row Node or id provided. Passing the Node or id for a descendant of the row also works. If no Model can be found, `null` is returned. @method getRecord @param {String|Node} seed Row Node or `id`, or one for a descendant of a row @return {Model} @since 3.5.0 **/ getRecord: function (seed) { var modelList = this.get('modelList'), tbody = this.tbodyNode, row = null, record; if (tbody) { if (isString(seed)) { seed = tbody.one('#' + seed); } if (Y.instanceOf(seed, Y.Node)) { row = seed.ancestor(function (node) { return node.get('parentNode').compareTo(tbody); }, true); record = row && modelList.getByClientId(row.getData('yui3-record')); } } return record || null; }, /** Returns the `<tr>` Node from the given row index, Model, or Model's `clientId`. If the rows haven't been rendered yet, or if the row can't be found by the input, `null` is returned. @method getRow @param {Number|String|Model} id Row index, Model instance, or clientId @return {Node} @since 3.5.0 **/ getRow: function (id) { var tbody = this.tbodyNode, row = null; if (tbody) { if (id) { id = this._idMap[id.get ? id.get('clientId') : id] || id; } row = isNumber(id) ? tbody.get('children').item(id) : tbody.one('#' + id); } return row; }, /** Creates the table's `<tbody>` content by assembling markup generated by populating the `ROW\_TEMPLATE`, and `CELL\_TEMPLATE` templates with content from the `columns` and `modelList` attributes. The rendering process happens in three stages: 1. A row template is assembled from the `columns` attribute (see `_createRowTemplate`) 2. An HTML string is built up by concatening the application of the data in each Model in the `modelList` to the row template. For cells with `formatter`s, the function is called to generate cell content. Cells with `nodeFormatter`s are ignored. For all other cells, the data value from the Model attribute for the given column key is used. The accumulated row markup is then inserted into the container. 3. If any column is configured with a `nodeFormatter`, the `modelList` is iterated again to apply the `nodeFormatter`s. Supported properties of the column objects include: * `key` - Used to link a column to an attribute in a Model. * `name` - Used for columns that don't relate to an attribute in the Model (`formatter` or `nodeFormatter` only) if the implementer wants a predictable name to refer to in their CSS. * `cellTemplate` - Overrides the instance's `CELL_TEMPLATE` for cells in this column only. * `formatter` - Used to customize or override the content value from the Model. These do not have access to the cell or row Nodes and should return string (HTML) content. * `nodeFormatter` - Used to provide content for a cell as well as perform any custom modifications on the cell or row Node that could not be performed by `formatter`s. Should be used sparingly for better performance. * `emptyCellValue` - String (HTML) value to use if the Model data for a column, or the content generated by a `formatter`, is the empty string, `null`, or `undefined`. * `allowHTML` - Set to `true` if a column value, `formatter`, or `emptyCellValue` can contain HTML. This defaults to `false` to protect against XSS. * `className` - Space delimited CSS classes to add to all `<td>`s in a column. Column `formatter`s are passed an object (`o`) with the following properties: * `value` - The current value of the column's associated attribute, if any. * `data` - An object map of Model keys to their current values. * `record` - The Model instance. * `column` - The column configuration object for the current column. * `className` - Initially empty string to allow `formatter`s to add CSS classes to the cell's `<td>`. * `rowIndex` - The zero-based row number. * `rowClass` - Initially empty string to allow `formatter`s to add CSS classes to the cell's containing row `<tr>`. They may return a value or update `o.value` to assign specific HTML content. A returned value has higher precedence. Column `nodeFormatter`s are passed an object (`o`) with the following properties: * `value` - The current value of the column's associated attribute, if any. * `td` - The `<td>` Node instance. * `cell` - The `<div>` liner Node instance if present, otherwise, the `<td>`. When adding content to the cell, prefer appending into this property. * `data` - An object map of Model keys to their current values. * `record` - The Model instance. * `column` - The column configuration object for the current column. * `rowIndex` - The zero-based row number. They are expected to inject content into the cell's Node directly, including any "empty" cell content. Each `nodeFormatter` will have access through the Node API to all cells and rows in the `<tbody>`, but not to the `<table>`, as it will not be attached yet. If a `nodeFormatter` returns `false`, the `o.td` and `o.cell` Nodes will be `destroy()`ed to remove them from the Node cache and free up memory. The DOM elements will remain as will any content added to them. _It is highly advisable to always return `false` from your `nodeFormatter`s_. @method render @return {BodyView} The instance @chainable @since 3.5.0 **/ render: function () { var table = this.get('container'), data = this.get('modelList'), columns = this.get('columns'), tbody = this.tbodyNode || (this.tbodyNode = this._createTBodyNode()); // Needed for mutation this._createRowTemplate(columns); if (data) { tbody.setHTML(this._createDataHTML(columns)); this._applyNodeFormatters(tbody, columns); } if (tbody.get('parentNode') !== table) { table.appendChild(tbody); } this.bindUI(); return this; }, // -- Protected and private methods --------------------------------------- /** Handles changes in the source's columns attribute. Redraws the table data. @method _afterColumnsChange @param {EventFacade} e The `columnsChange` event object @protected @since 3.5.0 **/ // TODO: Preserve existing DOM // This will involve parsing and comparing the old and new column configs // and reacting to four types of changes: // 1. formatter, nodeFormatter, emptyCellValue changes // 2. column deletions // 3. column additions // 4. column moves (preserve cells) _afterColumnsChange: function (e) { this.render(); }, /** Handles modelList changes, including additions, deletions, and updates. Modifies the existing table DOM accordingly. @method _afterDataChange @param {EventFacade} e The `change` event from the ModelList @protected @since 3.5.0 **/ _afterDataChange: function (e) { //var type = e.type.slice(e.type.lastIndexOf(':') + 1); // TODO: Isolate changes this.render(); }, /** Handles replacement of the modelList. Rerenders the `<tbody>` contents. @method _afterModelListChange @param {EventFacade} e The `modelListChange` event @protected @since 3.6.0 **/ _afterModelListChange: function (e) { var handles = this._eventHandles; if (handles.dataChange) { handles.dataChange.detach(); delete handles.dataChange; this.bindUI(); } if (this.tbodyNode) { this.render(); } }, /** Iterates the `modelList`, and calls any `nodeFormatter`s found in the `columns` param on the appropriate cell Nodes in the `tbody`. @method _applyNodeFormatters @param {Node} tbody The `<tbody>` Node whose columns to update @param {Object[]} columns The column configurations @protected @since 3.5.0 **/ _applyNodeFormatters: function (tbody, columns) { var host = this.host, data = this.get('modelList'), formatters = [], linerQuery = '.' + this.getClassName('liner'), rows, i, len; // Only iterate the ModelList again if there are nodeFormatters for (i = 0, len = columns.length; i < len; ++i) { if (columns[i].nodeFormatter) { formatters.push(i); } } if (data && formatters.length) { rows = tbody.get('childNodes'); data.each(function (record, index) { var formatterData = { data : record.toJSON(), record : record, rowIndex : index }, row = rows.item(index), i, len, col, key, cells, cell, keep; if (row) { cells = row.get('childNodes'); for (i = 0, len = formatters.length; i < len; ++i) { cell = cells.item(formatters[i]); if (cell) { col = formatterData.column = columns[formatters[i]]; key = col.key || col.id; formatterData.value = record.get(key); formatterData.td = cell; formatterData.cell = cell.one(linerQuery) || cell; keep = col.nodeFormatter.call(host,formatterData); if (keep === false) { // Remove from the Node cache to reduce // memory footprint. This also purges events, // which you shouldn't be scoping to a cell // anyway. You've been warned. Incidentally, // you should always return false. Just sayin. cell.destroy(true); } } } } }); } }, /** Binds event subscriptions from the UI and the host (if assigned). @method bindUI @protected @since 3.5.0 **/ bindUI: function () { var handles = this._eventHandles, modelList = this.get('modelList'), changeEvent = modelList.model.NAME + ':change'; if (!handles.columnsChange) { handles.columnsChange = this.after('columnsChange', bind('_afterColumnsChange', this)); } if (modelList && !handles.dataChange) { handles.dataChange = modelList.after( ['add', 'remove', 'reset', changeEvent], bind('_afterDataChange', this)); } }, /** Iterates the `modelList` and applies each Model to the `_rowTemplate`, allowing any column `formatter` or `emptyCellValue` to override cell content for the appropriate column. The aggregated HTML string is returned. @method _createDataHTML @param {Object[]} columns The column configurations to customize the generated cell content or class names @return {HTML} The markup for all Models in the `modelList`, each applied to the `_rowTemplate` @protected @since 3.5.0 **/ _createDataHTML: function (columns) { var data = this.get('modelList'), html = ''; if (data) { data.each(function (model, index) { html += this._createRowHTML(model, index, columns); }, this); } return html; }, /** Applies the data of a given Model, modified by any column formatters and supplemented by other template values to the instance's `_rowTemplate` (see `_createRowTemplate`). The generated string is then returned. The data from Model's attributes is fetched by `toJSON` and this data object is appended with other properties to supply values to {placeholders} in the template. For a template generated from a Model with 'foo' and 'bar' attributes, the data object would end up with the following properties before being used to populate the `_rowTemplate`: * `clientID` - From Model, used the assign the `<tr>`'s 'id' attribute. * `foo` - The value to populate the 'foo' column cell content. This value will be the value stored in the Model's `foo` attribute, or the result of the column's `formatter` if assigned. If the value is '', `null`, or `undefined`, and the column's `emptyCellValue` is assigned, that value will be used. * `bar` - Same for the 'bar' column cell content. * `foo-className` - String of CSS classes to apply to the `<td>`. * `bar-className` - Same. * `rowClass` - String of CSS classes to apply to the `<tr>`. This will be the odd/even class per the specified index plus any additional classes assigned by column formatters (via `o.rowClass`). Because this object is available to formatters, any additional properties can be added to fill in custom {placeholders} in the `_rowTemplate`. @method _createRowHTML @param {Model} model The Model instance to apply to the row template @param {Number} index The index the row will be appearing @param {Object[]} columns The column configurations @return {HTML} The markup for the provided Model, less any `nodeFormatter`s @protected @since 3.5.0 **/ _createRowHTML: function (model, index, columns) { var data = model.toJSON(), clientId = model.get('clientId'), values = { rowId : this._getRowId(clientId), clientId: clientId, rowClass: (index % 2) ? this.CLASS_ODD : this.CLASS_EVEN }, host = this.host || this, i, len, col, token, value, formatterData; for (i = 0, len = columns.length; i < len; ++i) { col = columns[i]; value = data[col.key]; token = col._id || col.key; values[token + '-className'] = ''; if (col.formatter) { formatterData = { value : value, data : data, column : col, record : model, className: '', rowClass : '', rowIndex : index }; if (typeof col.formatter === 'string') { if (value !== undefined) { // TODO: look for known formatters by string name value = fromTemplate(col.formatter, formatterData); } } else { // Formatters can either return a value value = col.formatter.call(host, formatterData); // or update the value property of the data obj passed if (value === undefined) { value = formatterData.value; } values[token + '-className'] = formatterData.className; values.rowClass += ' ' + formatterData.rowClass; } } if (value === undefined || value === null || value === '') { value = col.emptyCellValue || ''; } values[token] = col.allowHTML ? value : htmlEscape(value); values.rowClass = values.rowClass.replace(/\s+/g, ' '); } return fromTemplate(this._rowTemplate, values); }, /** Creates a custom HTML template string for use in generating the markup for individual table rows with {placeholder}s to capture data from the Models in the `modelList` attribute or from column `formatter`s. Assigns the `_rowTemplate` property. @method _createRowTemplate @param {Object[]} columns Array of column configuration objects @protected @since 3.5.0 **/ _createRowTemplate: function (columns) { var html = '', cellTemplate = this.CELL_TEMPLATE, i, len, col, key, token, headers, tokenValues; for (i = 0, len = columns.length; i < len; ++i) { col = columns[i]; key = col.key; token = col._id || key; // Only include headers if there are more than one headers = (col._headers || []).length > 1 ? 'headers="' + col._headers.join(' ') + '"' : ''; tokenValues = { content : '{' + token + '}', headers : headers, className: this.getClassName('col', token) + ' ' + (col.className || '') + ' ' + this.getClassName('cell') + ' {' + token + '-className}' }; if (col.nodeFormatter) { // Defer all node decoration to the formatter tokenValues.content = ''; } html += fromTemplate(col.cellTemplate || cellTemplate, tokenValues); } this._rowTemplate = fromTemplate(this.ROW_TEMPLATE, { content: html }); }, /** Creates the `<tbody>` node that will store the data rows. @method _createTBodyNode @return {Node} @protected @since 3.6.0 **/ _createTBodyNode: function () { return Y.Node.create(fromTemplate(this.TBODY_TEMPLATE, { className: this.getClassName('data') })); }, /** Destroys the instance. @method destructor @protected @since 3.5.0 **/ destructor: function () { (new Y.EventHandle(YObject.values(this._eventHandles))).detach(); }, /** Holds the event subscriptions needing to be detached when the instance is `destroy()`ed. @property _eventHandles @type {Object} @default undefined (initially unset) @protected @since 3.5.0 **/ //_eventHandles: null, /** Returns the row ID associated with a Model's clientId. @method _getRowId @param {String} clientId The Model clientId @return {String} @protected **/ _getRowId: function (clientId) { return this._idMap[clientId] || (this._idMap[clientId] = Y.guid()); }, /** Map of Model clientIds to row ids. @property _idMap @type {Object} @protected **/ //_idMap, /** Initializes the instance. Reads the following configuration properties in addition to the instance attributes: * `columns` - (REQUIRED) The initial column information * `host` - The object to serve as source of truth for column info and for generating class names @method initializer @param {Object} config Configuration data @protected @since 3.5.0 **/ initializer: function (config) { this.host = config.host; this._eventHandles = { modelListChange: this.after('modelListChange', bind('_afterModelListChange', this)) }; this._idMap = {}; this.CLASS_ODD = this.getClassName('odd'); this.CLASS_EVEN = this.getClassName('even'); } /** The HTML template used to create a full row of markup for a single Model in the `modelList` plus any customizations defined in the column configurations. @property _rowTemplate @type {HTML} @default (initially unset) @protected @since 3.5.0 **/ //_rowTemplate: null }); }, '@VERSION@' ,{requires:['datatable-core', 'view', 'classnamemanager']});
server/game/cards/characters/03/eddardstark.js
cavnak/throneteki
const DrawCard = require('../../../drawcard.js'); class EddardStark extends DrawCard { setupCardAbilities() { this.reaction({ when: { onRenown: (event, challenge, card) => card === this }, handler: () => { this.game.promptForSelect(this.controller, { cardCondition: card => this.cardCondition(this.game.currentChallenge, card), activePromptTitle: 'Select character to gain power', waitingPromptTitle: 'Waiting for opponent to use ' + this.name, onSelect: (player, card) => this.onCardSelected(player, card) }); } }); } cardCondition(challenge, card) { return card !== this && card.getType() === 'character' && challenge.isParticipating(card); } onCardSelected(player, card) { if(this.isBlank() || this.controller !== player) { return; } card.modifyPower(1); this.game.addMessage('{0} uses {1} to allow {2} to gain 1 power', player, this, card); return true; } } EddardStark.code = '03003'; module.exports = EddardStark;
src/components/LoadingButton.js
codevinsky/deep-ellum-jukebox-ui
import React from 'react'; import { Button } from 'react-bootstrap'; class LoadingButton extends React.Component { constructor(...args) { super(...args); this.state = {isLoading: false} } render() { let isLoading = this.state.isLoading; let style = this.props.bsStyle || 'default'; let loadingText = this.props.loadingText; return ( <Button bsStyle={style} disabled={isLoading} onClick={!isLoading ? this.handleClick : null}> {isLoading ? loadingText : this.props.children} </Button> ); } } export default LoadingButton;
components/Search/SearchResultsPanel/SpellcheckPanel.js
slidewiki/slidewiki-platform
import React from 'react'; class SpellcheckPanel extends React.Component { handleLink(suggestion, event){ event.preventDefault(); this.props.handleRedirect({ keywords: suggestion }); } renderSpellcheckCollations(){ if(this.props.spellcheckData.length === 0) return; // get the first suggestion const suggestion = this.props.spellcheckData[0]; return <h4>Do you mean <a href="#" key={suggestion} onClick={this.handleLink.bind(this, suggestion)}>{suggestion}</a>?</h4>; } render() { return ( <div ref="spellcheckDiv" className="ui grid"> <div className="column"> {this.renderSpellcheckCollations()} </div> </div> ); } } export default SpellcheckPanel;
src/components/Footer.js
angeloocana/angeloocana
import React from 'react'; import PropTypes from 'prop-types'; import Gravatar from 'react-gravatar'; import HeartIcon from './HeartIcon'; import FaGithub from 'react-icons/lib/fa/github'; import A from './A'; import styled from 'styled-components'; import Ca from './flags/Ca'; const Link = styled(A)` display: inline-block; padding-top: ${({theme}) => theme.scale(6)}; padding-bottom: ${({theme}) => theme.scale(7)}; padding-right: ${({theme}) => theme.scale(0)}; padding-left: ${({theme}) => theme.scale(0)}; margin: 0; line-height: 1.5; border-radius: ${props => props.theme.borderRadius}; transition: 0.3s; &:hover { background-color: ${props => props.theme.colors.blackShades[0]}; transition: 0.3s; } `; const FooterSection = styled.section` text-align: center; span { font-weight: bold; } `; const ProfilePicture = styled(Gravatar)` display: block; margin: auto; border-radius: 50%; margin-bottom: 1rem; `; const GithubIcon = styled(FaGithub)` font-size: ${({ theme }) => theme.scale(4)}; display: inline-block; margin: auto; margin: 0; padding: 0 ${({ theme }) => theme.scale(-6)} 0 0; `; const HomeCountryIcon = styled(Ca)` top: -0.1rem; position: relative; font-size: ${({ theme }) => theme.scale(2)}; margin-left: ${({ theme }) => theme.scale(-6)}; `; const getGitHubMsg = () => { return { en: ( <p> <GithubIcon /> <span>OPEN SOURCE</span>! </p> ), pt: ( <p> <GithubIcon /> <span>OPEN SOURCE</span>! </p> ), fr: ( <p> <GithubIcon /> <span>SOURCE OUVERTE</span>! </p> ) }; }; const getCreatedBy = (author) => { const profilePicture = (<ProfilePicture email={author.email} alt={author.name} width={60} height={60} />); return { en: ( <FooterSection> <Link href={author.defaultLink} target="_blank"> {profilePicture} {'Built with '} <HeartIcon /> {' by '} <span>{author.name}</span> {' who lives in '} <span>{author.homeCity}</span> <HomeCountryIcon /> </Link> </FooterSection> ), pt: ( <FooterSection> <Link href={author.defaultLink} target="_blank"> {profilePicture} {'Criado com '} <HeartIcon /> {' por '} <span>{author.name}</span> {' que mora em '} <span>{author.homeCity}</span> <HomeCountryIcon /> </Link> </FooterSection> ), fr: ( <FooterSection> <Link href={author.defaultLink} target="_blank"> {profilePicture} {'Créé avec '} <HeartIcon /> {' par '} <span>{author.name}</span> {' qui vit à '} <span>{author.homeCity}</span> <HomeCountryIcon /> </Link> </FooterSection> ) }; }; const Footer = ({ author, sourceCodeLink, currentLangKey }) => { return ( <footer> {getCreatedBy(author)[currentLangKey]} <FooterSection> <Link href={sourceCodeLink} target="_blank"> {getGitHubMsg()[currentLangKey]} </Link> </FooterSection> </footer> ); }; Footer.propTypes = { author: PropTypes.object.isRequired, sourceCodeLink: PropTypes.string.isRequired, currentLangKey: PropTypes.string }; export default Footer;
dev/js/containers/AlertBox.js
celsom3/Cosecha-SMS
import React, { Component } from 'react'; import { bindActionCreators } from 'redux'; import { connect } from 'react-redux'; import { onShowMessage, showAlert, closeAlert } from '../actions/index'; class AlertBox extends Component { visibilityClass( x='' ){ if (this.props.alerts.displayed) { return 'alert-box-open'; } else if ( x === 'init' ) { return 'alert-box-init'; } else { return 'alert-box-closed'; } } closeAlert(){ this.props.closeAlert(); } render() { return ( <div className={this.visibilityClass('init')}> <p> <a className="close-box" onClick={this.closeAlert.bind(this)} href="#" > X </a> </p> {this.props.alerts.alertMessage} </div> ) } } function mapStateToProps(state) { return { alerts: state.alerts, userInput: state.userInput } } function matchDispatchToProps(dispatch){ return bindActionCreators( { onShowMessage: onShowMessage, showAlert: showAlert, closeAlert: closeAlert }, dispatch ); } export default connect(mapStateToProps, matchDispatchToProps)(AlertBox);
src/components/video_detail.js
andrit/VideoListReact
import React from 'react'; const VideoDetail = ({video}) => { if(!video){ return <div>Hang on a minute, Loading...</div>; } const videoId = video.id.videoId; const url = `https://www.youtube.com/embed/${videoId}`; return( <div className="video-detail col-md-8"> <div className="embed-responsive embed-responsive-16by9"> <iframe src={url} className="embed-responsive-item"></iframe> </div> <div className="details"> <h2>{video.snippet.title}</h2> <div>{video.snippet.description}</div> </div> </div> ) } export default VideoDetail;